2012-11-15 68 views
0

我一直在尋找一個多小時的互聯網,我找不到任何關於這個。導軌類而不是開關

我的網站,目前這些數據創建過濾器由一個case語句

class MyClass 
    attr_accessor :attribute 
    def self.function(value) 
     query = case value 
     when "open" then "Open" 
     ... 
     end 
     where(:attribute => query) 
    end 
end 

由於各種原因處理(即動態的而不是硬編碼的過濾器)我想營造一個模型這與一個getter和setter,但我不能得到這個工作

我的新功能:

def self.function(value) 
    Attribute.name = value 
    where(:attribute => Attribute.name) 
end 

我的新模式:

class Attribute 
    attr_accessor :name 
end 

並且測試:

it "should set the attribute to 'hello'" do 
    MyClass.function("hello") 
    Attribute.name.should eql "hello" 
end 

給出一個錯誤:

Failure/Error: Myclass.function("hallo") 
NoMethodError: 
    undefined method `name=' for Attribute:Class 

任何幫助,將理解

回答

1

這是因爲attr_accessor被限定實例方法(即:方法在Attribute的一個實例上工作),並嘗試將它用作類方法(即:Attribute.name)。

你可以重寫你的函數是這樣的:

def self.function(value) 
    attribute = Attribute.new 
    attribute.name = value 
    where(:attribute => attribute.name) 
end 
+0

它固定的錯誤,但現在返回屬性。有時間來解決問題。 – Michael

+0

謝謝你的幫助! – Michael