开发者

Setting a dynamic field in Ohm / Redis

开发者 https://www.devze.com 2023-03-19 07:24 出处:网络
How do I set a field dynamically for a Ohm object? class OhmObj < Ohm::Model attribute :foo attribute :bar

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
  开发者_StackOverflow社区end

  def set att, val
    @ohm_obj[att] = val #doesn't work
    @ohm_obj.add(att, val) #doesn't work
  end 
end


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号