小编典典

在Ohm / Redis中设置动态字段

redis

如何为欧姆对象动态设置字段?

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

阅读 274

收藏
2020-06-20

共1个答案

小编典典

中的attributeclassOhm::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,您可以免费获得以下方法:

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
2020-06-20