Attr_accessor初始化值

今天在写接口的时候想attr_accessor初始化值,查了好像没有现成的吧。

1
2
3
4
5
6
7
8
9
10
def Foo
  @fields.each do |field_key,field_attr|
    define_method("#{field_key}=") do |value|
      instance_variable_set "@#{field_key}", self.class.type_value(field_attr,value)
    end
    define_method("#{field_key}") do
      instance_variable_set  "@#{field_key}", self.class.type_value(field_attr)
    end
  end
end

然后发现实例方法被nil重写,看了许久发现问题。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
define_method("#{field_key}") do
   instance_variable_get("@#{field_key}") ||
      (instance_variable_set  "@#{field_key}", self.class.type_value(field_attr) )
   end
end


class Cat
  # The below method could be defined in Module directly
  def self.defaulted_attributes(attributes)
    attributes.each do |attr, default|
      attr_writer attr

      define_method(attr) do
        instance_variable_get("@#{attr}") ||
          instance_variable_set("@#{attr}", default)
      end
    end
  end

  defaulted_attributes :amount_of_feet => 4
end

calin = Cat.new
print "calin had #{calin.amount_of_feet} feet... "
calin.amount_of_feet -= 1
puts "but I cut one of them, he now has #{calin.amount_of_feet}"

参考: How to initialize ‘attr_accessor’ attribute values? http://stackoverflow.com/questions/7081477/how-to-initialize-attr-accessor-attribute-values

原文地址:http://dlj.bz/khwZ8H

Comments