Harry
Harry

Reputation: 4835

Rails accessing object from string containing object name

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:

Any help greatly appreciated!

Upvotes: 0

Views: 95

Answers (1)

Nils Landt
Nils Landt

Reputation: 3134

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.


Upvotes: 1

Related Questions