2014-04-01 34 views
0

如何將符號參數傳遞給實例的屬性?如何將符號傳遞給實例的屬性?

<%= image_input_and_display(f, :footer, '1140 x 104 pixels') %> 

def image_input_and_display(f, symbol, hint) 
    f.input symbol, hint: hint 
    if @user.symbol.exists? 
    ... 
    end 
end 

我試圖讓函數運行,在這種情況下,if @user.footer.exists?。任何線索?

回答

2

在這種情況下,當你知道它的名字時,你想執行一個方法,所以Object#send就是你想要的。 send按名稱運行方法。

@user.send(symbol).exists? 

只是受到警告,這允許訪問該對象上的所有方法。這會做什麼?

image_input_and_display(f, :destroy, '1140 x 104 pixels') 

答案?一些非常糟糕的東西。它看起來好像只是訪問一個屬性,但它可能正在做一些你沒有想到的事情。只是要小心:)

+0

啊!很簡單。謝謝。 –

+0

也很好的建議。它只是訪問一個屬性,但這真的很值得注意。 –

1

不知道我明白你到底在問什麼,但它聽起來像一個動態的方法調用。 Object implements send。你可以撥打@user.send(symbol)