2012-07-01 96 views
0

我試圖根據包含對象名稱的字符串訪問對象。該對象是作用域的(我使用cancan來確保用戶只能訪問允許訪問的記錄)。我已經包含在其中,我有以下一些代碼:Rails從包含對象名稱的字符串訪問對象

operation_type:string, one of %w(add sub mult div) 
left_operand_object:string 
left_operand:string 
right_operand_object:string 
right_operand:string 


def result 
    r = [access object using left_operand_object] 
    k = [access object using right_operand_object] 

    if operation_type == 'add' 
     r.instance_variable_get('@'+left_operand) + k.instance_variable_get('@'+left_operand) 
    elsif operation_type == 'sub' 
     r.instance_variable_get('@'+left_operand) - k.instance_variable_get('@'+left_operand) 
    ... 
end 

於是,兩個問題:

  • 我怎樣才能完成r = [access object using left_operand_object]線,讓我根據訪問範圍的對象的姓名字符串left_operand_object
  • instance_variable_get工作,如果left_operandcustomers.count或者它只會工作沒有計數方法?

任何幫助非常感謝!

回答

1

我理解正確嗎,left_operand_object會是類似"Customer"

如果是這樣,您可以使用left_operand_object.constantize來獲得您的Customer類。
可能更安全地運行left_operand_object.classify.constantize,因此"row_entry"將變爲RowEntry

我不完全清楚你的第二個問題是關於什麼的。如果你想調用count方法,你可以做r.send(left_operand.to_sym)(假設`left_operand =「count」)。

如果left_operand就像「sales.count」,這是行不通的。我不知道是否有一種慣用的方式來做到這一點,但left_operand.split(".").inject(r) { |a, b| a.send b }做這個特殊情況下的伎倆。


+0

是的,你理解正確 - left_operand_object會像「客戶」。感謝您的信息,我會考慮使用constantize - 我認爲這將分配對象到r變量,如預期的那樣? –

+0

我認爲第二個問題有點不清楚 - 我問我是否可以使用instance_variable_get中的count方法作爲整數返回count,但我認爲你的答案給了我需要去的方向 - left_operand會是像「sales.count」(假設我試圖使用customer.sales.count)。 –

+0

我編輯了我的答案以允許「sales.count」 –