Accessing instance variables outside of an object
Ruby on Rails makes good use of Ruby’s instance variables (@variable) to make variables set in a Controller available all the way down to the View and the Helpers. It’s very useful because it works really well… until you try to create a new FormBuilder helper. In that case, you are subclassing the ActionView::Helpers::FormBuilder class and thus, you do not have access to the variables set in the Controller. So, how can you do this then?
Ends up Ruby has a way around this. Any object in Ruby has a few methods to help out in that case. If you run:
MyObject.public_methods
You’ll get a long list of methods that you can call. Among those, you’ll see a few that are interesting:
- instance_variable_defined?
- instance_variable_get
- instance_variable_names
- instance_variable_set
- instance_variables
With this, you can then do instance_variable_get(“@myvar”) to get the value of the @myvar instance variable. In the case of a FormBuilder subclass though, you’ll need to use the @template variable to get access to the “view” object first. You’d do this like this:
@template.instance_variable_get('@language')
We’ll be talking about how to create a FormBuilder helper soon.
Tags: formbuilder, helpers, rails, ruby