Metaprogramming in Ruby

From PeformIQ Upgrade
Revision as of 14:24, 14 May 2012 by PeterHarding (talk | contribs) (Created page with " =Reimplement attr_accessor= <pre> #!/usr/bin/env ruby module Accessor def my_attr_accessor(name) STDERR.print "#{name}\n" ivar_name = "@#{name}" define...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Reimplement attr_accessor

#!/usr/bin/env ruby

module Accessor
   def my_attr_accessor(name)
      STDERR.print "#{name}\n"
      ivar_name = "@#{name}"
      define_method(name) do
        STDERR.print "Get #{name}\n"
        instance_variable_get(ivar_name)
      end
      define_method("#{name}=") do |val|
        STDERR.print "Set #{name} = #{val}\n"
        instance_variable_set(ivar_name, val)
      end
   end
end

class Example
   extend Accessor
   my_attr_accessor :var
   my_attr_accessor :tst
end

ex = Example.new

ex.var = 99

puts ex.var


ex.tst = 2

puts ex.tst

Caegory:Metaprogramming