Accessing instance variables outside of an object

November 19, 2008 by Jonathan Grenier

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.

Removing accents in a Ruby String

October 29, 2008 by Jonathan Grenier

With Ruby on Rails, it often seems the developers thought of everything because there’s a ton of helpers to do most common tasks. One thing that’s clearly missing though is a way to remove accents from a string. I’m not talking about escaping characters, I’m talking about converting the accented characters to their base letter (i.e. “éàû” should become “eau“).

I’ve spent a bit of time today thinking about the best way to do this. Once again, Ruby’s awesome flexibility means we can actually extend the standard String class and add a method to it. In a Ruby on Rails project, we add this library to the lib directory, add one line to the environment.rb file and we’re good to go.

Head over to the Remove Accents From A Ruby String script page to see all the details and to download the script you can use in your Ruby (and Rails) projects. With it, you’ll be able to simply do:

"été".removeaccents

Yes, that simple. I’ve also added another method to prepare a string to be used as part of a URL. Rather than escaping characters, it converts them using removeaccents and it calls a few additional methods to make sure the string is ready.

"été".urlize

We’ve published the script under a creative commons licence. Use it, abuse it, modify it and make sure to send back your changes so we can have a great version to share with everyone.