views:

724

answers:

3

I'm trying to learn the life cycle of a rails application. When is application_controller.rb run? Is it just once every time it's changed, or on every request?

I want to know the same about the following file:

  • config/environments/*.rb (development, production, or test, depending on the current mode)
  • boot.rb
  • environment.rb
  • routes.rb

One of the reasons I'm asking this is, I want to know where is a good place to put

  • initialization code
  • custom configuration data

EDIT:

@Gdeglin's answer is good, but I'm actually interested in knowing when each of these files run.

+11  A: 
Gdeglin
A little more specifically, when does each of these files run? It's the application lifecycle I'm interested in learning about.
Ovesh
I updated my response to better answer your question.
Gdeglin
A: 

It is common practice to put initialization stuff in the config/initializers/ directory. This way you can keep your environment.rb files clean(er).

See this post by Ryan Daigle.

ronaldevers
Neat. I didn't know that. Thanks!
Gdeglin
+2  A: 

With a little effort, you can follow it through yourself, which will probably be more useful.

Start from 'ruby script/server'. In my (2.1) application, that look for a file named "server" in the "script" directory. It contains this:

#!/usr/bin/env ruby
require File.dirname(__FILE__) + '/../config/boot'
require 'commands/server'

So it requires boot.rb, which defines a whole lot of stuff and then calls Rails.boot! which more or less runs any pre-initialization you've defined and then requires environment, which does another level of bootstrapping. By that time it's starting to get complicated: I'd recommend a large-ish sheet of paper...

And so on.

Alternatively, you may be able to hack Kernel#require to log when a file is being required in - I haven't tried it myself (and the method may be overridden elsewhere) but it could work...

application_controller isn't exactly "run" at all - it's a parent class for your other controllers, so its content, if required and not overridden becomes available when the inheriting controller is loaded. You'd generally use it to provide common functionality across all your controllers.

Mike Woodhouse
Thanks, that's helpful!
Ovesh