312 | Chapter 10: Large Projects
Having a separate place for initializers helps you to separate them by function. Here
is a sample file for custom inflections:
# config/initializers/inflections.rb
# inflect.uncountable(["data"]) doesn't catch "something_data"
Inflector.inflections do |inflect|
inflect.plural(/(data)$/i, '\1')
inflect.singular(/(data)$/i, '\1')
end
The last trick for initialization is theafter_initializeblock. Included as part of the
configuration, it will be run at the end of initialization (immediately before the ini-
tializers mentioned previously). The block is specified thus:
config.after_initialize do
# some initialization code...
end
Unfortunately, you only get oneafter_initializeblock per initialization—you can’t
have one inenvironment.rband another inproduction.rb. So, choose wisely where
you need it. My recommendation: use it in your environment-specific configuration
files, and use the initializers directory for your generic initialization.
Including Gems
When deploying to a new machine, it can be frustrating to make sure all of the
dependencies are in order. RubyGems are typically the main culprit here. One way to
ensure you have gem dependencies under your control is to include them in the
project tree. This idea, from Chris Wanstrath,*is the natural extension of keeping
Rails and plugins within the project.
To include gems in the project, we will create a directory to hold them, then unpack
a gem there using thegem unpackcommand (you may need to update RubyGems for
this command to work):
$ mkdir vendor/gems
$ cd vendor/gems
$ gem unpack hpricot
Unpacked gem: 'hpricot-0.4'
Now we need to ensure that the directory we have created is added to the load path.
In the environment.rb file, inside the Rails::Initializer.run block, add the
following:
config.load_paths += Dir["#{RAILS_ROOT}/vendor/gems/**"].map do |dir|
File.directory?(lib = "#{dir}/lib")? lib : dir
end