2011-07-10 56 views
2

如何爲歐姆對象動態設置字段?在歐姆/ 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 

回答

3

attribute class method from Ohm::Model定義爲命名屬性訪問器和mutator方法:

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來調用像這樣的增變器方法:

@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 
+0

'to_sym'是多餘的。 – tribalvibes

0

[][]=作爲動態屬性存取器和增變器默認定義在Ohm :: Model in Ohm 0.2中。

相關問題