2011-06-08 87 views
1

在一個rails應用程序中,我有一個稱爲Record的模型的許多屬性。我想要設計一種方法,在屬性上調用時返回屬性的名稱(實際上它是Record對象上的一個方法)。然後這個名字被傳遞給一個哈希,它返回一個數字(爲了這個例子,說這個數字是一個百分比,然後乘以原始屬性值得到一個new value)。爲文字哈希查詢獲取Ruby方法的名稱

例如,假設我的Record具有四個屬性:teachers,students,principalsparents。然後,該方法將如下所示:

def name 
    **something here** 
end 

和相應的new_value方法和PRECENTAGE哈希是這樣的:

def new_value 
    self * PERCENTAGE[self.name] 
end 

PERCENTAGE = { 
    "teachers" => 0.40, 
    "students" => 0.53, 
    "principals" => 0.21, 
    "parents" => 0.87 
} 

然後,執行這件事,我會做Record.students.new_value,這會根據哈希中獲得的百分比返回新的學生數量。

我知道,讓當前正在執行的方法的名稱,你可以做這樣的事情:(上http://ryat.la/7RDk找到)

def this_method 
    __method__ 
end 

但不會爲我工作,因爲我需要以前的名稱執行的方法。

如果您對完成目標的替代方法有任何建議,我很樂意嘗試其他方法。

+0

你能發表一個你想要的方法調用會是什麼樣子的例子嗎?令人困惑的部分(對我來說)就是你說你在屬性上調用方法的地方。你的意思是'Record.students.some_method'或'some_method(Record.students)'?或者是其他東西? – Larsenal 2011-06-08 17:45:42

+0

在上面的代碼中,我使用前者,並將自己傳遞給哈希。這個例子看起來像'Record.students.new_value',它會返回'self * PERCENTAGE [self.name]'。後面的選項也可以。 (編輯的問題 - 抱歉的混亂!) – 2011-06-08 17:50:10

回答

2

瑞安,我掙扎,明白你的問題,但我認爲這是你想要的,爲record.teachers_percent,例如:

["teachers", "students", "principals", "parents"].each do |attrib| 
    Record.class_eval <<-RUBY 
    def #{attrib}_percent 
     #{attrib} * PERCENTAGE[#{attrib.inspect}] 
    end 
    RUBY 
end 

雖然這可能是一個清潔的解決方案,讓record.percent(:teachers)record.percent("teachers")

class Record 
    def percent(attrib) 
    self.send(attrib) * PERCENTAGE[attrib.to_s] 
    end 
end 
+0

第二個肯定是要走的路 - 這正是我想要的。謝謝Ben! – 2011-06-08 18:01:53