开发者

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/environmen开发者_C百科t.rb.


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.


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')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜