Setting a dynamic field in Ohm / Redis

社会主义新天地 提交于 2019-12-10 11:18:31

问题


How do I set a field dynamically for a Ohm object?

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

回答1:


The attribute class method from Ohm::Model defines accessor and mutator methods for the named attribute:

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

So when you say attribute :foo, you get these methods for free:

def foo         # Returns the value of foo.
def foo=(value) # Assigns a value to foo.

You could use send to call the mutator method like this:

@ohm_obj.send((att + '=').to_sym, val)

If you really want to say @ohm_obj[att] = val then you could add something like the following to your OhmObj class:

def []=(att, value)
    send((att + '=').to_sym, val)
end

And you'd probably want the accessor version as well to maintain symmetry:

def [](att)
    send(att.to_sym)
end



回答2:


[] and []= as a dynamic attribute accessor and mutator are defined by default in Ohm::Model in Ohm 0.2.



来源:https://stackoverflow.com/questions/6638375/setting-a-dynamic-field-in-ohm-redis

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!