At the time when i am writing this post it looks like this.
First thing that we see is that the code is well documented with an explanation of what this class actually represents followed by examples of it’s usage.
Now take your time, pick up a cup of coffee and read the contents of this file from top to bottom.
As we can see the code is very concise and self explanatory. It starts with
Railtie is the core of the Rails framework and provides several hooks
to extend Rails and/or modify the initialization process.
Every major component of Rails (
and Active Record)
is a Railtie. Each of them is responsible for their own initialization.
This makes Rails itself absent of any component hooks,
allowing other components to be used in place of any of the Rails defaults.
So in order to interact with the Rails framework you will need to have a Railtie if you want to register custom generators, rake tasks, run some intializations, add configurations etc. It serves as a gateway, a door to the Ruby on Rails world of magic. We can also see from the code that the framework has predefined several abstract railties such as Rails::Railtie Rails::Engine Rails::Application that are ready for us to use. We are already using the Rails::Application railtie whenever we start a rails project. An example of usage of the Rails::Engine railtie can be found in the devise source code.
We will cover both Rails::Aplication and the Rails::Engine railties in the following posts in this series.
Now if we take a look at the implementation we can see that except for the autoloading part there
is nothing special going on really. Methods like initializer, config, rake_tasks, generators are just simple class methods that are storing the blocks associated with a given
group in a separate collection kept inside of an instance variable of the class object.
This provides an ability for the classes that extend a Railtie to have their own different configuration class. Think of this as a kind of a dependency injection which we will see it
in action when we will look at the Rails::Engine source code.
Reading the source code will supply you with a bag of tricks and tips useful to every ruby
developer and i think that this is a really neat one. One important thing that i must say is that
you should always try to read the code as slowly as possible. Dont haste to reach the bottom. Try
to understand every line, and ask the questions like:
Why this is done this way?
Where can i find an example of its usage and what is it’s purpose?
Believe me, every single line is there for a reason.
Another thing that we should avoid is what i call lazy reading. If we look at the file we can see
that we are using a module Initializable that is being mixed inside the class definition and the Configuration class
which is lazy loaded inside the instance config method so please check them out too. Don leave any
gaps that will result in surprises when we go deeply inside the rabbit hole.