在运行时将类实例变量和attr_reader添加到Ruby类?

时间:2010-12-26 17:51:44

标签: ruby metaprogramming class-instance-variables

如何在运行时添加类实例变量,数据和attr_reader?

class Module
  def additional_data member, data
    self.class.send(:define_method, member)  {
      p "Added method #{member} to #{name}"
    }
  end
end

例如,给定此类

class Test
  additional_data :status, 55
end

现在我可以致电:

p Test.status # => prints 55

2 个答案:

答案 0 :(得分:4)

Module#class_eval就是你想要的:

def add_status(cls)
  cls.class_eval do
    attr_reader :status
  end
end

add_status(Test)

答案 1 :(得分:4)

这个怎么样?

class Object
  def self.additional_data(name, value)
    ivar_name = "@#{name}"

    instance_variable_set(ivar_name, value)

    self.class.send(:define_method, name) do
      instance_variable_get(ivar_name)
    end

    self.class.send(:define_method, "#{name}=") do |new_value|
      instance_variable_set(ivar_name, new_value)
    end
  end
end

class Foo
  additional_data :bar, 'baz'
end

puts Foo.bar # => 'baz'
Foo.bar = 'quux'
puts Foo.bar # => 'quux'

这是不言自明的,但如果您有任何问题,请告诉我。