在 Ohm/Redis 中设置动态字段 [英] Setting a dynamic field in Ohm / Redis

查看:49
本文介绍了在 Ohm/Redis 中设置动态字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

来自 Ohm::Modelattribute 类方法定义了命名属性的访问器和修改器方法:

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

所以当你说 attribute :foo 时,你可以免费获得这些方法:

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.

您可以使用 send 像这样调用 mutator 方法:

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

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

如果你真的想说 @ohm_obj[att] = val 那么你可以在你的 OhmObj 类中添加如下内容:

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

这篇关于在 Ohm/Redis 中设置动态字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆