How to define a attribute using metaprogramming.

Just for fun and learning. We can add an attribute using meta-programming :

class MyClass
   attr_accessor    :id, :diagram, :telegram
end

We can define a custom function :

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

class MyNewClass
  my_attr_accessor :id, :diagram, :telegram
end

We can create a set of attributes using class_eval :

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

Or more ruby idiomatic

class Yet_another_class
  def initialize
    self.class.class_eval do
        attr_accessor *[:id,:diagram,:telegram]
    end
  end
end
Advertisements

No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: