Metaprogramming and class_eval

P

Pedro Del Gallego

Hi

Whats the differents between this three classes. Why the
my_attr_accesor dosent create getters and setter clases.


Thanks in advance

#----------------------------------------------------------------------
#
#----------------------------------------------------------------------

class Class
def my_attr_accessor( *args )
args.each do |name|
self.class.class_eval do
attr_accessor :"#{name}"
end
end
end
end
=> nil

class MyNewClass
my_attr_accessor :id, :diagram, :telegram
end
=> [:id, :diagram, :telegram]

class MyClass
attr_accessor :id, :diagram, :telegram
end
=> nil

class Another_class
def initialize
["id","diagram","telegram"].each do |name|
self.class.class_eval do
attr_accessor :"#{name}"
end
end
end
end
=> nil

mnc = MyNewClass.new
=> #<MyNewClass:0xb7b97d0c>
mc = MyClass.new
=> #<MyClass:0xb7b950fc>
ac = Another_class.new
=> #<Another_class:0xb7b82358>

ac.diagram
=> nil
mc.diagram
 
T

Trans

Hi,

You seem to have an extra .class in your modification to Class. You can get
away with this:

class Class
def my_attr_accessor( *args )
self.class_eval do
attr_accessor *args
end
end
end


You are already where you need to be...

class Class
def my_attr_accessor( *args )
attr_accessor *args
end
end

T.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,969
Messages
2,570,161
Members
46,710
Latest member
bernietqt

Latest Threads

Top