0

I am attempting to access an object based on a string containing the object's name. The object is scoped (I am using cancan to ensure that users can only access records they are allowed to access). I have included some code below with where I have got to:

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

So, two questions:

  • How can I complete the r = [access object using left_operand_object] line, to allow me to access the scoped object based on its name from the string left_operand_object?
  • Will instance_variable_get work if left_operand is something like customers.count or would it only work without the count method?

Any help greatly appreciated!

1 Answer 1

1

Did I understand correctly, left_operand_object would be something like "Customer"?

If so, you can use left_operand_object.constantize to get your Customer class.
Probably safer to run left_operand_object.classify.constantize, so "row_entry" would become RowEntry.

I'm not perfectly clear what your second question is about. If you want to call the count method, you could do r.send(left_operand.to_sym) (assuming `left_operand = "count").

If left_operand is something like "sales.count", this would not work. I don't know if there's an idiomatic way to do it, but left_operand.split(".").inject(r) { |a, b| a.send b } does the trick for this particular case.


Sign up to request clarification or add additional context in comments.

2 Comments

Yes, you understand correctly - left_operand_object would be something like "customer". Thanks for the info, I'll look into using constantize - I assume this will assign the object to the r variable, as expected?
I think the second question was a little unclear - I am asking if I can use the count method inside instance_variable_get to return the count as an integer, but I think your answer has given me the direction I need to go - left_operand would be something like "sales.count" (assuming I was trying to use customer.sales.count).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.