2012-07-01 2 views
0

객체의 이름이 들어있는 문자열을 기반으로 객체에 액세스하려고합니다. 개체의 범위가 지정됩니다 (사용자가 액세스 할 수있는 레코드에만 액세스 할 수 있도록 cancan을 사용하고 있습니다). 나는이에 도착 한 곳으로 아래의 일부 코드를 포함했다 :객체 이름을 포함하는 문자열에서 객체에 액세스하는 레일

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?
  • left_operandcustomers.count이거나 카운트 방법없이 작동하는 경우 instance_variable_get이 작동합니까?

대단히 감사합니다!

답변

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 메서드를 사용할 수 있는지 묻는 중입니다.하지만 응답이 나에게 필요한 방향을 제공했다고 생각합니다. - left_operand는 뭔가가 될 것입니다. "sales.count"(customer.sales.count를 사용하려고한다고 가정)와 같습니다. –

+0

나는 "sales.count"를 허용하는 나의 대답을 편집했다. –

관련 문제