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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With