Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access instance variable dynamically based on params[:controller]?

I've got a partial which should access the instance variables of various Controllers based on the params[:controller] variable. Using singularize and downcase, I define the name of the instance variable, which is the singular of the controller name by convention.

But I only get a String. How can I call the instance variable which is named like the string?

For example I have the controller Articles, so I do the following:

params[:controller].singularize.downcase # => "article"

now I want to access @article. How can I do this?

like image 306
davidb Avatar asked Dec 22 '22 05:12

davidb


1 Answers

There is a instance_variable_get() method in ruby. So try something like this:

var_name = params[:controller].singularize.downcase # article
instance_variable_get("@#{var_name}")

P.S: remember that you should use instance_variable_get in the proper context.

like image 116
bor1s Avatar answered Feb 23 '23 01:02

bor1s