【问题标题】:Setting a dynamic field in Ohm / Redis在 Ohm / Redis 中设置动态字段
【发布时间】:2011-10-02 01:48:40
【问题描述】:

如何为 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

【问题讨论】:

    标签: ruby redis ohm


    【解决方案1】:

    attribute class method from Ohm::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
    

    【讨论】:

      【解决方案2】:

      [][]= 作为动态属性访问器和修改器在 Ohm 0.2 的 Ohm::Model 中默认定义。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-03-24
        • 1970-01-01
        • 2018-04-25
        • 2013-08-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多