Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is the best place to extend the functionality of built in classes in Rails?

I have a few methods I am adding to Ruby's Array class for my Rails application. Where is the best place to put them?

Right now I have them in config/environment.rb.

like image 409
muirbot Avatar asked Jan 21 '23 20:01

muirbot


2 Answers

config/environment.rb isn't really the best place, since you can run into serious load ordering-problems if try to extend classes that haven't been resolved at the time environment.rb is executed.

Better to put a file into config/initializers. Any script placed there will be executed after the rails runtime is loaded.

What you could do is to create a file lib/my_extensions.rb

module MyExtensions
end

then in lib/my_extensions/array.rb :

module MyExtensions::Array 
  def join_with_commas
    join(", ")
  end
end

and in config/initializers/load_my_extensions.rb

class Array
  include MyExtensions::Array
end

This will cause MyExtensions::Array to be auto-reloaded each time you invoke a request in development mode. This is nicer than restarting your application everytime you make a change to your code.

like image 93
flitzwald Avatar answered Mar 16 '23 22:03

flitzwald


It would probably be cleaner to add a lib/ directory with all your extensions. Then add a line in config/environment.rb that loads the file:

require File.join(RAILS_ROOT, 'lib', 'array.rb')
like image 26
hundredwatt Avatar answered Mar 16 '23 23:03

hundredwatt