Take me home

Extending Ruby classes in a Rails app

Written by August Lilleaas, published December 06, 2007

Extending a Ruby class (or any class, really) in a Rails app is easy mode. Here’s how to do it.

Say we’re extending array. Add a file called array_extension.rb to lib/. In other words, lib/array_extension.rb. Put this inside that file:

class Array
  def be_silly
    self.reverse.map {|i| i.upcase }
  end
end

Yay, we added a be_silly method. Here’s how it works:

["this", "is", "cool"].be_silly
# => ["COOL", "IS", "THIS"]

However, one more thing needs to be done. Open config/environment.rb and add this to the very bottom of the file:

require "array_extension"

Voila!


Questions or comments?

Feel free to contact me on Twitter, @augustl, or e-mail me at august@augustl.com.