2012-08-09 28 views
1

行,所以我想聲明,將接受PARAMS這樣我如何接受紅寶石上的這些參數?

比方說,我的方法是custom_method名爲

的方法
@variable.custom_method(Profile, :as => @user) 

我的方法應該抓住變量@user並調用@user.profile

但我怎麼捕獲第二個參數,這是一個散列

+0

在方法簽名中聲明一個參數? – 2012-08-09 23:19:27

回答

2

更簡單的解決方案可能是:

def custom_method(association, args) 
    obj = args[:as] or fail("Missing argument :as => obj") 
    obj.send(association.name.underscore) 
    ... 
end 

更豐富的函數調用,但缺點很明顯:方法簽名會丟失信息。

+0

如何在 – Trace 2012-08-09 23:21:43

+0

內執行@ user.profile是否有執行命令 – Trace 2012-08-09 23:22:09

+2

您可以使用.send(method_name)方法。像這樣使用它:@ user.send(「profile」)或@ user.send(:profile) – Andrei 2012-08-10 01:41:32