Forum: Ruby Metaprogramming and class_eval

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
F09383a4b8725aa99cf892813608de76?d=identicon&s=25 Pedro Del gallego (pedro)
on 2007-03-11 23:25
(Received via mailing list)
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 Gallego

Email              :   pedro.delgallego@gmail.com
74886c14aa167f34d39145d75c0b971c?d=identicon&s=25 Mushfeq Khan (Guest)
on 2007-03-12 00:42
(Received via mailing list)
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.
45196398e9685000d195ec626d477f0e?d=identicon&s=25 Trans (Guest)
on 2007-03-12 04:28
(Received via mailing list)
On Mar 11, 7:41 pm, "Mushfeq Khan" <mushfeq.k...@gmail.com> wrote:
>  end
> end


You are already where you need to be...

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

T.
This topic is locked and can not be replied to.