Ruby:如何动态创建attr_accessor

时间:2017-08-21 12:11:18

标签: ruby attributes attr-accessor

我想知道如何动态创建attr_accessor。是否可以做类似的事情:

attr_accessor "@#{key}" 

在initialize方法中?

module Mymodule
  def initialize(parameters = {})
    parameters.each do |key, value|
      instance_variable_set("@#{key}", value) unless value.nil?
    end
  end
end

class Myclass
  include Mymodule
end

clazz = Myclass.new attr1: "Arg1", attr2: "Arg2", attr3: "Arg3"
  # => #<Myclass:0x43f6050 @attr1="Arg1", @attr2="Arg2", @attr3="Arg3">

clazz.attr1
  # !> NoMethodError: undefined method `attr1' for #<Myclass:0x43f6050 @attr1="Arg1", @attr2="Arg2", @attr3="Arg3">

clazz.attr1="ATTR1"
  # !> NoMethodError: undefined method `attr1=' for #<Myclass:0x43f6050 @attr1="Arg1", @attr2="Arg2", @attr3="Arg3">

1 个答案:

答案 0 :(得分:6)

您可以通过在该实例的单例类上调用attr_accessor来定义每个实例访问者。

class Structy
  def initialize(parameters = {})
    parameters.each do |key, value|
      singleton_class.send :attr_accessor, key
      instance_variable_set "@#{key}", value
    end
  end
end