如何为Ohm对象动态设置字段?
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
答案 0 :(得分:3)
attribute
class method from Ohm::Model
定义了命名属性的访问器和mutator方法:
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
时,你可以免费获得这些方法:
def foo # Returns the value of foo.
def foo=(value) # Assigns a value to foo.
您可以使用send
来调用mutator方法,如下所示:
@ohm_obj.send((att + '=').to_sym, val)
如果您真的想说@ohm_obj[att] = val
,那么您可以在OhmObj
课程中添加以下内容:
def []=(att, value)
send((att + '=').to_sym, val)
end
你可能也希望访问器版本保持对称性:
def [](att)
send(att.to_sym)
end
答案 1 :(得分:0)
[]
和[]=
作为动态属性访问器和mutator默认定义为Ohm :: Model in Ohm 0.2。