Metaprogramming and class_eval

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

Pedro Del G.

Email : [email protected]

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

Explanation: When you’re invoking my_attr_accessor from within the class
def
of MyNewClass, ‘self’ is the class object MyNewClass (an instance of
Class).
You need to call class_eval on this object. When the block passed into
class_eval is executed, ‘self’ is again the class object MyNewClass.
This is
what allows you to access the private ‘attr_accessor’ method.

Mushfeq.

On Mar 11, 7:41 pm, “Mushfeq K.” [email protected] wrote:

end
end

You are already where you need to be…

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

T.