如何为欧姆对象动态设置字段?
class OhmObj < Ohm::Model attribute :foo attribute :bar attribute :baz def add att, val self[att] = val end end class OtherObj def initialize @ohm_obj = OhmObj.create end def set att, val @ohm_obj[att] = val #doesn't work @ohm_obj.add(att, val) #doesn't work end end
中的attributeclassOhm::Model方法为命名属性定义访问器和更改器方法:
attribute
Ohm::Model
def self.attribute(name) define_method(name) do read_local(name) end define_method(:"#{name}=") do |value| write_local(name, value) end attributes << name unless attributes.include?(name) end
因此,当您说时attribute :foo,您可以免费获得以下方法:
attribute :foo
def foo # Returns the value of foo. def foo=(value) # Assigns a value to foo.
您可以send像这样调用mutator方法:
send
@ohm_obj.send((att + '=').to_sym, val)
如果您真的想说,@ohm_obj[att] = val那么可以在OhmObj课堂上添加以下内容:
@ohm_obj[att] = val
OhmObj
def []=(att, value) send((att + '=').to_sym, val) end
您可能还希望访问器版本保持对称:
def [](att) send(att.to_sym) end