How to call a class method from an instance

I am trying to call a class method from an instance,

e.g. @item = @item.class.find(params[:id]) or
@item = @item.type.find(params[:id])

@Item can reference objects form different classes.

With either of the above examples I get:
undefined method `find’ for NilClass:Class

Any help?

I don’t know that it is the best way, but you can do this with eval.
Eval will take a string and interpret it as ruby code.

So you would do something like:

eval( @item.class + ‘.find(params[:id])’ )

So this should take your class name, append the find clause and then
run the result.

Ok I tried eval( @item.class.to_s + ‘.find(params[:id])’ )
and i still get the error
undefined method `find’ for NilClass:Class error.

stupid mistake by me I think I know the problem, i’ll post again when
i’m sure.

Good to know, I guess I overlooked the simple answer.

Your way is better, as eval will blindly do whatever you tell it
(which can be dangerous).

I got it working with,
@item = @items.pop.type.find(params[:id])

I just wasn’t [email protected] with anything.

Thanks monki for the eval hint though. I wasn’t aware of the eval

Your original method was better (IMHO) – @item.class.find(params[:id])
– as type is deprecated and can sometimes behave unexpectedly as it’s
used as the key in STI models.

Also wanted to check you knew that @items.pop is a destructive method,
i.e. the item is removed from @items.
I would wonder if @items.last.class.find(params[:id]) is perhaps a bit

You’ve prob figured now that undefined method `find’ for NilClass:Class
was happening because @item was nil (instance variables are nil when
they are undefined, unlike local variables – try p @item and p item in
the console), and the class of nil is NilClass, which obviously doesn’t
have a find method.


This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs