2012-07-01 97 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” –