aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorXavier Noria <fxn@hashref.com>2010-12-29 23:46:03 +0100
committerXavier Noria <fxn@hashref.com>2010-12-29 23:46:03 +0100
commit69765aad8bcc853e7ab6b0e79f4edece2cdd7fe2 (patch)
treecbff92b476133e56dfdc4cfbdf2f5ecb6cfca2c3
parent0ac66caac5581c4793d120c8ad4a2cf4137f6ce2 (diff)
parent6f58b9ad5331d3619fc68a4706d5f85a95510a63 (diff)
downloadrails-69765aad8bcc853e7ab6b0e79f4edece2cdd7fe2.tar.gz
rails-69765aad8bcc853e7ab6b0e79f4edece2cdd7fe2.tar.bz2
rails-69765aad8bcc853e7ab6b0e79f4edece2cdd7fe2.zip
Merge branch 'master' of git://github.com/lifo/docrails
-rw-r--r--README.rdoc4
-rw-r--r--actionpack/CHANGELOG4
-rw-r--r--actionpack/lib/action_controller/base.rb2
-rw-r--r--actionpack/lib/action_view/base.rb2
-rw-r--r--actionpack/lib/action_view/partials.rb20
-rw-r--r--railties/guides/rails_guides/generator.rb2
-rw-r--r--railties/guides/source/action_view_overview.textile10
-rw-r--r--railties/guides/source/active_record_querying.textile6
-rw-r--r--railties/guides/source/active_support_core_extensions.textile8
-rw-r--r--railties/guides/source/association_basics.textile6
-rw-r--r--railties/guides/source/debugging_rails_applications.textile6
-rw-r--r--railties/guides/source/getting_started.textile10
-rw-r--r--railties/guides/source/i18n.textile14
-rw-r--r--railties/guides/source/initialization.textile3533
-rw-r--r--railties/guides/source/performance_testing.textile6
-rw-r--r--railties/guides/source/plugins.textile104
-rw-r--r--railties/guides/source/rails_application_templates.textile18
-rw-r--r--railties/guides/source/rails_on_rack.textile4
-rw-r--r--railties/guides/source/routing.textile3
-rw-r--r--railties/guides/source/security.textile10
-rw-r--r--railties/guides/w3c_validator.rb4
21 files changed, 316 insertions, 3460 deletions
diff --git a/README.rdoc b/README.rdoc
index 7ca376d492..0b209cf56f 100644
--- a/README.rdoc
+++ b/README.rdoc
@@ -53,8 +53,8 @@ more separate. Each of these packages can be used independently outside of
* The README file created within your application.
* The {Getting Started with Rails}[http://guides.rubyonrails.org/getting_started.html].
* The {Ruby on Rails Tutorial}[http://railstutorial.org/book].
-* The {Ruby on Rails guides}[http://guides.rubyonrails.org/getting_started.html].
-* The {API documentation}[http://api.rubyonrails.org].
+* The {Ruby on Rails Guides}[http://guides.rubyonrails.org].
+* The {API Documentation}[http://api.rubyonrails.org].
== Contributing
diff --git a/actionpack/CHANGELOG b/actionpack/CHANGELOG
index 20b19909fc..78fadce6cb 100644
--- a/actionpack/CHANGELOG
+++ b/actionpack/CHANGELOG
@@ -47,9 +47,7 @@
* Symbols and strings in routes should yield the same behavior. Note this may break existing apps that were using symbols with the new routes API. [José Valim]
-* Add clear_helpers as a way to clean up all helpers added to this controller, maintaing just the helper with the same name as the controller. [José Valim]
-
-* See http://github.com/rails/rails/compare/v3.0.0_RC...v3.0.0_RC2 for gory details
+* Add clear_helpers as a way to clean up all helpers added to this controller, maintaining just the helper with the same name as the controller. [José Valim]
* Support routing constraints in functional tests. [Andrew White]
diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb
index 48308cbb60..81c0698fb8 100644
--- a/actionpack/lib/action_controller/base.rb
+++ b/actionpack/lib/action_controller/base.rb
@@ -24,7 +24,7 @@ module ActionController
#
# Actions, by default, render a template in the <tt>app/views</tt> directory corresponding to the name of the controller and action
# after executing code in the action. For example, the +index+ action of the PostsController would render the
- # template <tt>app/views/posts/index.erb</tt> by default after populating the <tt>@posts</tt> instance variable.
+ # template <tt>app/views/posts/index.html.erb</tt> by default after populating the <tt>@posts</tt> instance variable.
#
# Unlike index, the create action will not render a template. After performing its main purpose (creating a
# new post), it initiates a redirect instead. This redirect works by returning an external
diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb
index 95eb3446da..ab8c6259c5 100644
--- a/actionpack/lib/action_view/base.rb
+++ b/actionpack/lib/action_view/base.rb
@@ -18,7 +18,7 @@ module ActionView #:nodoc:
# following loop for names:
#
# <b>Names of all the people</b>
- # <% for person in @people %>
+ # <% @people.each do |person| %>
# Name: <%= person.name %><br/>
# <% end %>
#
diff --git a/actionpack/lib/action_view/partials.rb b/actionpack/lib/action_view/partials.rb
index cd3f130dc4..56c661c00c 100644
--- a/actionpack/lib/action_view/partials.rb
+++ b/actionpack/lib/action_view/partials.rb
@@ -12,19 +12,19 @@ module ActionView
#
# <%= render :partial => "account" %>
#
- # This would render "advertiser/_account.erb" and pass the instance variable @account in as a local variable
+ # This would render "advertiser/_account.html.erb" and pass the instance variable @account in as a local variable
# +account+ to the template for display.
#
# In another template for Advertiser#buy, we could have:
#
# <%= render :partial => "account", :locals => { :account => @buyer } %>
#
- # <% for ad in @advertisements %>
+ # <% @advertisements.each do |ad| %>
# <%= render :partial => "ad", :locals => { :ad => ad } %>
# <% end %>
#
- # This would first render "advertiser/_account.erb" with @buyer passed in as the local variable +account+, then
- # render "advertiser/_ad.erb" and pass the local variable +ad+ to the template for display.
+ # This would first render "advertiser/_account.html.erb" with @buyer passed in as the local variable +account+, then
+ # render "advertiser/_ad.html.erb" and pass the local variable +ad+ to the template for display.
#
# == The :as and :object options
#
@@ -44,12 +44,12 @@ module ActionView
#
# The <tt>:object</tt> option can be used to directly specify which object is rendered into the partial;
# useful when the template's object is elsewhere, in a different ivar or in a local variable for instance.
- #
+ #
# Revisiting a previous example we could have written this code:
- #
+ #
# <%= render :partial => "account", :object => @buyer %>
#
- # <% for ad in @advertisements %>
+ # <% @advertisements.each do |ad| %>
# <%= render :partial => "ad", :object => ad %>
# <% end %>
#
@@ -64,12 +64,12 @@ module ActionView
#
# <%= render :partial => "ad", :collection => @advertisements %>
#
- # This will render "advertiser/_ad.erb" and pass the local variable +ad+ to the template for display. An
+ # This will render "advertiser/_ad.html.erb" and pass the local variable +ad+ to the template for display. An
# iteration counter will automatically be made available to the template with a name of the form
# +partial_name_counter+. In the case of the example above, the template would be fed +ad_counter+.
#
# The <tt>:as</tt> option may be used when rendering partials.
- #
+ #
# You can specify a partial to be rendered between elements via the <tt>:spacer_template</tt> option.
# The following example will render <tt>advertiser/_ad_divider.html.erb</tt> between each ad partial:
#
@@ -89,7 +89,7 @@ module ActionView
#
# <%= render :partial => "advertisement/ad", :locals => { :ad => @advertisement } %>
#
- # This will render the partial "advertisement/_ad.erb" regardless of which controller this is being called from.
+ # This will render the partial "advertisement/_ad.html.erb" regardless of which controller this is being called from.
#
# == Rendering objects with the RecordIdentifier
#
diff --git a/railties/guides/rails_guides/generator.rb b/railties/guides/rails_guides/generator.rb
index 0a2170a09e..68d406e31c 100644
--- a/railties/guides/rails_guides/generator.rb
+++ b/railties/guides/rails_guides/generator.rb
@@ -32,7 +32,7 @@
#
# Separate many using commas:
#
-# # generates only
+# # generates only association_basics.html and migrations.html
# ONLY=assoc,migrations ruby rails_guides.rb
#
# Note that if you are working on a guide generation will by default process
diff --git a/railties/guides/source/action_view_overview.textile b/railties/guides/source/action_view_overview.textile
index 30faeeaa91..e1fc0e7732 100644
--- a/railties/guides/source/action_view_overview.textile
+++ b/railties/guides/source/action_view_overview.textile
@@ -367,14 +367,14 @@ This helper makes building an ATOM feed easy. Here's a full usage example:
*config/routes.rb*
<ruby>
-map.resources :posts
+resources :posts
</ruby>
*app/controllers/posts_controller.rb*
<ruby>
def index
- @posts = Post.find(:all)
+ @posts = Post.all
respond_to do |format|
format.html
@@ -439,7 +439,7 @@ The +capture+ method allows you to extract part of a template into a variable. Y
<% @greeting = capture do %>
<p>Welcome! The date and time is <%= Time.now %></p>
<% end %>
-<ruby>
+</ruby>
The captured variable can then be used anywhere else.
@@ -809,7 +809,7 @@ end
Sample usage (selecting the associated Author for an instance of Post, +@post+):
<ruby>
-collection_select(:post, :author_id, Author.find(:all), :id, :name_with_initial, {:prompt => true})
+collection_select(:post, :author_id, Author.all, :id, :name_with_initial, {:prompt => true})
</ruby>
If @post.author_id is already 1, this would return:
@@ -910,7 +910,7 @@ Create a select tag and a series of contained option tags for the provided objec
Example with @post.person_id => 1:
<ruby>
-select("post", "person_id", Person.find(:all).collect {|p| [ p.name, p.id ] }, { :include_blank => true })
+select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, { :include_blank => true })
</ruby>
could become:
diff --git a/railties/guides/source/active_record_querying.textile b/railties/guides/source/active_record_querying.textile
index 61d8205278..6e45bf3188 100644
--- a/railties/guides/source/active_record_querying.textile
+++ b/railties/guides/source/active_record_querying.textile
@@ -150,7 +150,7 @@ SQL equivalent of the above is:
SELECT * FROM clients WHERE (clients.id IN (1,10))
</sql>
-<tt>Model.find(array_of_primary_key)</tt> will raise an +ActiveRecord::RecordNotFound+ exception unless a matching record is found for <strong>all</strong> of the supplied primary keys.
+WARNING: <tt>Model.find(array_of_primary_key)</tt> will raise an +ActiveRecord::RecordNotFound+ exception unless a matching record is found for <strong>all</strong> of the supplied primary keys.
h4. Retrieving Multiple Objects in Batches
@@ -569,9 +569,7 @@ SELECT clients.* FROM clients LEFT OUTER JOIN addresses ON addresses.client_id =
h4. Using Array/Hash of Named Associations
-WARNING: This method only works with +INNER JOIN+,
-
-<br />
+WARNING: This method only works with +INNER JOIN+.
Active Record lets you use the names of the "associations":association_basics.html defined on the model as a shortcut for specifying +JOIN+ clause for those associations when using the +joins+ method.
diff --git a/railties/guides/source/active_support_core_extensions.textile b/railties/guides/source/active_support_core_extensions.textile
index 33e281d59b..9a1f913ded 100644
--- a/railties/guides/source/active_support_core_extensions.textile
+++ b/railties/guides/source/active_support_core_extensions.textile
@@ -498,7 +498,7 @@ h4. Attributes
h5. +alias_attribute+
-Model attributes have a reader, a writer, and a predicate. You can aliase a model attribute having the corresponding three methods defined for you in one shot. As in other aliasing methods, the new name is the first argument, and the old name is the second (my mnemonic is they go in the same order as if you did an assignment):
+Model attributes have a reader, a writer, and a predicate. You can alias a model attribute having the corresponding three methods defined for you in one shot. As in other aliasing methods, the new name is the first argument, and the old name is the second (my mnemonic is they go in the same order as if you did an assignment):
<ruby>
class User < ActiveRecord::Base
@@ -563,7 +563,7 @@ h5. Internal Attributes
When you are defining an attribute in a class that is meant to be subclassed name collisions are a risk. That's remarkably important for libraries.
-Active Support defines the macros +attr_internal_reader+, +attr_internal_writer+, and +attr_internal_accessor+. They behave like their Ruby builtin +attr_*+ counterparts, except they name the underlying instance variable in a way that makes collisions less likely.
+Active Support defines the macros +attr_internal_reader+, +attr_internal_writer+, and +attr_internal_accessor+. They behave like their Ruby built-in +attr_*+ counterparts, except they name the underlying instance variable in a way that makes collisions less likely.
The macro +attr_internal+ is a synonym for +attr_internal_accessor+:
@@ -991,7 +991,7 @@ a2.x # => 2, overridden in a2
The generation of the writer instance method can be prevented by setting the option +:instance_writer+ to false, as in
<ruby>
-module AcitveRecord
+module ActiveRecord
class Base
class_attribute :table_name_prefix, :instance_writer => false
self.table_name_prefix = ""
@@ -1001,7 +1001,7 @@ end
A model may find that option useful as a way to prevent mass-assignment from setting the attribute.
-For convenience +class_attribute+ defines also an instance predicate which is the double negation of what the instance reader returns. In the examples above it would be called +x?+.
+For convenience +class_attribute+ also defines an instance predicate which is the double negation of what the instance reader returns. In the examples above it would be called +x?+.
NOTE: Defined in +active_support/core_ext/class/attribute.rb+
diff --git a/railties/guides/source/association_basics.textile b/railties/guides/source/association_basics.textile
index 62abc40c81..f22f41e8b1 100644
--- a/railties/guides/source/association_basics.textile
+++ b/railties/guides/source/association_basics.textile
@@ -65,7 +65,7 @@ To learn more about the different types of associations, read the next section o
h3. The Types of Associations
-In Rails, an _association_ is a connection between two Active Record models. Associations are implemented using macro-style calls, so that you can declaratively add features to your models. For example, by declaring that one model +belongs_to+ another, you instruct Rails to maintain Primary Key–Foreign Key information between instances of the two models, and you also get a number of utility methods added to your model. Rails supports six types of association:
+In Rails, an _association_ is a connection between two Active Record models. Associations are implemented using macro-style calls, so that you can declaratively add features to your models. For example, by declaring that one model +belongs_to+ another, you instruct Rails to maintain Primary Key–Foreign Key information between instances of the two models, and you also get a number of utility methods added to your model. Rails supports six types of associations:
* +belongs_to+
* +has_one+
@@ -1135,7 +1135,7 @@ h6(#has_many-collection-find). <tt><em>collection</em>.find(...)</tt>
The <tt><em>collection</em>.find</tt> method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+.
<ruby>
-@open_orders = @customer.orders.find(:all, :conditions => "open = 1")
+@open_orders = @customer.orders.all(:conditions => "open = 1")
</ruby>
NOTE: Starting Rails 3, supplying options to +ActiveRecord::Base.find+ method is discouraged. Use <tt><em>collection</em>.where</tt> instead when you need to pass conditions.
@@ -1564,7 +1564,7 @@ h6(#has_and_belongs_to_many-collection-find). <tt><em>collection</em>.find(...)<
The <tt><em>collection</em>.find</tt> method finds objects within the collection. It uses the same syntax and options as +ActiveRecord::Base.find+. It also adds the additional condition that the object must be in the collection.
<ruby>
-@new_assemblies = @part.assemblies.find(:all,
+@new_assemblies = @part.assemblies.all(
:conditions => ["created_at > ?", 2.days.ago])
</ruby>
diff --git a/railties/guides/source/debugging_rails_applications.textile b/railties/guides/source/debugging_rails_applications.textile
index 2c8a6619c2..b84d7d088d 100644
--- a/railties/guides/source/debugging_rails_applications.textile
+++ b/railties/guides/source/debugging_rails_applications.textile
@@ -269,7 +269,7 @@ If you got there by a browser request, the browser tab containing the request wi
For example:
<shell>
-@posts = Post.find(:all)
+@posts = Post.all
(rdb:7)
</shell>
@@ -302,7 +302,7 @@ This command shows you where you are in the code by printing 10 lines centered a
3 # GET /posts.xml
4 def index
5 debugger
-=> 6 @posts = Post.find(:all)
+=> 6 @posts = Post.all
7
8 respond_to do |format|
9 format.html # index.html.erb
@@ -380,7 +380,7 @@ Any expression can be evaluated in the current context. To evaluate an expressio
This example shows how you can print the instance_variables defined within the current context:
<shell>
-@posts = Post.find(:all)
+@posts = Post.all
(rdb:11) instance_variables
["@_response", "@action_name", "@url", "@_session", "@_cookies", "@performed_render", "@_flash", "@template", "@_params", "@before_filter_chain_aborted", "@request_origin", "@_headers", "@performed_redirect", "@_request"]
</shell>
diff --git a/railties/guides/source/getting_started.textile b/railties/guides/source/getting_started.textile
index 4466c291bb..82700532c0 100644
--- a/railties/guides/source/getting_started.textile
+++ b/railties/guides/source/getting_started.textile
@@ -163,7 +163,7 @@ $ rails new blog
This will create a Rails application called Blog in a directory called blog.
-TIP: You can see all of the switches that the Rails application builder accepts by running <tt>rails -h</tt>.
+TIP: You can see all of the switches that the Rails application builder accepts by running <tt>rails new -h</tt>.
After you create the blog application, switch to its folder to continue work directly in that application:
@@ -258,6 +258,8 @@ development:
Change the username and password in the +development+ section as appropriate.
+TIP: You don't have to update the database configurations manually. If you had a look at the options of application generator, you have seen that one of them is named <tt>--database</tt>. It lets you choose an adapter for couple of most used relational databases. You can even run the generator repeatedly: <tt>cd .. && rails new blog --database=mysql</tt>. When you confirm the overwriting of the +config/database.yml+ file, your application will be configured for MySQL instead of SQLite.
+
h4. Creating the Database
Now that you have your database configured, it's time to have Rails create an empty database for you. You can do this by running a rake command:
@@ -298,7 +300,7 @@ To get Rails saying "Hello", you need to create at minimum a controller and a vi
$ rails generate controller home index
</shell>
-TIP: If you're on Windows, or your Ruby is set up in some non-standard fashion, you may need to explicitly pass Rails +rails+ commands to Ruby: +ruby \path\to\rails controller home index+.
+TIP: If you're on Windows, or your Ruby is set up in some non-standard fashion, you may need to explicitly pass Rails +rails+ commands to Ruby: <tt>ruby \path\to\your\application\script\rails generate controller home index</tt>.
Rails will create several files for you, including +app/views/home/index.html.erb+. This is the template that will be used to display the results of the +index+ action (method) in the +home+ controller. Open this file in your text editor and edit it to contain a single line of code:
@@ -347,7 +349,7 @@ In the case of the blog application, you can start by generating a scaffolded Po
$ rails generate scaffold Post name:string title:string content:text
</shell>
-NOTE. While scaffolding will get you up and running quickly, the "one size fits all" code that it generates is unlikely to be a perfect fit for your application. In most cases, you'll need to customize the generated code. Many experienced Rails developers avoid scaffolding entirely, preferring to write all or most of their source code from scratch.
+NOTE. While scaffolding will get you up and running quickly, the code it generates is unlikely to be a perfect fit for your application. You'll most probably want to customize the generated code. Many experienced Rails developers avoid scaffolding entirely, preferring to write all or most of their source code from scratch. Rails, however, makes it really simple to customize templates for generated models, controllers, views and other source files. You'll find more information in the "Creating and Customizing Rails Generators & Templates":generators.html guide.
The scaffold generator will build 15 files in your application, along with some folders, and edit one more. Here's a quick overview of what it creates:
@@ -409,7 +411,7 @@ Rails will execute this migration command and tell you it created the Posts tabl
== CreatePosts: migrated (0.0020s) ===========================================
</shell>
-NOTE. Because you're working in the development environment by default, this command will apply to the database defined in the +development+ section of your +config/database.yml+ file.
+NOTE. Because you're working in the development environment by default, this command will apply to the database defined in the +development+ section of your +config/database.yml+ file. If you would like to execute migrations in other environment, for instance in production, you must explicitely pass it when invoking the command: <tt>rake db:migrate RAILS_ENV=production</tt>.
h4. Adding a Link
diff --git a/railties/guides/source/i18n.textile b/railties/guides/source/i18n.textile
index 46e3b80a76..bb8bf8b240 100644
--- a/railties/guides/source/i18n.textile
+++ b/railties/guides/source/i18n.textile
@@ -10,7 +10,7 @@ So, in the process of _internationalizing_ your Rails application you have to:
* Tell Rails where to find locale dictionaries
* Tell Rails how to set, preserve and switch locale
-In the process of _localizing_ your application you'll probably want to do following three things:
+In the process of _localizing_ your application you'll probably want to do the following three things:
* Replace or supplement Rails' default locale -- e.g. date and time formats, month names, Active Record model names, etc
* Abstract strings in your application into keyed dictionaries -- e.g. flash messages, static text in your views, etc.
@@ -305,12 +305,12 @@ end
# app/controllers/home_controller.rb
class HomeController < ApplicationController
def index
- flash[:notice] = "Hello flash!"
+ flash[:notice] = "Hello Flash"
end
end
# app/views/home/index.html.erb
-<h1>Hello world!</h1>
+<h1>Hello World</h1>
<p><%= flash[:notice] %></p>
</ruby>
@@ -344,8 +344,8 @@ So let's add the missing translations into the dictionary files (i.e. do the "lo
<ruby>
# config/locales/en.yml
en:
- hello_world: Hello World
- hello_flash: Hello Flash
+ hello_world: Hello world!
+ hello_flash: Hello flash!
# config/locales/pirate.yml
pirate:
@@ -586,7 +586,7 @@ I18n.t :foo
I18n.l Time.now
</ruby>
-Explicitely passing a locale:
+Explicitly passing a locale:
<ruby>
I18n.t :foo, :locale => :de
@@ -623,7 +623,7 @@ pt:
bar: baz
</ruby>
-As you see, in both cases the toplevel key is the locale. +:foo+ is a namespace key and +:bar+ is the key for the translation "baz".
+As you see, in both cases the top level key is the locale. +:foo+ is a namespace key and +:bar+ is the key for the translation "baz".
Here is a "real" example from the Active Support +en.yml+ translations YAML file:
diff --git a/railties/guides/source/initialization.textile b/railties/guides/source/initialization.textile
index 1504b973a5..0cbbe1f389 100644
--- a/railties/guides/source/initialization.textile
+++ b/railties/guides/source/initialization.textile
@@ -224,7 +224,17 @@ Action Dispatch is the routing component of the Rails framework. It depends on A
h4. +activesupport/lib/active_support.rb+
-This file begins with requiring +active_support/lib/active_support/dependencies/autoload.rb+ which redefines Ruby's +autoload+ method to have a little more extra behaviour especially in regards to eager autoloading. Eager autoloading is the loading of all required classes and will happen when the +config.cache_classes+ setting is +true+.
+This file begins with requiring +active_support/lib/active_support/dependencies/autoload.rb+ which redefines Ruby's +autoload+ method to have a little more extra behaviour especially in regards to eager autoloading. Eager autoloading is the loading of all required classes and will happen when the +config.cache_classes+ setting is +true+. The required file also requires another file: +active_support/lazy_load_hooks+
+
+h4. +activesupport/lib/active_support/lazy_load_hooks.rb+
+
+This file defines the +ActiveSupport.on_load+ hook which is used to execute code when specific parts are loaded. We'll see this in use a little later on.
+
+This file begins with requiring +active_support/inflector/methods+.
+
+h4. +activesupport/lib/active_support/inflector/methods.rb+
+
+The +methods.rb+ file is responsible for defining methods such as +camelize+, +underscore+ and +dasherize+ as well as a slew of others. The "+ActiveSupport::Inflector+ documentation":http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html covers them all pretty decently.
In this file there are a lot of lines such as this inside the +ActiveSupport+ module:
@@ -647,6 +657,8 @@ h4. +activesupport/lib/active_support/inflector.rb+
require 'active_support/core_ext/string/inflections'
</ruby>
+The +active_support/inflector/methods+ file has already been required by +active_support/autoload+ and so won't be loaded again here.
+
h4. +activesupport/lib/active_support/inflector/inflections.rb+
This file references the +ActiveSupport::Inflector+ constant which isn't loaded by this point. But there were autoloads set up in +activesupport/lib/active_support.rb+ which will load the file which loads this constant and so then it will be defined. Then this file defines pluralization and singularization rules for words in Rails. This is how Rails knows how to pluralize "tomato" to "tomatoes".
@@ -655,13 +667,9 @@ h4. +activesupport/lib/active_support/inflector/transliterate.rb+
In this file is where the "+transliterate+":http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-transliterate and +parameterize+:http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-parameterize methods are defined. The documentation for both of these methods is very much worth reading.
-h4. +activesupport/lib/active_support/inflector/methods.rb+
-
-The +methods.rb+ file is responsible for defining methods such as +camelize+, +underscore+ and +dasherize+ as well as a slew of others. The "+ActiveSupport::Inflector+ documentation":http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html covers them all pretty decently.
-
h4. Back to +railties/lib/rails/railtie.rb+
-Once the inflector files have been loaded, the +Rails::Railtie+ class is defined. This class includes a module called +Initializable+, which is actually +Rails::Initializable+ and is automatically loaded at this point.
+Once the inflector files have been loaded, the +Rails::Railtie+ class is defined. This class includes a module called +Initializable+, which is actually +Rails::Initializable+. This module includes the +initializer+ method which is used later on for setting up initializers, amongst other methods.
h4. +railties/lib/rails/initializable.rb+
@@ -699,9 +707,11 @@ h4. +railties/lib/rails/version.rb+
Much like +active_support/version+, this file defines the +VERSION+ constant which has a +STRING+ constant on it which returns the current version of Rails.
+Once this file has finished loading we go back to +railties/lib/rails.rb+ which then requires +active_support/railtie.rb+.
+
h4. +activesupport/lib/active_support/railtie.rb+
-This file requires +active_support+ and +rails+ which have already been required so these two lines are effectively ignored. The third require in this file is to +active_support/railtie+.
+This file requires +active_support+ and +rails+ which have already been required so these two lines are effectively ignored. The third require in this file is to +active_support/i18n_railtie.rb+.
h4. +activesupport/lib/active_support/i18n_railtie.rb+
@@ -715,1976 +725,39 @@ This file is the first file that sets up configuration with these lines inside t
config.i18n.fallbacks = ActiveSupport::OrderedOptions.new
</ruby>
-
-
-
-**** REVIEW IS HERE ****
-
-This defines two methods on the module itself by using the familiar +class << self+ syntax. This allows you to call them as if they were class methods: +ActiveSupport.on_load_all+ and +ActiveSupport.load_all!+ respectively. The first method simply adds loading hooks to save them up for loading later on when +load_all!+ is called. By +call+'ing the block, the classes will be loaded. (NOTE: kind of guessing, I feel 55% about this).
-
-The +on_load_all+ method is called later with the +Dependencies+, +Deprecation+, +Gzip+, +MessageVerifier+, +Multibyte+ and +SecureRandom+. What each of these modules do will be covered later.
-
-This file goes on to define some classes that will be automatically loaded using Ruby's +autoload+ method, but not before including Rails's own variant of the +autoload+ method from _active_support/dependencies/autoload.rb_:
-
-
-<ruby>
- require "active_support/inflector/methods"
- require "active_support/lazy_load_hooks"
-
- module ActiveSupport
- module Autoload
- def self.extended(base)
- base.extend(LazyLoadHooks)
- end
-
- @@autoloads = {}
- @@under_path = nil
- @@at_path = nil
- @@eager_autoload = false
-
- def autoload(const_name, path = @@at_path)
- full = [self.name, @@under_path, const_name.to_s, path].compact.join("::")
- location = path || Inflector.underscore(full)
-
- if @@eager_autoload
- @@autoloads[const_name] = location
- end
- super const_name, location
- end
-
- ...
- end
- end
-</ruby>
-
-h4. Lazy Hooks
-
-+ActiveSupport::LazyLoadHooks+ is responsible for defining methods used for running hooks that are defined during the initialization process, such as the one defined inside the +active_record.initialize_timezone+ initializer:
-
-<ruby>
- initializer "active_record.initialize_timezone" do
- ActiveSupport.on_load(:active_record) do
- self.time_zone_aware_attributes = true
- self.default_timezone = :utc
- end
- end
-</ruby>
-
-When the initializer runs it invokes method +on_load+ for +ActiveRecord+ and the block passed to it would be called only when +run_load_hooks+ is called.
-When the entirety of +activerecord/lib/active_record/base.rb+ has been evaluated then +run_load_hooks+ is invoked. The very last line of +activerecord/lib/active_record/base.rb+ is:
-
-<ruby>
-ActiveSupport.run_load_hooks(:active_record, ActiveRecord::Base)
-</ruby>
-
-h4. +require 'active_support'+ cont'd.
-
-This file also uses the method +eager_autoload+ also defined in _active_support/dependencies/autoload.rb_:
-
-<ruby>
- def eager_autoload
- old_eager, @@eager_autoload = @@eager_autoload, true
- yield
- ensure
- @@eager_autoload = old_eager
- end
-</ruby>
-
-As you can see for the duration of the +eager_autoload+ block the class variable +@@eager_autoload+ is set to +true+, which has the consequence of when +autoload+ is called that the location of the file for that specific +autoload+'d constant is added to the +@@autoloads+ hash initialized at the beginning of this module declaration. So now that you have part of the context, here's the other, the code from _activesupport/lib/active_support.rb_:
-
-<ruby>
- require "active_support/dependencies/autoload"
-
- module ActiveSupport
- extend ActiveSupport::Autoload
-
- autoload :DescendantsTracker
- autoload :FileUpdateChecker
- autoload :LogSubscriber
- autoload :Notifications
-
- # TODO: Narrow this list down
- eager_autoload do
- autoload :BacktraceCleaner
- autoload :Base64
- autoload :BasicObject
- autoload :Benchmarkable
- autoload :BufferedLogger
- autoload :Cache
- autoload :Callbacks
- autoload :Concern
- autoload :Configurable
- autoload :Deprecation
- autoload :Gzip
- autoload :Inflector
- autoload :JSON
- autoload :Memoizable
- autoload :MessageEncryptor
- autoload :MessageVerifier
- autoload :Multibyte
- autoload :OptionMerger
- autoload :OrderedHash
- autoload :OrderedOptions
- autoload :Rescuable
- autoload :SecureRandom
- autoload :StringInquirer
- autoload :XmlMini
- end
-
- autoload :SafeBuffer, "active_support/core_ext/string/output_safety"
- autoload :TestCase
- end
-
- autoload :I18n, "active_support/i18n"
-</ruby>
-
-So we know the ones in +eager_autoload+ are eagerly loaded and it does this by storing them in an +@@autoloads+ hash object and then loading them via +eager_autoload!+ which is called via the +preload_frameworks+ initializer defined in _railties/lib/rails/application/bootstrap.rb_.
-
-The classes and modules that are not +eager_autoload+'d are automatically loaded as they are references
-
-Note: What does it means to be autoloaded? An example of this would be calling the +ActiveSupport::TestCase+ class which hasn't yet been initialized. Because it's been specified as an +autoload+ Ruby will require the file that it's told to. The file it requires is not defined in the +autoload+ call here but, as you may have seen, in the +ActiveSupport::Autoload.autoload+ definition. So once that file has been required Ruby will try again and then if it still can't find it it will throw the all-too-familiar +uninitialized constant+ error.
-
-h4. +require 'action_dispatch'+
-
-Back in _actionpack/lib/action_dispatch.rb_, the next require after _active_support_ is to _active_support/dependencies/autoload_ but this file has already been loaded by _activesupport/lib/active_support.rb_ and so will not be loaded again. The next require is to Rack itself:
-
-<ruby>
- require 'rack'
-</ruby>
-
-As mentioned previously, Bundler has added the gems' _lib_ directories to the load path so this _rack_ file that is referenced lives in the Rack gem: _lib/rack.rb_. This loads Rack so we can use it later on when we define +Rails::Server+ to descend from +Rack::Server+.
-
-This file then goes on to define the +ActionDispatch+ module and it's related autoloads:
-
-<ruby>
- module Rack
- autoload :Test, 'rack/test'
- end
-
- module ActionDispatch
- extend ActiveSupport::Autoload
-
- autoload_under 'http' do
- autoload :Request
- autoload :Response
- end
-
- autoload_under 'middleware' do
- autoload :Callbacks
- autoload :Cascade
- autoload :Cookies
- autoload :Flash
- autoload :Head
- autoload :ParamsParser
- autoload :RemoteIp
- autoload :Rescue
- autoload :ShowExceptions
- autoload :Static
- end
-
- autoload :MiddlewareStack, 'action_dispatch/middleware/stack'
- autoload :Routing
-
- module Http
- extend ActiveSupport::Autoload
-
- autoload :Cache
- autoload :Headers
- autoload :MimeNegotiation
- autoload :Parameters
- autoload :FilterParameters
- autoload :Upload
- autoload :UploadedFile, 'action_dispatch/http/upload'
- autoload :URL
- end
-
- module Session
- autoload :AbstractStore, 'action_dispatch/middleware/session/abstract_store'
- autoload :CookieStore, 'action_dispatch/middleware/session/cookie_store'
- autoload :MemCacheStore, 'action_dispatch/middleware/session/mem_cache_store'
- end
-
- autoload_under 'testing' do
- autoload :Assertions
- autoload :Integration
- autoload :PerformanceTest
- autoload :TestProcess
- autoload :TestRequest
- autoload :TestResponse
- end
- end
-
- autoload :Mime, 'action_dispatch/http/mime_type'
-</ruby>
-
-h4. +require "rails/commands/server"+
-
-Now that Rails has required Action Dispatch and it has required Rack, Rails can now go about defining the +Rails::Server+ class:
-
-<ruby>
- module Rails
- class Server < ::Rack::Server
-
- ...
-
- def initialize(*)
- super
- set_environment
- end
-
- ...
-
- def set_environment
- ENV["RAILS_ENV"] ||= options[:environment]
- end
- ...
- end
- end
-</ruby>
-
-h4. +require "rails/commands"+
-
-Back in _rails/commands_ Rails calls +Rails::Server.new+ which calls the +initialize+ method on the +Rails::Server+ class, which calls +super+, meaning it's actually calling +Rack::Server#initialize+, with it being defined like this:
-
-<ruby>
- def initialize(options = nil)
- @options = options
- end
-</ruby>
-
-The +options+ method like this:
-
-<ruby>
- def options
- @options ||= parse_options(ARGV)
- end
-</ruby>
-
-The +parse_options+ method like this:
-
-<ruby>
- def parse_options(args)
- options = default_options
-
- # Don't evaluate CGI ISINDEX parameters.
- # http://hoohoo.ncsa.uiuc.edu/cgi/cl.html
- args.clear if ENV.include?("REQUEST_METHOD")
-
- options.merge! opt_parser.parse! args
- options
- end
-</ruby>
-
-And +default_options+ like this:
-
-<ruby>
- def default_options
- {
- :environment => "development",
- :pid => nil,
- :Port => 9292,
- :Host => "0.0.0.0",
- :AccessLog => [],
- :config => "config.ru"
- }
- end
-</ruby>
-
-Here it is important to note that the default environment is _development_. After +Rack::Server#initialize+ has done its thing it returns to +Rails::Server#initialize+ which calls +set_environment+:
-
-<ruby>
- def set_environment
- ENV["RAILS_ENV"] ||= options[:environment]
- end
-</ruby>
-
-From the information given we can determine that +ENV["RAILS_ENV"]+ will be set to _development_ if no other environment is specified.
-
-Finally, after +Rails::Server.new+ has executed, there is one more require:
-
-<ruby>
- require APP_PATH
-</ruby>
-
-+APP_PATH+ was previously defined as _config/application.rb_ in the application's root, and so that is where Rails will go next.
-
-h4. +require APP_PATH+
-
-This file is _config/application.rb_ in your application and makes two requires to begin with:
-
-<ruby>
- require File.expand_path('../boot', __FILE__)
- require 'rails/all'
-</ruby>
-
-The +../boot+ file it references is +config/boot.rb+, which was loaded earlier in the initialization process and so will not be loaded again.
-
-If you generate the application with the +-O+ option this will put a couple of pick-and-choose requirements at the top of your _config/application.rb_ instead:
-
-<ruby>
- # Pick the frameworks you want:
- # require "active_record/railtie"
- require "action_controller/railtie"
- require "action_mailer/railtie"
- require "active_resource/railtie"
- require "rails/test_unit/railtie"
-</ruby>
-
-For the purposes of this guide, will will assume only:
-
-<ruby>
- require 'rails/all'
-</ruby>
-
-h4. +require "rails/all"+
-
-Now we'll dive into the internals of the pre-initialization stage of Rails. The file that is being required is _railties/lib/rails/all.rb_. The first line in this file is:
-
-<ruby>
- require 'rails'
-</ruby>
-
-h4. +require 'rails'+
-
-This file (_railties/lib/rails.rb_) requires the very, very basics that Rails needs to get going. I'm not going to delve into these areas yet, just cover them briefly for now. Later on we will go through the ones that are important to the boot procedure.
-
-<ruby>
- require 'pathname'
-
- require 'active_support'
- require 'active_support/core_ext/kernel/reporting'
- require 'active_support/core_ext/logger'
-
- require 'rails/application'
- require 'rails/version'
- require 'rails/deprecation'
- require 'rails/log_subscriber'
- require 'rails/ruby_version_check'
-
- require 'active_support/railtie'
- require 'action_dispatch/railtie'
-</ruby>
-
-+require 'pathname'+ requires the Pathname class which is used for returning a Pathname object for +Rails.root+. Although is coming to use this path name to generate paths as below:
-
-<ruby>
- Rails.root.join("app/controllers")
-</ruby>
-
-Pathname can also be converted to string, so the following syntax is preferred:
-
-<ruby>
- "#{Rails.root}/app/controllers"
-</ruby>
-
-
-This works because Ruby automatically handles file path conversions. Although this is not new to Rails 3 (it was available in 2.3.5), it is something worthwhile pointing out.
-
-Inside this file there are other helpful helper methods defined, such as +Rails.root+, +Rails.env+, +Rails.logger+ and +Rails.application+.
-
-The first require:
-
-<ruby>
- require 'active_support'
-</ruby>
-
-Is not ran as this was already required by _actionpack/lib/action_dispatch.rb_.
-
-
-h4. +require 'active_support/core_ext/kernel/reporting'+
-
-This file extends the +Kernel+ module, providing the methods +silence_warnings+, +enable_warnings+, +with_warnings+, +silence_stderr+, +silence_stream+ and +suppress+. The API documentation on these overridden methods is fairly good and if you wish to know more "have a read.":http://api.rubyonrails.org/classes/Kernel.html
-
-For information on this file see the "Core Extensions" guide. TODO: link to guide.
-
-h4. +require 'active_support/core_ext/logger'+
-
-For information on this file see the "Core Extensions" guide. TODO: link to guide.
-
-h4. +require 'rails/application'+
-
-Here's where +Rails::Application+ is defined. This is the superclass of +YourApp::Application+ from _config/application.rb_ and the subclass of +Rails::Engine+ This is the main entry-point into the Rails initialization process as when your application is initialized, your class is the basis of its configuration.
-
-This file requires three important files before +Rails::Application+ is defined: _rails/railties_path.rb_, _rails/plugin.rb_ and _rails/engine.rb_.
-
-
-h4. +require 'rails/railties_path'+
-
-This file serves one purpose:
-
-<ruby>
- RAILTIES_PATH = File.expand_path(File.join(File.dirname(__FILE__), '..', '..'))
-</ruby>
-
-Helpful, hey? One must wonder why they just didn't define it outright.
-
-
-h4. +require 'rails/plugin'+
-
-Firstly this file requires _rails/engine.rb_, which defines our +Rails::Engine+ class, explained in the very next section.
-
-This file defines a class called +Rails::Plugin+ which descends from +Rails::Engine+.
-
-This defines the first few initializers for the Rails stack:
-
-* load_init_rb
-* sanity_check_railties_collisons
-
-These are explained in the Initialization section. TODO: First write initialization section then come back here and link.
-TODO: Expand.
-
-h4. +require 'rails/engine'+
-
-This file requires _rails/railtie.rb_ which defines +Rails::Railtie+.
-
-+Rails::Engine+ defines a couple of further initializers for your application:
-
-* set_load_path
-* set_autoload_paths
-* add_routing_paths
-* add_routing_namespaces
-* add_locales
-* add_view_paths
-* add_generator_templates
-* load_application_initializers
-* load_application_classes
-
-These are explained in the Initialization section. TODO: First write initialization section then come back here and link.
-
-Also in here we see that a couple of methods are +delegate+'d:
-
-<ruby>
- delegate :middleware, :paths, :root, :to => :config
-</ruby>
-
-This means when you call either the +middleware+, +paths+ or +root+ methods you are in reality calling +config.middleware+, +config.paths+ and +config.root+ respectively.
-
-+Rails::Engine+ descends from +Rails::Railtie+.
-
-h4. +require 'rails/railtie'+
-
-+Rails::Railtie+ (_pronounced Rail-tie, as in a bowtie_), provides a method of classes to hook into Rails, providing them with methods to add generators, rake tasks and subscribers. All of the facets of Rails are their own Railtie. and as you've probably already figured out, the engines that you use are railties too. Plugins also can be railties, but they do not have to be.
-
-Here there's requires to _rails/initializable.rb_ and and _rails/configurable.rb_.
-
-h4. +require 'rails/initializable'+
-
-The +Rails::Initializable+ module includes methods helpful for the initialization process in rails, such as the method to define initializers: +initializer+. This is included into +Rails::Railtie+ so it's available there as well as +Rails::Engine+, +Rails::Application+ and +YourApp::Application+. In here we also see the class definition for +Rails::Initializer+, the class for all initializer objects.
-
-h4. +require 'rails/configuration'+
-
-The +Rails::Configuration+ module sets up shared configuration for applications, engines and plugins alike.
-
-At the top of this file there are three +require+s:
-
-<ruby>
- require 'active_support/ordered_options'
- require 'rails/paths'
- require 'rails/rack'
-</ruby>
-
-h4. +require 'active_support/ordered_options'+
-
-+ActiveSupport::OrderedOptions+ is a special-purpose +OrderedHash+, used for keeping track of the options specified in the configuration of your application.
-
-TODO: expand.
-
-h4. +require 'rails/paths'+
-
-This file is used to set up the +Rails::Paths+ module which is used to set up helpers for referencing paths to the folders of your Rails application, such as in _railties/lib/rails/engine/configuration.rb_ where it is used to firstly define them:
-
-<ruby>
- def paths
- @paths ||= begin
- paths = Rails::Paths::Root.new(@root)
- paths.app "app", :eager_load => true, :glob => "*"
- paths.app.controllers "app/controllers", :eager_load => true
- paths.app.helpers "app/helpers", :eager_load => true
- paths.app.models "app/models", :eager_load => true
- paths.app.mailers "app/mailers", :eager_load => true
- paths.app.views "app/views", :eager_load => true
- paths.lib "lib", :load_path => true
- paths.lib.tasks "lib/tasks", :glob => "**/*.rake"
- paths.lib.templates "lib/templates"
- paths.config "config"
- paths.config.initializers "config/initializers", :glob => "**/*.rb"
- paths.config.locales "config/locales", :glob => "*.{rb,yml}"
- paths.config.routes "config/routes.rb"
- paths.public "public"
- paths.public.javascripts "public/javascripts"
- paths.public.stylesheets "public/stylesheets"
- paths
- end
- end
-</ruby>
-
-You can then get to these helper methods by calling +YourApp::Application.config.paths+.
-
-h4. +require 'rails/rack'+
-
-This file sets up some +autoload+'d constants for +Rails::Rack+:
-
-<ruby>
- module Rails
- module Rack
- autoload :Debugger, "rails/rack/debugger"
- autoload :Logger, "rails/rack/logger"
- autoload :LogTailer, "rails/rack/log_tailer"
- autoload :Static, "rails/rack/static"
- end
- end
-</ruby>
-
-h4. +require 'rails/version'+
-
-Now we're back to _rails.rb_. The line after +require 'rails/application'+ in _rails.rb_ is:
-
-<ruby>
- require 'rails/version'
-</ruby>
-
-The code in this file declares +Rails::VERSION+ so that the version number can easily be accessed. It stores it in constants, with the final version number being attainable by calling +Rails::VERSION::STRING+.
-
-h4. +require 'rails/deprecation'+
-
-This sets up a couple of familiar constants: +RAILS_ENV+, +RAILS_ROOT+ and +RAILS_DEFAULT_LOGGER+ to still be usable, but raise a deprecation warning when they are. Their alternatives are now +Rails.env+, +Rails.root+ and +Rails.logger+ respectively.
-
-If you wish to know more about how they're deprecated see the +require 'active_support/deprecation/proxy_wrappers'+ section. TODO: link to section.
-
-h4. +require 'rails/log_subscriber'+
-
-The +Rails::LogSubscriber+ provides a central location for logging in Rails 3 so as to not slow down the main thread. When you call one of the logging methods (+info+, +debug+, +warn+, +error+, +fatal+ or +unknown+) from the +Rails::LogSubscriber+ class or one of its subclasses this will notify the Rails logger to log this call in the fashion you specify, but will not write it to the file. The file writing is done at the end of the request, courtesy of the +Rails::Rack::Logger+ middleware.
-
-Each Railtie defines its own class that descends from +Rails::LogSubscriber+ with each defining its own methods for logging individual tasks.
-
-h4. +require 'rails/ruby_version_check'+
-
-This file ensures that you're running a minimum of 1.8.7. If you're running an older version, it will tell you:
-
-<pre>
- Rails requires Ruby version 1.8.7 or later.
- You're running [your Ruby version here]; please upgrade to continue.
-</pre>
-
-h4. +require 'activesupport/railtie'+
-
-This file declares two Railties, one for ActiveSupport and the other for I18n. In these Railties there's the following initializers defined:
-
-* active_support.initialize_whiny_nils
-* active_support.initialize_time_zone
-
-* i18n.initialize
-
-This Railtie also defines an an +after_initialize+ block, which will (as the name implies) be ran after the initialization process. More on this later. TODO: When you write the section you can link to it.
-
-h4. +require 'action_dispatch/railtie'+
-
-This file is explained in the ActionDispatch Railtie Section. TODO: link
-
-h4. Return to _rails/all.rb_
-
-Now that we've covered the extensive process of what the first line does in this file, lets cover the remainder:
-
-<ruby>
- %w(
- active_record
- action_controller
- action_mailer
- active_resource
- rails/test_unit
- ).each do |framework|
- begin
- require "#{framework}/railtie"
- rescue LoadError
- end
- end
-</ruby>
-
-As you may be able to tell from the code, this is going through and loading all the Railties for Active Record, Action Controller, Action Mailer, Active Resource. Two other Railties, one for Active Support and one for Action Dispatch were required earlier, but are still covered in this section for continuity reasons. TODO: link.
-
-h4. ActiveSupport Railtie
-
-From Active Support's README:
-
-Active Support is a collection of various utility classes and standard library extensions that were found useful for Rails.
-
-TODO: Quotify.
-
-h5. +require 'active_support/railtie'+
-
-
-h4. Active Record Railtie
-
-The Active Record Railtie takes care of hooking Active Record into Rails. This depends on Active Support, Active Model and Arel. From Active Record's readme:
-
-TODO: Quotify.
-
-<plain>
- Active Record connects business objects and database tables to create a persistable domain model where logic and data are presented in one wrapping. It's an implementation of the object-relational mapping (ORM) pattern by the same name as described by Martin Fowler:
-
- "An object that wraps a row in a database table or view, encapsulates
- the database access, and adds domain logic on that data."
-
- Active Record's main contribution to the pattern is to relieve the original of two stunting problems:
- lack of associations and inheritance. By adding a simple domain language-like set of macros to describe
- the former and integrating the Single Table Inheritance pattern for the latter, Active Record narrows the
- gap of functionality between the data mapper and active record approach.
-</plain>
-
-h5. +require "active_record/railtie"+
-
-The _activerecord/lib/active_record/railtie.rb_ file defines the Railtie for Active Record.
-
-This file first requires Active Record, the _railties/lib/rails.rb_ file which has already been required and so will be ignored, and the Active Model Railtie:
-
-<ruby>
- require "active_record"
- require "rails"
- require "active_model/railtie"
-</ruby>
-
-Active Model's Railtie is covered in the next section. TODO: Section.
-
-h5. +require "active_record"+
-
-TODO: Why are +activesupport_path+ and +activemodel_path+ defined here?
-
-The first three requires require ActiveSupport, Active Model and Arel in that order:
-
-<ruby>
- require 'active_support'
- require 'active_model'
- require 'arel'
-</ruby>
-
-
-h5. +require "active_support"+
-
-This was loaded earlier by _railties/lib/rails.rb_. This line is here as a safeguard for when Active Record is loaded outside the scope of Rails.
-
-h5. +require "active_model"+
-
-TODO: Again with the +activesupport_path+!
-
-Here we see another +require "active_support"+ this is again, a safeguard for when Active Model is loaded outside the scope of Rails.
-
-This file defines a few +autoload+'d modules for Active Model, requires +active_support/i18n+ and adds the default translation file for Active Model to +I18n.load_path+.
-
-The +require 'active_support/i18n'+ just loads I18n and adds Active Support's default translations file to +I18n.load_path+ too:
-
-<ruby>
- require 'i18n'
- I18n.load_path << "#{File.dirname(__FILE__)}/locale/en.yml
-</ruby>
-
-
-h5. +require "arel"+
-
-This file in _arel/lib/arel.rb_ loads a couple of Active Support things first:
-
-<ruby>
- require 'active_support/inflector'
- require 'active_support/core_ext/module/delegation'
- require 'active_support/core_ext/class/attribute_accessors'
-</ruby>
-
-These files are explained in the "Common Includes" section.
-
-h5. +require 'arel'+
-
-Back in _arel/lib/arel.rb_, the next two lines require Active Record parts:
-
-<ruby>
- require 'active_record'
- require 'active_record/connection_adapters/abstract/quoting'
-</ruby>
-
-Because we're currently loading _active_record.rb_, it skips right over it.
-
-h5. +require 'active_record/connection_adapters/abstract/quoting'+
-
-_activerecord/lib/active_record/connection_adapters/abstract/quoting.rb_ defines methods used for quoting fields and table names in Active Record.
-
-TODO: Explain why this is loaded especially.
-
-h5. +require 'active_record'+
-
-Back the initial require from the _railtie.rb_.
-
-The _active_support_ and _active_model_ requires are again just an insurance for if we're loading Active Record outside of the scope of Rails. In _active_record.rb_ the ActiveRecord +Module+ is initialized and in it there is defined a couple of +autoloads+ and +eager_autoloads+.
-
-There's a new method here called +autoload_under+ which is defined in +ActiveSupport::Autoload+. This sets the autoload path to temporarily be the specified path, in this case +relation+ for the +autoload+'d classes inside the block.
-
-Inside this file the +AttributeMethods+, +Locking+ and +ConnectionAdapter+ modules are defined inside the +ActiveRecord+ module. The second to last line tells Arel what SQL engine we want to use. In this case it's +ActiveRecord::Base+. The final line adds in the translations for Active Record which are only for if a record is invalid or non-unique.
-
-h5. +require 'rails'+
-
-As mentioned previously this is skipped over as it has been already loaded. If you'd still like to see what this file does go to section TODO: section.
-
-h5. +require 'active_model/railtie'+
-
-This is covered in the Active Model Railtie section. TODO: link there.
-
-h5. +require 'action_controller/railtie'+
-
-This is covered in the Action Controller Railtie section. TODO: link there.
-
-h5. The Active Record Railtie
-
-Inside the Active Record Railtie the +ActiveRecord::Railtie+ class is defined:
-
-<ruby>
- module ActiveRecord
- class Railtie < Rails::Railtie
-
- ...
- end
- end
-</ruby>
-
-TODO: Explain the logger.
-
-By doing this the +ActiveRecord::Railtie+ class gains access to the methods contained within +Rails::Railtie+ such as +rake_tasks+, +log_subscriber+ and +initiailizer+, all of which the Railtie is using in this case. The initializers defined here are:
-
-* active_record.initialize_timezone
-* active_record.logger
-* active_record.set_configs
-* active_record.initialize_database
-* active_record.log_runtime
-* active_record.initialize_database_middleware
-* active_record.load_observers
-* active_record.set_dispatch_hooks
-
-As with the engine initializers, these are explained later.
-
-
-h4. Active Model Railtie
-
-This Railtie is +require+'d by Active Record's Railtie.
-
-From the Active Model readme:
-
-<plain>
- Prior to Rails 3.0, if a plugin or gem developer wanted to be able to have an object interact with Action Pack helpers, it was required to either copy chunks of code from Rails, or monkey patch entire helpers to make them handle objects that did not look like Active Record. This generated code duplication and fragile applications that broke on upgrades.
-
- Active Model is a solution for this problem.
-
- Active Model provides a known set of interfaces that your objects can implement to then present a common interface to the Action Pack helpers.
-</plain>
-
-
-h5. +require "active_model/railtie"+
-
-This Railtie file, _activemodel/lib/active_model/railtie.rb_ is quite small and only requires in +active_model+. As mentioned previously, the require to _rails_ is skipped over as it has been already loaded. If you'd still like to see what this file does go to section TODO: section.
-
-<ruby>
- require "active_model"
- require "rails"
-</ruby>
-
-h5. +require "active_model"+
-
-Active Model depends on Active Support and ensures it is required by making a +require 'active_support'+ call. It has already been loaded from _railties/lib/rails.rb_ so will not be reloaded for us here. The file goes on to define the +ActiveModel+ module and all of its autoloaded classes. This file also defines the english translations for some of the validation messages provided by Active Model, such as "is not included in the list" and "is reserved".
-
-h4. Action Controller Railtie
-
-The Action Controller Railtie takes care of all the behind-the-scenes code for your controllers; it puts the C into MVC; and does so by implementing the +ActionController::Base+ class which you may recall is where your +ApplicationController+ class descends from.
-
-h5. +require 'action_controller/railtie'+
-
-This first makes a couple of requires:
-
-<ruby>
- require "action_controller"
- require "rails"
- require "action_view/railtie"
-</ruby>
-
-The _action_controller_ file is explained in the very next section. The require to _rails_ is requiring the already-required _railties/lib/rails.rb_. If you wish to know about the require to _action_view/railtie_ this is explained in the Action View Railtie section.
-
-h5. +require 'action_controller+
-
-This file, _actionpack/lib/action_controller.rb_, defines the Action Controller module and its relative autoloads. Before it does any of that it makes two requires: one to _abstract_controller_, explored next, and the other to _action_dispatch_, explored directly after that.
-
-h5. +require 'abstract_controller'+
-
-+AbstractController+ provides the functionality of TODO.
-
-This file is in _actionpack/lib/abstract_controller.rb_ and begins by attempting to add the path to Active Support to the load path, which it would succeed in if it wasn't already set by anything loaded before it. In this case, it's not going to be set due to Arel already loading it in (TODO: right?).
-
-The next thing in this file four +require+ calls:
-
-<ruby>
- require 'active_support/ruby/shim'
- require 'active_support/dependencies/autoload'
- require 'active_support/core_ext/module/attr_internal'
- require 'active_support/core_ext/module/delegation'
-</ruby>
-
-After these require calls the +AbstractController+ module is defined with some standard +autoload+'d classes.
-
-
-h5. +require 'active_support/ruby/shim'+
-
-This file is explained in the "Common Includes" section beneath.
-
-h5. +require 'active_support/dependencies/autoload+
-
-This file was loaded upon the first require of +active_support+ and is not included. If you wish to be refreshed on what this file performs visit TODO: link to section.
-
-h5. +require 'active_support/core_ext/module/attr_internal'+
-
-This file is explained in the "Common Includes" section as it is required again later on. See the TODO: section. I also think this may be explained in the Active Support Core Extensions guide.
-
-h5. +require 'active_support/core_ext/module/delegation'+
-
-This file is explained in the "Common Includes" section as it has already been required by Arel at this point in the initialization process (see: section TODO: LINK!).
-
-h5. +require 'action_controller'+
-
-Back to _actionpack/lib/action_controller.rb_.
-
-After the initial call to +require 'abstract_controller'+, this calls +require 'action_dispatch'+ which was required earlier by _railties/lib/rails.rb_. The purpose of this file is explained in the ActionDispatch Railtie section.
-
-This file defines the +ActionController+ module and its autoloaded classes.
-
-Here we have a new method called +autoload_under+. This was covered in the Active Record Railtie but it is covered here also just in case you missed or skimmed over it. The +autoload_under+ method is defined in +ActiveSupport::Autoload+ and it sets the autoload path to temporarily be the specified path, in this case by specifying _metal_ it will load the specified +autoload+'d classes from _lib/action_controller/metal_ inside the block.
-
-Another new method we have here is called +autoload_at+:
-
-<ruby>
- autoload_at "action_controller/metal/exceptions" do
- autoload :ActionControllerError
- autoload :RenderError
- autoload :RoutingError
- autoload :MethodNotAllowed
- autoload :NotImplemented
- autoload :UnknownController
- autoload :MissingFile
- autoload :RenderError
- autoload :SessionOverflowError
- autoload :UnknownHttpMethod
- end
-</ruby>
-
-This defines the path of which to find these classes defined at and is most useful for if you have multiple classes defined in a single file, as is the case for this block; all of those classes are defined inside _action_controller/metal/exceptions.rb_ and when Active Support goes looking for them it will look in that file.
-
-At the end of this file there are a couple more requires:
-
-<ruby>
- # All of these simply register additional autoloads
- require 'action_view'
- require 'action_controller/vendor/html-scanner'
-
- # Common Active Support usage in ActionController
- require 'active_support/concern'
- require 'active_support/core_ext/class/attribute_accessors'
- require 'active_support/core_ext/load_error'
- require 'active_support/core_ext/module/attr_internal'
- require 'active_support/core_ext/module/delegation'
- require 'active_support/core_ext/name_error'
- require 'active_support/inflector'
-</ruby>
-
-h5. +require 'action_view'+
-
-This is best covered in the Action View Railtie section, so skip there by TODO: Link / page?
-
-h5. +require 'action_controller/vendor/html-scanner'+
-
-TODO: What is the purpose of this? Find out.
-
-h5. +require 'active_support/concern'+
-
-TODO: I can kind of understand the purpose of this.. need to see where @_dependencies is used however.
-
-h5. +require 'active_support/core_ext/class/attribute_accessors'+
-
-This file defines, as the path implies, attribute accessors for class. These are +cattr_reader+, +cattr_writer+, +cattr_accessor+.
-
-h5. +require 'active_support/core_ext/load_error'+
-
-The Active Support Core Extensions (TODO: LINK!) guide has a great coverage of what this file precisely provides.
-
-h5. +require 'active_support/core_ext/module/attr_internal'+
-
-This file is explained in the "Core Extension" guide.
-
-This file was required through the earlier _abstract_controller.rb_ require.
-
-h5. +require 'active_support/core_ext/module/delegation'+
-
-This file is explained in the "Common Includes" section.
-
-This file was required earlier by Arel and so is not required again.
-
-h5. +require 'active_support/core_ext/name_error'+
-
-This file includes extensions to the +NameError+ class, providing the +missing_name+ and +missing_name?+ methods. For more information see the Active Support Core Extensions guide.
-
-h5. +require 'active_support/inflector'+
-
-This file is explained in the "Common Includes" section.
-
-This file was earlier required by Arel and so is not required again.
-
-h5. Action Controller Railtie
-
-So now we come back to the Action Controller Railtie with a couple more requires to go before +ActionController::Railtie+ is defined:
-
-<ruby>
- require "action_view/railtie"
- require "active_support/core_ext/class/subclasses"
- require "active_support/deprecation/proxy_wrappers"
- require "active_support/deprecation"
-</ruby>
-
-As explained previously the +action_view/railtie+ file will be explained in the Action View Railtie section. TODO: link to it.
-
-h5. +require 'active_support/core_ext/class/subclasses'+
-
-For an explanation of this file _activesupport/lib/active_support/core_ext/class/subclasses_, see the Active Support Core Extension guide.
-
-h5. +require 'active_support/deprecation/proxy_wrappers'+
-
-This file, _activesupport/lib/active_support/deprecation/proxy_wrappers.rb_, defines a couple of deprecation classes, which are +DeprecationProxy+, +DeprecationObjectProxy+, +DeprecationInstanceVariableProxy+, +DeprecationConstantProxy+ which are all namespaced into +ActiveSupport::Deprecation+. These last three are all subclasses of +DeprecationProxy+.
-
-Why do we mention them here? Beside the obvious-by-now fact that we're covering just about everything about the initialization process in this guide, if you're deprecating something in your library and you use Active Support, you too can use the +DeprecationProxy+ class (and it's subclasses) too.
-
-
-h6. +DeprecationProxy+
-
-This class is used only in _railties/lib/rails/deprecation.rb_, loaded further on in the initialization process. It's used in this way:
-
-<ruby>
- RAILS_ROOT = (Class.new(ActiveSupport::Deprecation::DeprecationProxy) do
- cattr_accessor :warned
- self.warned = false
-
- def target
- Rails.root
- end
-
- def replace(*args)
- warn(caller, :replace, *args)
- end
-
- def warn(callstack, called, args)
- unless warned
- ActiveSupport::Deprecation.warn("RAILS_ROOT is deprecated! Use Rails.root instead", callstack)
- self.warned = true
- end
- end
- end).new
-</ruby>
-
-There is similar definitions for the other constants of +RAILS_ENV+ and +RAILS_DEFAULT_LOGGER+. All three of these constants are in the midst of being deprecated (most likely in Rails 3.1) so Rails will tell you if you reference them that they're deprecated using the +DeprecationProxy+ class. Whenever you call +RAILS_ROOT+ this will raise a warning, telling you: "RAILS_ROOT is deprecated! Use Rails.root instead".... TODO: investigate if simply calling it does raise this warning. This same rule applies to +RAILS_ENV+ and +RAILS_DEFAULT_LOGGER+, their new alternatives are +Rails.env+ and +Rails.logger+ respectively.
-
-h6. +DeprecatedObjectProxy+
-
-This is used in one place _actionpack/lib/action_controller/railtie.rb_, which you may remember is how we got to the +DeprecationProxy+ section:
-
-<ruby>
- ActiveSupport::Deprecation::DeprecatedObjectProxy.new(app.routes, message)
-</ruby>
-
-This makes more sense in the wider scope of the initializer:
-
-<ruby>
- initializer "action_controller.url_helpers" do |app|
- ActionController.base_hook do
- extend ::ActionController::Railtie::UrlHelpers.with(app.routes)
- end
-
- message = "ActionController::Routing::Routes is deprecated. " \
- "Instead, use Rails.application.routes"
-
- proxy = ActiveSupport::Deprecation::DeprecatedObjectProxy.new(app.routes, message)
- ActionController::Routing::Routes = proxy
- end
-</ruby>
-
-+ActionController::Routing::Routes+ was the previous constant used in defining routes in Rails 2 applications, now it's simply a method on +Rails.application+ rather than it's own individual class: +Rails.application.routes+. Both of these still call the +draw+ method on the returned object to end up defining the routes.
-
-
-h6. +DeprecatedInstanceVariableProxy+
-
-This isn't actually used anywhere in Rails anymore. It was used previously for when +@request+ and +@params+ were deprecated in Rails 2. It has been kept around as it could be useful for the same purposes in libraries that use Active Support.
-
-h6. +DeprecatedConstantProxy+
-
-This method is used in a couple of places, _activesupport/lib/active_support/json/encoding.rb_ and _railties/lib/rails/rack.rb_.
-
-In _encoding.rb_ it's used to define a constant that's now been deprecated:
-
-<ruby>
- CircularReferenceError = Deprecation::DeprecatedConstantProxy.new('ActiveSupport::JSON::CircularReferenceError', Encoding::CircularReferenceError)
-</ruby>
-
-
-Now when you reference +ActiveSupport::JSON::CircularReferenceError+ you'll receive a warning:
-
-<plain>
- ActiveSupport::JSON::CircularReferenceError is deprecated! Use Encoding::CircularReferenceError instead.
-</plain>
-
-h5. +require "active_support/deprecation"+
-
-This re-opens the +ActiveSupport::Deprecation+ module which was already defined by our deprecation proxies. Before this happens however we have 4 requires:
-
-<ruby>
- require 'active_support/deprecation/behaviors'
- require 'active_support/deprecation/reporting'
- require 'active_support/deprecation/method_wrappers'
- require 'active_support/deprecation/proxy_wrappers'
-</ruby>
-
-The remainder of this file goes about setting up the +silenced+ and +debug+ accessors:
-
-<ruby>
- module ActiveSupport
- module Deprecation #:nodoc:
- class << self
- # The version the deprecated behavior will be removed, by default.
- attr_accessor :deprecation_horizon
- end
- self.deprecation_horizon = '3.0'
-
- # By default, warnings are not silenced and debugging is off.
- self.silenced = false
- self.debug = false
- end
- end
-</ruby>
-
-h5. +require "active_support/deprecation/behaviors"+
-
-This sets up some default behavior for the warnings raised by +ActiveSupport::Deprecation+, defining different ones for _development_ and _test_ and nothing for production, as we never want deprecation warnings in production:
-
-<ruby>
- # Default warning behaviors per Rails.env. Ignored in production.
- DEFAULT_BEHAVIORS = {
- 'test' => Proc.new { |message, callstack|
- $stderr.puts(message)
- $stderr.puts callstack.join("\n ") if debug
- },
- 'development' => Proc.new { |message, callstack|
- logger =
- if defined?(Rails) && Rails.logger
- Rails.logger
- else
- require 'logger'
- Logger.new($stderr)
- end
- logger.warn message
- logger.debug callstack.join("\n ") if debug
- }
- }
-</ruby>
-
-In the _test_ environment, we will see the deprecation errors displayed in +$stderr+ and in _development_ mode, these are sent to +Rails.logger+ if it exists, otherwise it is output to +$stderr+ in a very similar fashion to the _test_ environment. These are both defined as procs, so Active Support can pass arguments to the +call+ method we call on it when Active Support +warn+.
-
-h5. +require 'active_support/deprecation/reporting'+
-
-This file defines further extensions to the +ActiveSupport::Deprecation+ module, including the +warn+ method which is used from Active Support's +DeprecationProxy+ class and an +attr_accessor+ on the class called +silenced+. This checks that we have a behavior defined, which we do in the _test_ and _development_ environments, and that we're not +silenced+ before warning about deprecations by +call+'ing the +Proc+ time.
-
-This file also defines a +silence+ method on the module also which you can pass a block to temporarily silence errors:
-
-<ruby>
- ActiveSupport::Deprecation.silence do
- puts "YOU CAN FIND ME HERE: #{RAILS_ROOT}"
- end
-</ruby>
-
-TODO: may have to correct this example.
-
-h5. +require 'active_support/deprecation/method_wrappers'+
-
-This file defines a class method on +ActiveSupport::Deprecation+ called +deprecate_methods+. This method is used in _activesupport/lib/active_support/core_ext/module/deprecation.rb_ to allow you to declare deprecated methods on modules:
-
-<ruby>
- class Module
- # Declare that a method has been deprecated.
- # deprecate :foo
- # deprecate :bar => 'message'
- # deprecate :foo, :bar, :baz => 'warning!', :qux => 'gone!'
- def deprecate(*method_names)
- ActiveSupport::Deprecation.deprecate_methods(self, *method_names)
- end
- end
-</ruby>
-
-h5. +require 'action_controller/railtie'+
-
-Inside +ActionController::Railtie+ there are another two requires:
-
-<ruby>
- require "action_controller/railties/log_subscriber"
- require "action_controller/railties/url_helpers"
-</ruby>
-
-
-h5. +require 'action_controller/railties/log_subscriber'+
-
-+ActionController::Railties::LogSubscriber+ inherits from +Rails::LogSubscriber+ and defines methods for logging such things as action processing and file sending.
-
-h5. +require 'action_controller/railties/url_helpers'+
-
-This file defines a +with+ method on +ActionController::Railtie::UrlHelpers+ which is later used in the +action_controller.url_helpers+ initializer. For more information see the +action_controller.url_helpers+ initializer section.
-
-h5. Action Controller Railtie
-
-After these requires it deprecates a couple of ex-Action Controller methods and points whomever references them to their ActionDispatch equivalents. These methods are +session+, +session=+, +session_store+ and +session_store=+.
-
-After the deprecations, Rails defines the +log_subscriber+ to be a new instance of +ActionController::Railties::LogSubscriber+ and then go about defining the following initializers, keeping in mind that these are added to the list of initializers defined before hand:
-
-* action_controller.logger
-* action_controller.set_configs
-* action_controller.initialize_framework_caches
-* action_controller.set_helpers_path
-* action_controller.url_helpers
-
-h4. Action View Railtie
-
-The Action View Railtie provides the backend code for your views and it puts the C into MVC. This implements the +ActionView::Base+ of which all views and partials are objects of.
-
-h5. +require 'action_view/railtie'+
-
-The Railtie is defined in a file called _actionpack/lib/action_view/railtie.rb_ and initially makes a call to +require 'action_view'+.
-
-h5. +require 'action_view'+
-
-Here again we have the addition of the path to Active Support to the load path attempted, but because it's already in the load path it will not be added. Similarly, we have two requires:
-
-<ruby>
- require 'active_support/ruby/shim'
- require 'active_support/core_ext/class/attribute_accessors'
-</ruby>
-
-And these have already been required. If you wish to know what these files do go to the explanation of each in the "Common Includes" section. TODO: link to them!
-
-This file goes on to +require 'action_pack'+ which consists of all this code (comments stripped):
-
-<ruby>
- require 'action_pack/version'
-</ruby>
-
-the _version_ file contains this code (comments stripped):
-
-<ruby>
- module ActionPack #:nodoc:
- module VERSION #:nodoc:
- MAJOR = 3
- MINOR = 1
- TINY = 0
- BUILD = "beta"
-
- STRING = [MAJOR, MINOR, TINY, BUILD].join('.')
- end
- end
-</ruby>
-
-TODO: Why?!
-
-This file goes on to define the +ActionView+ module and its +autoload+'d modules and then goes on to make two more requires:
-
-<ruby>
- require 'active_support/core_ext/string/output_safety'
- require 'action_view/base'
-</ruby>
-
-h5. +require 'active_support/core_ext/string/output_safety'+
-
-The _actionpack/lib/active_support/core_ext/string/output_saftey.rb_ file is responsible for the code used in escaping HTML and JSON, namely the +html_escape+ and +json_escape+ methods. It does this by overriding these methods in +Erb::Util+ which is later included into +ActionView::Base+. This also defines +ActiveSupport::SafeBuffer+ which descends from +String+ and is used for concatenating safe output from your views to ERB templates.
-
-h5. +require 'action_view/base'+
-
-This file initially makes requires to the following files:
-
-<ruby>
- require 'active_support/core_ext/module/attr_internal'
- require 'active_support/core_ext/module/delegation'
- require 'active_support/core_ext/class/attribute'
-</ruby>
-
-These are explained in their relevant areas inside the "Common Includes" section.
-
-The remainder of this file sets up the +ActionView+ module and the +ActionView::Base+ class which is the class of all view templates. Inside of +ActionView::Base+ it makes an include to several helper modules:
-
-<ruby>
- include Helpers, Rendering, Partials, Layouts, ::ERB::Util, Context
-</ruby>
-
-h5. +ActionView::Helpers+
-
-This module, from _actionpack/lib/action_view/helpers.rb_, initially sets up the +autoload+'s for the various +ActionView::Helpers+ modules (TODO: mysteriously not using +autoload_under+). This also sets up a +ClassMethods+ module which is included automatically into wherever +ActionView::Helpers+ is included by defining a +self.included+ method:
-
-<ruby>
- def self.included(base)
- base.extend(ClassMethods)
- end
-
- module ClassMethods
- include SanitizeHelper::ClassMethods
- end
-</ruby>
-
-Inside of +SanitizeHelper::ClassMethods+ it defines, of course, methods for assisting with sanitizing in Rails such as +link_sanitizer+ which is used by the +strip_links+ method.
-
-Afterwards this includes the +ActiveSupport::Benchmarkable+ which is used for benchmarking how long a specific thing takes in a view. The method is simply +benchmark+ and can be used like this:
-
-<ruby>
- benchmark("potentially long running thing") do
- Post.count
- end
-</ruby>
-
-The "documentation":http://api.rubyonrails.org/classes/ActiveSupport/Benchmarkable.html is great about explaining what precisely this does.
-
-This module is also included into Active Record and +AbstractController+, meaning you can also use the +benchmark+ method in these methods.
-
-After including +ActiveSupport::Benchmarkable+, the helpers which we have declared to be +autoload+'d are included. I will not go through and cover what each of these helpers do, as their names should be fairly explicit about it, and it's not really within the scope of this guide.
-
-h5. +ActionView::Rendering+
-
-This module, from _actionpack/lib/action_view/render/rendering.rb_ defines a method you may be a little too familiar with: +render+. This is the +render+ use for rendering all kinds of things, such as partials, templates and text.
-
-h5. +ActionView::Partials+
-
-This module, from _actionpack/lib/action_view/render/partials.rb_, defines +ActionView::Partials::PartialRenderer+ which you can probably guess is used for rendering partials.
-
-h5. +ActionView::Layouts+
-
-This module, from _actionpack/lib/action_view/render/layouts.rb_, defines +ActionView::Layouts+ which defines methods such as +find_layout+ for locating layouts.
-
-h5. +ERB::Util+
-
-The +ERB::Util+ module from Ruby core, as the document describes it: "A utility module for conversion routines, often handy in HTML generation". It offers two methods +html_escape+ and +url_encode+, with a third called +json_escape+ being added in by the requirement of _actionpack/lib/active_support/core_ext/string/output_saftey.rb_ earlier. As explained earlier, +html_escape+ is overridden to return a string marked as safe.
-
-h5. +ActionView::Context+
-
-TODO: Not entirely sure what this is all about. Something about the context of view rendering... can't work it out.
-
-h5. Action View Railtie
-
-Now that _actionpack/lib/action_view.rb_ has been required, the next step is to +require 'rails'+, but this will be skipped as the file was required by _railties/lib/rails/all.rb_ way back in the beginnings of the initialization process.
-
-Next, the Railtie itself is defined:
-
-
-<ruby>
- module ActionView
- class Railtie < Rails::Railtie
- railtie_name :action_view
-
- require "action_view/railties/log_subscriber"
- log_subscriber ActionView::Railties::LogSubscriber.new
-
- initializer "action_view.cache_asset_id" do |app|
- unless app.config.cache_classes
- ActiveSupport.on_load(:action_view) do
- ActionView::Helpers::AssetTagHelper::AssetPaths.cache_asset_ids = false
- end
- end
- end
- end
- end
-</ruby>
-
-The +ActionView::LogSubscriber+ sets up a method called +render_template+ which is called when a template is rendered. TODO: Templates only or partials and layouts also? I would imagine these fall under the templates category, but there needs to research to ensure this is correct.
-
-The sole initializer defined here, _action_view.cache_asset_ids_ is responsible for caching the timestamps on the ends of your assets. If you've ever seen a link generated by +image_tag+ or +stylesheet_link_tag+ you would know that I mean that this timestamp is the number after the _?_ in this example: _/javascripts/prototype.js?1265442620_. This initializer will do nothing if +cache_classes+ is set to false in any of your application's configuration. TODO: Elaborate.
-
-h4. Action Mailer Railtie
-
-The Action Mailer Railtie is responsible for including all the emailing functionality into Rails by way of the Action Mailer gem itself. Action Mailer is:
-
-Action Mailer is a framework for designing email-service layers. These layers
-are used to consolidate code for sending out forgotten passwords, welcome
-wishes on signup, invoices for billing, and any other use case that requires
-a written notification to either a person or another system.
-
-Action Mailer is in essence a wrapper around Action Controller and the
-Mail gem. It provides a way to make emails using templates in the same
-way that Action Controller renders views using templates.
-
-TODO: Quotify.
-
-h5. +require 'action_mailer/railtie'+
-
-This file first makes two requires:
-
-<ruby>
- require "action_mailer"
- require "rails"
-</ruby>
-
-The requires in +action_mailer+ are already loaded or are core extensions:
-
-<ruby>
- require 'abstract_controller'
- require 'action_view'
-
- # Common Active Support usage in Action Mailer
- require 'active_support/core_ext/class'
- require 'active_support/core_ext/object/blank'
- require 'active_support/core_ext/array/uniq_by'
- require 'active_support/core_ext/module/attr_internal'
- require 'active_support/core_ext/module/delegation'
- require 'active_support/core_ext/string/inflections'
- require 'active_support/lazy_load_hooks'
-</ruby>
-
-_abstract_controller_ is covered in the "Action Controller Railtie" section. TODO: Cover AbstractController there and link to it.
-_action_view_ was required by the Action View Railtie and will not be required again.
-
-For the core extensions you may reference the "Core Extensions" guide. TODO: Link to guide.
-
-_active_support/lazy_load_hooks_ was covered earlier in the guide and since it has already been required at this point in the initialization process, it will not be required again.
-
-The +require "rails"+ is referencing the _railties/lib/rails.rb_ file which was included back in TODO: link to section.
-
-_actionmailer/lib/action_mailer.rb_ then goes on to define the +ActionMailer+ module:
-
-<ruby>
- module ActionMailer
- extend ::ActiveSupport::Autoload
-
- autoload :AdvAttrAccessor
- autoload :Collector
- autoload :Base
- autoload :DeliveryMethods
- autoload :DeprecatedApi
- autoload :MailHelper
- autoload :OldApi
- autoload :Quoting
- autoload :TestCase
- autoload :TestHelper
- end
-</ruby>
-
-And a +Text+ module too:
-
-<ruby>
- module Text
- extend ActiveSupport::Autoload
-
- autoload :Format, 'text/format'
- end
-</ruby>
-
-which is used by the +ActionMailer::MailerHelper+ method +block_format+:
-
-<ruby>
- def block_format(text)
- formatted = text.split(/\n\r\n/).collect { |paragraph|
- Text::Format.new(
- :columns => 72, :first_indent => 2, :body_indent => 2, :text => paragraph
- ).format
- }.join("\n")
-
- # Make list points stand on their own line
- formatted.gsub!(/[ ]*([*]+) ([^*]*)/) { |s| " #{$1} #{$2.strip}\n" }
- formatted.gsub!(/[ ]*([#]+) ([^#]*)/) { |s| " #{$1} #{$2.strip}\n" }
-
- formatted
- end
-</ruby>
-
-h5. Action Mailer Railtie
-
-The Railtie defines the +log_subscriber+ as +ActionMailer::Railties::LogSubscriber.new+, with this class having two logging methods: one for delivery called +deliver+ and one for receipt called +receive+.
-
-The initializers defined in this Railtie are:
-
-* action_mailer.url_for
-* action_mailer.logger
-* action_mailer.set_configs
-
-These are covered later on the Initialization section. TODO: first write then link to Initialization section.
-
-h4. Active Resource Railtie
-
-The Active Resource Railtie is responsible for creating an interface into remote sites that offer a REST API. The Active Resource Railtie depends on Active Support and Active Model.
-
-h5. +require 'active_resource/railtie'+
-
-This file defines the Active Resource Railtie:
-
-<ruby>
- require "active_resource"
- require "rails"
-
- module ActiveResource
- class Railtie < Rails::Railtie
- railtie_name :active_resource
-
- require "active_resource/railties/log_subscriber"
- log_subscriber ActiveResource::Railties::LogSubscriber.new
-
- initializer "active_resource.set_configs" do |app|
- app.config.active_resource.each do |k,v|
- ActiveResource::Base.send "#{k}=", v
- end
- end
- end
- end
-</ruby>
-
-The +require 'rails'+ has already been done back in TODO: link to section.
-
-h5. +require 'active_resource'+
-
-This file, _activeresource/lib/active_resource.rb_, defines the +ActiveResource+ module, first off this will add the path to Active Support and Active Model to the load path if it's not already there, then require both +active_support+ (_activesupport/lib/active_support.rb_) and +active_model+ (_activemodel/lib/active_model.rb_)
-
-<ruby>
- activesupport_path = File.expand_path('../../../activesupport/lib', __FILE__)
- $:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.include?(activesupport_path)
-
- activemodel_path = File.expand_path('../../../activemodel/lib', __FILE__)
- $:.unshift(activemodel_path) if File.directory?(activemodel_path) && !$:.include?(activemodel_path)
-
- require 'active_support'
- require 'active_model'
-
- module ActiveResource
- extend ActiveSupport::Autoload
-
- autoload :Base
- autoload :Connection
- autoload :CustomMethods
- autoload :Formats
- autoload :HttpMock
- autoload :Observing
- autoload :Schema
- autoload :Validations
- end
-</ruby>
-
-h5. Active Resource Railtie
-
-The Railtie itself is fairly short as Active Resource is the smallest component of Rails.
-
-<ruby>
- module ActiveResource
- class Railtie < Rails::Railtie
- railtie_name :active_resource
-
- require "active_resource/railties/log_subscriber"
- log_subscriber ActiveResource::Railties::LogSubscriber.new
-
- initializer "active_resource.set_configs" do |app|
- app.config.active_resource.each do |k,v|
- ActiveResource::Base.send "#{k}=", v
- end
- end
- end
- end
-</ruby>
-
-The Railtie defines the +log_subscriber+ as +ActiveResource::Railties::LogSubscriber.new+ which has one method defined: +request+. +request+ is used whenever a request is made to an external service.
-
-There is only one initializer defined here: +set_configs+. This is covered later in the Initialization section.
-
-
-h4. ActionDispatch Railtie
-
-ActionDispatch handles all dispatch work for Rails. It interfaces with Action Controller to determine what action to undertake when a request comes in. TODO: I would quote the README but it is strangely absent. Flyin' blind here!
-
-The ActionDispatch Railtie was previously required when we called +require 'rails'+, but we will cover the Railtie here too.
-
-ActionDispatch depends on Active Support.
-
-h5. +require 'action_dispatch/railtie'+
-
-This file defines the ActionDispatch Railtie:
-
-<ruby>
- require "action_dispatch"
- require "rails"
-
- module ActionDispatch
- class Railtie < Rails::Railtie
- railtie_name :action_dispatch
-
- config.action_dispatch.x_sendfile_header = "X-Sendfile"
- config.action_dispatch.ip_spoofing_check = true
-
- # Prepare dispatcher callbacks and run 'prepare' callbacks
- initializer "action_dispatch.prepare_dispatcher" do |app|
- # TODO: This used to say unless defined?(Dispatcher). Find out why and fix.
- require 'rails/dispatcher'
- ActionDispatch::Callbacks.to_prepare { app.routes_reloader.reload_if_changed }
- end
- end
- end
-</ruby>
-
-The +require 'rails'+ has already been done back in TODO: link to section.
-
-
-
-
-h5. +require 'action_dispatch'+
-
-This file was already loaded earlier in the initialization process. TODO: link to it.
-
-h5. ActionDispatch Railtie
-
-The ActionDispatch Railtie is almost as short as the Active Resource Railtie:
-
-<ruby>
- require "action_dispatch"
- require "rails"
-
- module ActionDispatch
- class Railtie < Rails::Railtie
- railtie_name :action_dispatch
-
- config.action_dispatch.x_sendfile_header = "X-Sendfile"
- config.action_dispatch.ip_spoofing_check = true
-
- # Prepare dispatcher callbacks and run 'prepare' callbacks
- initializer "action_dispatch.prepare_dispatcher" do |app|
- # TODO: This used to say unless defined?(Dispatcher). Find out why and fix.
- require 'rails/dispatcher'
- ActionDispatch::Callbacks.to_prepare { app.routes_reloader.reload_if_changed }
- end
- end
- end
-</ruby>
-
-The +config+ method here is from +Rails::Railtie+ and pertains to your application's configuration. In this case, it is setting up some defaults which you can later override in _config/application.rb_.
-
-This Railtie does not define a +log_subscriber+ and only defines one initializer: +prepare_dispatcher+.
-
-h3. Return to _config/application.rb_
-
-Now that Rails has finished loading all the Railties by way of +require 'rails/all'+ Rails can now move on to the next line:
-
-<ruby>
- Bundler.require :default, Rails.env
-</ruby>
-
-NOTE: It is worth mentioning here that you are not tied to using Bundler with Rails 3, but it is (of course) advised that you do. To "turn off" Bundler, comment out or remove the corresponding lines in _config/application.rb_ and _config/boot.rb_.
-
-Bundler was +require+'d back in _config/boot.rb_, and so that is what makes it available here. This guide does not dive into the internals of Bundler; it's really it's own separate guide.
-
-The +Bundler.require+ method adds all the gems not specified inside a +group+ in the +Gemfile+ and the ones specified in groups for the +Rails.env+ (in this case, _development_), to the load path. This is how an application is able to find them.
-
-The rest of this file is spent defining your application's main class. This is it without the comments:
-
-<ruby>
- module YourApp
- class Application < Rails::Application
- config.encoding = "utf-8"
- config.filter_parameters += [:password]
- end
- end
-</ruby>
-
-h3. Return to Rails
-
-On the surface, this looks like a simple class inheritance. There's more underneath though. back in +Rails::Application+, the +inherited+ method is defined:
-
-<ruby>
- def inherited(base)
- raise "You cannot have more than one Rails::Application" if Rails.application
- super
- Rails.application = base.instance
- end
-</ruby>
-
-We do not already have a +Rails.application+, so instead this resorts to calling +super+. +Rails::Application+ descends from +Rails::Engine+ and so will call the +inherited+ method in +Rails::Engine+ (in _railties/lib/rails/engine.rb_), but before that it's important to note that +called_from+ is defined an +attr_accessor+ on +Rails::Engine+ and that +YourApp::Application+ is not an +abstract_railtie+:
-
-<ruby>
- def inherited(base)
- unless base.abstract_railtie?
- base.called_from = begin
- # Remove the line number from backtraces making sure we don't leave anything behind
- call_stack = caller.map { |p| p.split(':')[0..-2].join(':') }
- File.dirname(call_stack.detect { |p| p !~ %r[railties[\w\-\.]*/lib/rails|rack[\w\-\.]*/lib/rack] })
- end
- end
-
- super
- end
-</ruby>
-
-This +called_from+ setting looks a little overwhelming to begin with, but the short end of it is that it returns your application's root, something like: _/home/you/yourapp_. After +called_from+ has been set, +super+ is again called and this means the +Rails::Railtie#inherited+ method (in _railties/lib/rails/railtie.rb_):
+By inheriting from +Rails::Railtie+ the +Rails::Railtie#inherited+ method is called:
<ruby>
def inherited(base)
unless base.abstract_railtie?
- base.send(:include, self::Configurable)
+ base.send(:include, Railtie::Configurable)
subclasses << base
end
end
</ruby>
-Again, +YourApp::Application+ will return false for +abstract_railtie+ and so the code inside the +unless+ will be ran. The first line:
-
-<ruby>
- base.send(:include, self::Configurable)
-</ruby>
-
-includes the +self::Configurable+ module, with self being +Rails::Application+ in this context:
-
-<ruby>
- module Rails
- class Application
- module Configurable
- def self.included(base)
- base.extend ClassMethods
- end
-
- module ClassMethods
- def inherited(base)
- raise "You cannot inherit from a Rails::Application child"
- end
- end
-
- def config
- @config ||= Application::Configuration.new(self.class.find_root_with_flag("config.ru", Dir.pwd))
- end
- end
- end
- end
-</ruby>
-
-The inclusion of the +Rails::Application::Configurable+ module triggers the +included+ method in here which extends +YourApp::Application+ with the +Rails::Application::Configurable::ClassMethods+.
-
-Now that the chain of +super+ calls is done, we'll go back to the original +inherited+ method in +Rails::Application+ and the final line in this method:
-
-<ruby>
- Rails.application = base.instance
-</ruby>
-
-+base+ in this case is +YourApp::Application+ and calling +instance+ on this will return an instance of +YourApp::Application+ through the +instance+ method defined here:
-
-<ruby>
- def instance
- if self == Rails::Application
- Rails.application
- else
- @@instance ||= new
- end
- end
-</ruby>
-
-+self+ in this case is +YourApp::Application+, so it won't match to +Rails::Application+ so instead the +new+ method is called which calls the +initialize+ method.
-
-
-
-
-h3. Firing it up!
-
-Now that we've covered the boot process of Rails the next line best to cover would be what happens after _script/rails_ has loaded _config/boot.rb_. That's quite simply that it then +require 'rails/commands'+ which is located at _railties/lib/rails/commands.rb_. Remember how +exec+ passed the arguments to +script/rails+? This is where they're used. _rails/commands.rb_ is quite a large file in Rails 3, as it contains all the Rails commands like console, about, generate and, of course, server. Because we've called +rails server+ the first argument in +ARGV+ is of course +"server"+. So assuming this we can determine that the +ARGV.shift+ in _commands.rb_ is going to return +"server"+, therefore it'll match this +when+:
-
-<ruby>
- when 's', 'server'
- require 'rails/commands/server'
- Dir.chdir(ROOT_PATH)
- Rails::Server.start
-</ruby>
-
-The keen-eyed observer will note that this +when+ also specifies the argument could also be simply +'s'+ thereby making the full command +rails s+. This is the same with the other commands with +generate+ becoming +g+, +console+ becoming +c+ and +dbconsole+ becoming +db+.
-
-This code here ensures we are at the +ROOT_PATH+ of our application (this constant was defined in _script/rails_) and then calls +Rails::Server.start+. +Rails::Server+ descends from +Rack::Server+ which is defined in the rack gem. The +Rails::Server.start+ method is defined like this:
-
-<ruby>
- def start
- ENV["RAILS_ENV"] = options[:environment]
-
- puts "=> Booting #{ActiveSupport::Inflector.demodulize(server)}"
- puts "=> Rails #{Rails.version} application starting in #{Rails.env} on http://#{options[:Host]}:#{options[:Port]}"
- puts "=> Call with -d to detach" unless options[:daemonize]
- trap(:INT) { exit }
- puts "=> Ctrl-C to shutdown server" unless options[:daemonize]
-
- super
- ensure
- puts 'Exiting' unless options[:daemonize]
- end
-</ruby>
-
-We can see here that there is usual output indicating that the server is booting up.
-
-How the +options+ variable gets set and how Rack starts the server up is covered in the next section.
-
-h3. Racking it up!
-
-
-This +Rack::Server.start+ method is defined like this:
-
-<ruby>
- def self.start
- new.start
- end
-</ruby>
-
-+new+ as you know calls +initialize+ in a class, and that is defined like this:
-
-<ruby>
- def initialize(options = nil)
- @options = options
- end
-</ruby>
-
-And then +options+, which are the options referenced by the +start+ method in +Rails::Server+.
-
-<ruby>
- def options
- @options ||= parse_options(ARGV)
- end
-</ruby>
-
-And +parse_options+:
-
-<ruby>
- def parse_options(args)
- options = default_options
-
- # Don't evaluate CGI ISINDEX parameters.
- # http://hoohoo.ncsa.uiuc.edu/cgi/cl.html
- args.clear if ENV.include?("REQUEST_METHOD")
-
- options.merge! opt_parser.parse! args
- options
- end
-</ruby>
-
-And +default_options+:
-
-<ruby>
- def default_options
- {
- :environment => "development",
- :pid => nil,
- :Port => 9292,
- :Host => "0.0.0.0",
- :AccessLog => [],
- :config => "config.ru"
- }
- end
-</ruby>
-
-Finally! We've arrived at +default_options+ which leads into our next point quite nicely. After the object has been +initialize+'d, +start+ is called:
-
-<ruby>
- def start
- if options[:debug]
- $DEBUG = true
- require 'pp'
- p options[:server]
- pp wrapped_app
- pp app
- end
-
- if options[:warn]
- $-w = true
- end
-
- if includes = options[:include]
- $LOAD_PATH.unshift *includes
- end
-
- if library = options[:require]
- require library
- end
-
- daemonize_app if options[:daemonize]
- write_pid if options[:pid]
- server.run wrapped_app, options
- end
-</ruby>
-
-We're not debugging anything, so there goes the first 7 lines, we're not warning, nor are we including, requiring, daemonising or writing out a pid file. That's everything except the final line, which calls +run+ with the +wrapped_app+ which is then defined like this:
+This first checks if the Railtie that's inheriting it is a component of Rails itself:
<ruby>
- def wrapped_app
- @wrapped_app ||= build_app app
- end
-</ruby>
+ABSTRACT_RAILTIES = %w(Rails::Railtie Rails::Plugin Rails::Engine Rails::Application)
-and +build_app+'s first and only argument is +app+ which is defined like this:
+...
-
-<ruby>
- def app
- @app ||= begin
- if !::File.exist? options[:config]
- abort "configuration #{options[:config]} not found"
- end
-
- app, options = Rack::Builder.parse_file(self.options[:config], opt_parser)
- self.options.merge! options
- app
- end
- end
-</ruby>
-
-+options+ is a method we talked about a short while ago, which is just the set of default options. +options[:config]+ in this context is therefore _config.ru_ which coincidentally we have in our application! To get an application instance from this method +Rack::Builder+ joins the fray with a call to +parse_file+ on our _config.ru_:
-
-<ruby>
- def self.parse_file(config, opts = Server::Options.new)
- options = {}
- if config =~ /\.ru$/
- cfgfile = ::File.read(config)
- if cfgfile[/^#\\(.*)/] && opts
- options = opts.parse! $1.split(/\s+/)
- end
- cfgfile.sub!(/^__END__\n.*/, '')
- app = eval "Rack::Builder.new {( " + cfgfile + "\n )}.to_app",
- TOPLEVEL_BINDING, config
- else
- require config
- app = Object.const_get(::File.basename(config, '.rb').capitalize)
- end
- return app, options
- end
-</ruby>
-
-First this reads your config file and checks it for +#\+ at the beginning. This is supported if you want to pass options into the +Rack::Server+ instance that you have and can be used like this:
-
-<ruby>
- #\\ -E production
- # This file is used by Rack-based servers to start the application.
-
- require ::File.expand_path('../config/environment', __FILE__)
- run YourApp::Application.instance
-
-</ruby>
-
-TODO: Is the above correct? I am simply guessing!
-
-After that it removes all the content after any +__END__+ in your _config.ru_ (TODO: because? Is this so it doesn't get eval'd?) and then evals the content of this file which, as you've seen is quite simple. The code that's first evaluated would be the require to the _config/environment.rb_ file, which leads into the next section.
-
-h3. _config/environment.rb_
-
-Now that we've seen that _rails/server_ gets to _config/environment.rb_ via Rack's requiring of it and Passenger requires it straight off the line. We've covered the boot process of Rails and covered the beginnings of a Rack server starting up. We have reached a common path for both _rails/server_ and Passenger now, so let's investigate what _config/environment.rb_ does.
-
-<ruby>
- # Load the rails application
- require File.expand_path('../application', __FILE__)
-
- # Initialize the rails application
- YourApp::Application.initialize!
-
-</ruby>
-
-As you can see, there's a require in here for _config/application.rb_, and this file looks like this:
-
-
-<ruby>
- module YourApp
- class Application < Rails::Application
- # Settings in config/environments/* take precedence over those specified here.
- # Application configuration should go into files in config/initializers
- # -- all .rb files in that directory are automatically loaded.
-
- # Add additional load paths for your own custom dirs
- # config.load_paths += %W( #{config.root}/extras )
-
- # Only load the plugins named here, in the order given (default is alphabetical).
- # :all can be used as a placeholder for all plugins not explicitly named
- # config.plugins = [ :exception_notification, :ssl_requirement, :all ]
-
- # Activate observers that should always be running
- # config.active_record.observers = :cacher, :garbage_collector, :forum_observer
-
- # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
- # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
- # config.time_zone = 'Central Time (US & Canada)'
-
- # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
- # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
- # config.i18n.default_locale = :de
-
- # Configure generators values. Many other options are available, be sure to check the documentation.
- # config.generators do |g|
- # g.orm :active_record
- # g.template_engine :erb
- # g.test_framework :test_unit, :fixture => true
- # end
- end
- end
-</ruby>
-
-These options (and their siblings) are explained in a later section. What's important to note for this file currently is that this is where the +YourApp::Application+ class is initialized and that it's a subclass of +Rails::Application+. This is the first point where your application begins to initialize Rails and as you can see all of this is configuration stuff which your initializers and really, the rest of your application will depend on. These options and what they do will be covered later.
-
-
-h3. Rails Initialization Process
-
-Now begins the actual initialization of Rails. Previously we have covered how _rails server_ and Passenger get to this stage and the parts of Rails that they have both loaded.
-
-h3. +Rails::Application+
-
-The first steps for the initialization process of Rails begins when +YourApp::Application+ descends from +Rails::Application+. The +Rails::Application+ class descends from +Rails::Engine+ class which itself descends from +Rails::Railtie+ defined in _railties/lib/rails/railtie.rb_. Along this fantastical chain of superclasses, there's defined a couple of inherited class methods. These methods just so happen to be called when a class inherits from (aka: is made a subclass of) this class. This first one is for +Rails::Application+:
-
-<ruby>
- def inherited(base)
- raise "You cannot have more than one Rails::Application" if Rails.application
- super
- Rails.application = base.instance
- end
-</ruby>
-
-This goes up the chain by using +super+ to calling +Rails::Engine.inherited+:
-
-<ruby>
- def inherited(base)
- unless abstract_railtie?(base)
- base.called_from = begin
- call_stack = caller.map { |p| p.split(':').first }
- File.dirname(call_stack.detect { |p| p !~ %r[railties/lib/rails|rack/lib/rack] })
- end
- end
-
- super
- end
-</ruby>
-
-+called_from+ references where this code was called from. This is covered later on in the "Bootstrap Initializers" section.
-
-Which then calls +Rails::Railtie.inherited+:
-
-<ruby>
- def inherited(base)
- unless abstract_railtie?(base)
- base.send(:include, self::Configurable)
- subclasses << base
- end
- end
-</ruby>
-
-This +inherited+ first includes the +Rails::Configurable+ module on +base+, which is +YourApp::Application+. This module defines the +config+ method on +YourApp::Application+, and now it's starting to come together. You may notice that in your +config/application.rb+ file there's a +config+ method called there. This is the method from +Rails::Configurable+.
-
-Then this adds to +Rails::Railtie.subclasses+ your application's class because... TODO: explain.
-
-With +Rails::Railtie.inherited+ out of the way, and that being the last thing to do in +Rails::Engine.inherited+ we return to +Rails::Application.inherited+ which calls the following:
-
-<ruby>
- Rails.application = base.instance
+def abstract_railtie?
+ ABSTRACT_RAILTIES.include?(name)
+end
</ruby>
-As you already know, +base+ is +YourApp::Application+ and now it's calling the +instance+ method on it. This method is defined in +Rails::Application+ like this:
+Because +I18n::Railtie+ isn't in this list, +abstract_railtie?+ returns +false+. Therefore the +Railtie::Configurable+ module is included into this class and the +subclasses+ method is called and +I18n::Railtie+ is added to this new array.
<ruby>
- def instance
- if self == Rails::Application
- Rails.application
- else
- @@instance ||= new
- end
- end
+def subclasses
+ @subclasses ||= []
+end
</ruby>
-The +new+ method here simply creates a new +Rails::Application+ and sets it to the +@@instance+ class variable. No magic.
-
-h3. Your Application's Configuration
-Now that +inherited+ has finished doing its job, next up in _config/application.rb_ is the call to the +config+ object's methods. As explained before, this +config+ object is an instance of +Rails::Railtie::Configuration+, put into place by the call of +include Rails::Configurable+ back in +Rails::Railtie.inherited+. This defined it as such:
+The +config+ method used at the top of +I18n::Railtie+ is defined on +Rails::Railtie+ and is defined like this:
<ruby>
def config
@@ -2692,231 +765,45 @@ Now that +inherited+ has finished doing its job, next up in _config/application.
end
</ruby>
-All the methods for +Rails::Railtie::Configuration+ are defined like this in _railties/lib/rails/railtie/configuration.rb_:
-
-<ruby>
- require 'rails/configuration'
-
- module Rails
- class Railtie
- class Configuration
- include Rails::Configuration::Shared
- end
- end
- end
-</ruby>
-
-As you can probably guess here, the +Rails::Configuration+ module is defined by _rails/configuration_ (_railties/lib/rails/configuration.rb_).
-
-h3. +Rails::Configuration::Shared+
-
-In a standard application, the +application.rb+ looks like this with all the comments stripped out:
+At this point, that +Railtie::Configuration+ constant is automatically loaded which causes the +rails/railties/configuration+ file to be loaded. The line for this is this particular line in +railties/lib/rails/railtie.rb+:
<ruby>
- require File.expand_path('../boot', __FILE__)
-
- module YourApp
- class Application < Rails::Application
- config.filter_parameters << :password
- end
- end
+ autoload :Configuration, "rails/railtie/configuration"
</ruby>
-The +config+ method being the one defined on +Rails::Application::Configurable+:
+h4. +railties/lib/rails/railtie/configuration.rb+
-<ruby>
- def config
- @config ||= Application::Configuration.new(self.class.find_root_with_flag("config.ru", Dir.pwd))
- end
-</ruby>
+This file begins with a require out to +rails/configuration+ which has already been required earlier in the process and so isn't required again.
-The method +find_with_root_flag+ is defined on +Rails::Engine+ (the superclass of +Rails::Application+) and it will find the directory containing a certain flag. In this case it's the +config.ru+ file:
-
-<ruby>
- def find_root_with_flag(flag, default=nil)
- root_path = self.called_from
-
- while root_path && File.directory?(root_path) && !File.exist?("#{root_path}/#{flag}")
- parent = File.dirname(root_path)
- root_path = parent != root_path && parent
- end
-
- root = File.exist?("#{root_path}/#{flag}") ? root_path : default
- raise "Could not find root path for #{self}" unless root
-
- RUBY_PLATFORM =~ /(:?mswin|mingw)/ ?
- Pathname.new(root).expand_path : Pathname.new(root).realpath
- end
-</ruby>
-
-+called_from+ goes through the +caller+ which is the stacktrace of the current thread, in the case of your application it would go a little like this:
-
-<pre>
- /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.0/lib/rails/application.rb:30:in `inherited'
- /home/you/yourapp/config/application.rb:4:in `<module:TestApp>'
- /home/you/yourapp/config/application.rb:3:in `<top (required)>'
- /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:167:in `require'
- /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:167:in `block in require'
- /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:537:in `new_constants_in'
- /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:167:in `require'
- /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.0/lib/rails/commands.rb:33:in `<top (required)>'
- /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:167:in `require'
- /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:167:in `block in require'
- /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:537:in `new_constants_in'
- /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0/lib/active_support/dependencies.rb:167:in `require'
- /var/www/rboard/script/rails:10:in `<main>'
-</pre>
-
-+called_from+ is defined in the +inherited+ method for +Rails::Engine+ which looks like this:
-
-<ruby>
- base.called_from = begin
- call_stack = caller.map { |p| p.split(':').first }
- File.dirname(call_stack.detect { |p| p !~ %r[railties/lib/rails|rack/lib/rack] })
- end
-</ruby>
-
-The +call_stack+ here is the +caller+ output shown previously, minus everything after the first +:+ on all the lines. The first path that matches this is _/usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.0/lib/rails_. Yours may vary slightly, but should always end in _railties-x.x.x/lib/rails_.
-
-The code in +find_root_with_flag+ will go up this directory structure until it reaches the top, which in this case is +/+.
-
-<ruby>
- while root_path && File.directory?(root_path) && !File.exist?("#{root_path}/#{flag}")
- parent = File.dirname(root_path)
- root_path = parent != root_path && parent
- end
-
- root = File.exist?("#{root_path}/#{flag}") ? root_path : default
- raise "Could not find root path for #{self}" unless root
-</ruby>
-
-TODO: What is all this for?
-
-At the root of the system it looks for +config.ru+. TODO: Why? Obviously it's not going to find it, so it uses the +default+ option we've specified which is +Dir.pwd+ which will default to the root folder of your Rails application. This path is then passed to +Rails::Application::Configuration.new+. +Rails::Application::Configuration+ descends from +Rails::Engine::Configuration+ and the +initialize+ method goes like this:
-
-<ruby>
- def initialize(*)
- super
- @allow_concurrency = false
- @colorize_logging = true
- @filter_parameters = []
- @dependency_loading = true
- @serve_static_assets = true
- @time_zone = "UTC"
- @consider_all_requests_local = true
- end
-</ruby>
-
-The +super+ method here is the +initialize+ method in +Rails::Engine::Configuration+:
-
-<ruby>
- def initialize(root=nil)
- @root = root
- end
-</ruby>
-
-Here, the +@root+ variable is assigned the path of your application and then the remainder of +Rails::Application::Configuration.initialize+ is ran, setting up a few instance variables for basic configuration, including one for +@filter_parameters+.
-
-Now with the +config+ option set up, we can go onwards and call +filter_parameters+ on it. This +filter_parameters+ method is not defined on +Rails::Configuration::Shared+ and actually falls to the +method_missing+ defined there instead:
+This file defines the +Rails::Railtie::Configuration+ class which is responsible for providing a way to easily configure railties and it's the +initialize+ method here which is called by the +config+ method back in the +i18n_railtie.rb+ file. The methods on this object don't exist, and so are rescued by the +method_missing+ defined further down in +configuration.rb+:
<ruby>
def method_missing(name, *args, &blk)
- if name.to_s =~ config_key_regexp
- return $2 == '=' ? options[$1] = args.first : options[$1]
- end
- super
- end
-</ruby>
-
-We're not calling +filter_parameters=+, we're calling +filter_parameters+, therefore it'll be the second part of this ternary argument: +options[$1]+. The options method is defined like this:
-
-<ruby>
- def options
- @@options ||= Hash.new { |h,k| h[k] = ActiveSupport::OrderedOptions.new }
- end
-</ruby>
-
-OrderedOptions exists... TODO: explain.
-
-
-So from this we can determine that our +options+ hash now has a key for +filter_parameters+ which's value is an array consisting of a single symbol: +:password+. How this option manages to get into the +@filter_parameters+ variable defined on the +Rails::Application::Configuration.initialize+ method is explained later.
-
-h3. Application Configured!
-
-Now your application has finished being configured (at least in the sense of _config/application.rb_, there's more to come!) in _config/environment.rb_ the final line calls +YourApp::Application.initalize!+.
-
-h3. Initialization begins
-
-This is one of those magical uses of +method_missing+ which, for the purposes of debugging, is something that you don't expect to come across as often as you do and as a consequence you'll spend a good portion of an hour looking for method definitions that don't exist because +method_missing+ is taking care of it. There's some pretty crafty use of +method_missing+ all over Rails and it's encouraged to take note of its power.
-
-+Rails::Application+ has a +method_missing+ definition which does this:
-
-<ruby>
- def method_missing(*args, &block)
- instance.send(*args, &block)
- end
-</ruby>
-
-With our +instance+ being our already initialized by the +inherited+ method, this will just return the value of the +@@instance+ variable, a +Rails::Application+ object. Calling +initialize!+ on this method does this:
-
-<ruby>
- def initialize!
- run_initializers(self)
- self
+ if name.to_s =~ /=$/
+ @@options[$`.to_sym] = args.first
+ elsif @@options.key?(name)
+ @@options[name]
+ else
+ super
+ end
end
</ruby>
-The initializers it is talking about running here are the initializers for our application. The object passed in to +run_initializers+ is +YourApp::Application+.
-
-
-h3. +run_initializers+
+So therefore when an option is referred to it simply stores the value as the key if it's used in a setter context, or retrieves it if used in a getter context. Nothing fancy going on there.
-This method begins the running of all the defined initializers. In the section "The Boot Process" we covered the loading sequence of Rails before any initialization happens and during this time we saw that the +Rails::Railtie+ class includes the +Initializable+ module. As we've also seen +YourApp::Application+ is a descendant of this class, so it too has these methods.
+h4. Back to +activesupport/lib/active_support/i18n_railtie.rb+
-+run_initializers+ looks like this:
+After the configuration method the +reloader+ method is defined, and then the first of of Railties' initializers is defined: +i18n.callbacks+.
<ruby>
- def run_initializers(*args)
- return if instance_variable_defined?(:@ran)
- initializers.each do |initializer|
- initializer.run(*args)
+ initializer "i18n.callbacks" do
+ ActionDispatch::Reloader.to_prepare do
+ I18n::Railtie.reloader.execute_if_updated
end
- @ran = true
- end
-</ruby>
-
-Here the +initializers+ method is defined in _railties/lib/rails/application.rb_:
-
-<ruby>
- def initializers
- initializers = Bootstrap.initializers_for(self)
- railties.all { |r| initializers += r.initializers }
- initializers += super
- initializers += Finisher.initializers_for(self)
- initializers
end
</ruby>
-h3. +Bootstrap+ initializers
-
-The first line here references a +Bootstrap+ class we haven't seen before. Or have we? The keen-eyed observer would have spotted an +autoload+ for it at the top of +Rails::Application+:
-
-<ruby>
- autoload :Bootstrap, 'rails/application/bootstrap'
-</ruby>
-
-Now that we've referenced that class, it will be required for us. You'll notice inside this class that there's an +include Initializable+, providing the afore-mentioned methods from this module. Inside this class a number of initializers are defined.
-
-* load_environment_config
-* load_all_active_support
-* preload_frameworks
-* initialize_logger
-* initialize_cache
-* initialize_subscriber
-* set_clear_dependencies_hook
-* initialize_dependency_mechanism
-
-These are all defined using the +initializer+ method:
+The +initializer+ method (from the +Rails::Initializable+ module) here doesn't run the block, but rather stores it to be run later on:
<ruby>
def initializer(name, opts = {}, &blk)
@@ -2926,50 +813,25 @@ These are all defined using the +initializer+ method:
end
</ruby>
-The +initializers+ method defined here just references an +@initializers+ variable:
-
-<ruby>
- def initializers
- @initializers ||= []
- end
-</ruby>
+An initializer can be configured to run before or after another initializer, which we'll see a couple of times throughout this initialization process. Anything that inherits from +Rails::Railtie+ may also make use of the +initializer+ method, something which is covered in the "Configuration guide":[http://ryanbigg.com/guides/configuring.html#rails-railtie-initializer].
-As you can see from this method it will set +opts[:after]+ if there are previously defined initializers. So we can determine from this that the order our initializers are defined in is the same order that they run in, but only by default. It is possible to change this by specifying an +:after+ or +:before+ option as we will see later on. Each initializer is its own instance of the +Initializer+ class:
+The +Initializer+ class here is defined within the +Rails::Initializable+ module and its +initialize+ method is defined to just set up a couple of variables:
<ruby>
- class Initializer
- attr_reader :name, :block
-
- def initialize(name, context, options, &block)
- @name, @context, @options, @block = name, context, options, block
- end
-
- def before
- @options[:before]
- end
-
- def after
- @options[:after]
- end
-
- def run(*args)
- @context.instance_exec(*args, &block)
- end
-
- def bind(context)
- return self if @context
- Initializer.new(@name, context, @options, &block)
- end
+ def initialize(name, context, options, &block)
+ @name, @context, @options, @block = name, context, options, block
end
</ruby>
-Now that +Rails::Application::Bootstrap+ has finished loading, we can continue on with our initialization. We saw that it called this:
+Once this +initialize+ method is finished, the object is added to the object the +initializers+ method returns:
<ruby>
- initializers = Bootstrap.initializers_for(self)
+ def initializers
+ @initializers ||= self.class.initializers_for(self)
+ end
</ruby>
-Calling +initializers_for+, defined like this:
+If +@initializers+ isn't set (which it won't be at this point), the +intializers_for+ method will be called for this class.
<ruby>
def initializers_for(binding)
@@ -2977,12 +839,14 @@ Calling +initializers_for+, defined like this:
end
</ruby>
-The +binding+ argument here is +YourApp::Application+ and this will return a new +Initializer+ object for all the initializers in +initializers_chain+ for this particular context. +initializers_chain+ goes like this:
+The +Collection+ class in +railties/lib/rails/initializable.rb+ inherits from +Array+ and includes the +TSort+ module which is used to sort out the order of the initializers based on the order they are placed in.
-<ruby>
+The +initializers_chain+ method referenced in the +initializers_for+ method is defined like this:
+
+<rub>
def initializers_chain
initializers = Collection.new
- ancestors.reverse_each do |klass|
+ ancestors.reverse_each do | klass |
next unless klass.respond_to?(:initializers)
initializers = initializers + klass.initializers
end
@@ -2990,1278 +854,259 @@ The +binding+ argument here is +YourApp::Application+ and this will return a new
end
</ruby>
-The ancestors list is relatively short for +Rails::Application::Bootstrap+, consisting of itself and +Rails::Initializable+. Rails will go through these ancestors in reverse and check them all if they +respond_to?(:initializers)+. +Rails::Initializable+ does not and so it's skipped. +Rails::Application::Bootstrap+ of course does, and this is the list of initializers we covered earlier.
-
-After +initializers_chain+ is finished, then they are +map+'d like this, with the +binding+ of course being +YourApp::Application+ as explained previously.
-
-<ruby>
- def initializers_for(binding)
- Collection.new(initializers_chain.map { |i| i.bind(binding) })
- end
-</ruby>
-
-Wow. All that to cover just the first line in the +initializers+ method for +Rails::Application+.
-
-h3. Railties Initializers
-
-This section covers the loading of the initializers and we will go into depth for each initializer in the next section, as they make more sense explained in their chain.
-
-The second line in +Rails::Application#initializers+:
-
-<ruby>
- def initializers
- railties.all { |r| initializers += r.initializers }
- end
-</ruby>
-
-calls +railties+, which is defined like this:
+This method collects the initializers from the ancestors of this class and adds them to a new +Collection+ object using the <tt>+</tt> method which is defined like this for the <tt>Collection</tt> class:
<ruby>
- def railties
- @railties ||= Railties.new(config)
+ def +(other)
+ Collection.new(to_a + other.to_a)
end
</ruby>
-This sets up a new +Rails::Application::Railties+ object like this:
-
-<ruby>
- def initialize(config)
- @config = config
- end
-</ruby>
+So this <tt>+</tt> method is overriden to return a new collection comprising of the existing collection as an array and then using the <tt>Array#+</tt> method combines these two collections, returning a "super" +Collection+ object. In this case, the only initializer that's going to be in this new +Collection+ object is the +i18n.callbacks+ initializer.
-And calls +all+ on it:
+The next method to be called after this +initializer+ method is the +after_initialize+ method on the +config+ object, which is defined like this:
<ruby>
- def all(&block)
- @all ||= railties + engines + plugins
- @all.each(&block) if block
- @all
+ def after_initialize(&block)
+ ActiveSupport.on_load(:after_initialize, :yield => true, &block)
end
</ruby>
-This +all+ method executes code on all the +Rails::Railtie+ and +Rails::Engine+ subclasses, retreived by the +railties+ and +engines+ methods defined right after +all+:
+The +on_load+ method here is provided by the +active_support/lazy_load_hooks+ file which was required earlier and is defined like this:
<ruby>
- def railties
- @railties ||= ::Rails::Railtie.subclasses.map(&:new)
- end
-
- def engines
- @engines ||= ::Rails::Engine.subclasses.map(&:new)
- end
-</ruby>
-
-By default, the railties are:
-
-* +ActiveSupport::Railtie+
-* +I18n::Railtie+
-* +ActionDispatch::Railtie+
-* +ActionController::Railtie+
-* +ActiveRecord::Railtie+
-* +ActionView::Railtie+
-* +ActionMailer::Railtie+
-* +ActiveResource::Railtie+
-* +Rails::TestUnitRailtie+
-
-And these all descend from +Rails::Railtie+.
-
-The default +engines+ are +[]+.
-
-The +plugins+ method it calls is a little more complex:
-
-<ruby>
- def plugins
- @plugins ||= begin
- plugin_names = (@config.plugins || [:all]).map { |p| p.to_sym }
- Plugin.all(plugin_names, @config.paths.vendor.plugins)
- end
- end
-</ruby>
-
-+@config.paths+ is defined in the +Rails::Application::Configuration+ like this:
-
-<ruby>
- def paths
- @paths ||= begin
- paths = super
- paths.app.controllers << builtin_controller if builtin_controller
- paths.config.database "config/database.yml"
- paths.config.environment "config/environments", :glob => "#{Rails.env}.rb"
- paths.log "log/#{Rails.env}.log"
- paths.tmp "tmp"
- paths.tmp.cache "tmp/cache"
- paths.vendor "vendor", :load_path => true
- paths.vendor.plugins "vendor/plugins"
-
- if File.exists?("#{root}/test/mocks/#{Rails.env}")
- ActiveSupport::Deprecation.warn "\"RAILS_ROOT/test/mocks/#{Rails.env}\" won't be added " <<
- "automatically to load paths anymore in future releases"
- paths.mocks_path "test/mocks", :load_path => true, :glob => Rails.env
- end
-
- paths
- end
- end
-</ruby>
-
-When we call +@config.paths.vendor.plugins+ it will return +"vendor/plugins"+.
-
-
-If you've defined specific plugin requirements for your application in _config/application.rb_ by using this code:
-
-<ruby>
- config.plugins = [:will_paginate, :by_star]
-</ruby>
-
-or specific plugin loading using a similar statement such as this next one:
-
-<ruby>
- config.plugins = [:will_paginate, :by_star, :all]
-</ruby>
-
-
-Then this is where the +@config.plugins+ comes from. If you wish to load only certain plugins for your application, use the first example. If you wish to load certain plugins before the rest then the second example is what you would use.
-
-If +config.plugins+ is not defined then +:all+ is specified in its place. Whatever the +plugin_names+ is specified as, is passed to +Plugin.all+ along with the path to the plugins, +@config.path.vendor.plugins+ (which defaults to _vendor/plugins_):
-
-<ruby>
- def self.all(list, paths)
- plugins = []
- paths.each do |path|
- Dir["#{path}/*"].each do |plugin_path|
- plugin = new(plugin_path)
- next unless list.include?(plugin.name) || list.include?(:all)
- plugins << plugin
- end
- end
-
- plugins.sort_by do |p|
- [list.index(p.name) || list.index(:all), p.name.to_s]
- end
- end
-</ruby>
-
-As we can see here it will go through the paths and for every folder in _vendor/plugins_ and +initialize+ a new +Rails::Plugin+ object for each:
-
-<ruby>
- def initialize(root)
- @name = File.basename(root).to_sym
- config.root = root
- end
-</ruby>
-
-This sets the plugin name to be the same name as the folder so the plugin located at _vendor/plugins/by\_star_'s name is +by_star+. After that, the +config+ object is initialized:
-
-<ruby>
- def config
- @config ||= Engine::Configuration.new
- end
-</ruby>
-
-and the root of the plugin defined as that folder. The reasoning for defining a +root+ is so that the initializer called +load_init_rb+ has some place to look for this file:
-
-<ruby>
- initializer :load_init_rb, :before => :load_application_initializers do |app|
- file = Dir["#{root}/{rails/init,init}.rb"].first
- config = app.config
- eval(File.read(file), binding, file) if file && File.file?(file)
- end
-</ruby>
-
-A little more on that later, however.
-
-If the plugin is not included in the list then it moves on to the next one. For all plugins included in the list (or if +:all+ is specified in the list) they are put into a +plugins+ local variable which is then sorted:
-
-<ruby>
- plugins.sort_by do |p|
- [list.index(p.name) || list.index(:all), p.name.to_s]
- end
-</ruby>
-
-The sort order is the same order as which they appear in the +config.plugins+ setting, or in alphabetical order if there is no setting specified.
-
-Now that we have our railties, engines, and plugins in a line we can finally get back to the +all+ code:
-
-<ruby>
- def initializers
- railties.all { |r| initializers += r.initializers }
- end
-</ruby>
-
-This block will gather add the railties' initializers to it.
-
-h3. Engine Initializers
-
-The third line in this +initializers+ method:
-
-<ruby>
- initializers += super
-</ruby>
-
-The +super+ method it's referring to is of course +Rails::Engine.initializers+, which isn't defined on the class but, as we have seen before, is defined on the +Rails::Railtie+ class it inherits from through the +Rails::Initializable+ module. Therefore we can determine the initializers to be added are now the ones defined in +Rails::Engine+.
-
-h3. Finisher Initializers
-
-The final set of initializers in this chain are those in +Rails::Finisher+. This involves running any after initialize code, building the middleware stack and adding the route for _rails/info/properties_.
-
-h3. Running the Initializers
-
-Now that we have all the initializers we can go back to the +run_initializers+ in +Rails::Initializable+:
-
-<ruby>
- def run_initializers(*args)
- return if instance_variable_defined?(:@ran)
- initializers.each do |initializer|
- initializer.run(*args)
- end
- @ran = true
- end
-</ruby>
-
-Now we finally have all the +initializers+ we can go through them and call +run+:
-
-<ruby>
- def run(*args)
- @context.instance_exec(*args, &block)
- end
-</ruby>
-
-You may remember that the +@context+ in this code is +YourApp::Application+ and calling +instance_exec+ on this class will make a new instance of it and execute the code within the +&block+ passed to it. This code within the block is the code from all the initializers.
-
-h3. Bootstrap Initializers
-
-These initializers are the very first initializers that will be used to get your application going.
-
-h4. +load_environment_config+
-
-<ruby>
- initializer :load_environment_config do
- require_environment!
- end
-</ruby>
-
-This quite simply makes a call to +require_environment!+ which is defined like this in +Rails::Application+:
-
-<ruby>
- def require_environment!
- environment = config.paths.config.environment.to_a.first
- require environment if environment
- end
-</ruby>
-
-We've seen +config.paths+ before when loading the plugins and they're explained in more detail in the Bonus section at the end of this guide. +config.enviroment+ for +paths+ is defined like this:
-
-<ruby>
- paths.config.environment "config/environments", :glob => "#{Rails.env}.rb"
-</ruby>
-
-+Rails.env+ was defined way back in the boot process when +railties/lib/rails.rb+ was required:
-
-<ruby>
-module Rails
- class << self
-
- ...
-
- def env
- @_env ||= ActiveSupport::StringInquirer.new(ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development")
- end
-
- ...
-
- end
-end
-</ruby>
-
-With +ENV["RAILS_ENV"]+ and +ENV["RACK_ENV"]+ not set to anything for our server booting process, this will default to +"development"+.
-
-Therefore the path to this config file line would look like this with a substitution made:
-
-<ruby>
- paths.config.environment "config/environments", :glob => "development.rb"
-</ruby>
-
-This method returns a +Path+ object (which acts as an +Enumerable+).
-
-Back to +require_environment+ now:
-
-<ruby>
- def require_environment!
- environment = config.paths.config.environment.to_a.first
- require environment if environment
- end
-</ruby>
-
-And we've determined that +config.paths.config.environment+ is +Path+ object, and calling +to_a+ on that object calls +paths+ because it's +alias+'d at the bottom of the +Path+ class definition:
-
-<ruby>
- alias to_a paths
-</ruby>
-
-<ruby>
- def paths
- raise "You need to set a path root" unless @root.path
- result = @paths.map do |p|
- path = File.expand_path(p, @root.path)
- @glob ? Dir[File.join(path, @glob)] : path
- end
- result.flatten!
- result.uniq!
- result
- end
-</ruby>
-
-This returns an array of files according to our +path+ and +@glob+ which are +config/environments+ and +development.rb+ respectively, therefore we can determine that:
-
-<ruby>
- Dir[File.join(path, @glob)]
-</ruby>
-
-will return an +Array+ containing one element, +"config/enviroments/development.rb"+. Of course when we call +first+ on this Array we'll get the first element and because that exists, we now +require "config/environments/development.rb"+.
-
-This file contains the following by default:
-
-<ruby>
- YourApp::Application.configure do
- # Settings specified here will take precedence over those in config/environment.rb
-
- # In the development environment your application's code is reloaded on
- # every request. This slows down response time but is perfect for development
- # since you don't have to restart the webserver when you make code changes.
- config.cache_classes = false
-
- # Log error messages when you accidentally call methods on nil.
- config.whiny_nils = true
-
- # Show full error reports and disable caching
- config.consider_all_requests_local = true
- config.action_view.debug_rjs = true
- config.action_controller.perform_caching = false
-
- # Don't care if the mailer can't send
- config.action_mailer.raise_delivery_errors = false
- end
-</ruby>
-
-This +configure+ method is an +alias+ of +class_eval+ on +Rails::Application+:
-
-<ruby>
- alias :configure :class_eval
-</ruby>
-
-therefore, the code inside of the +configure+ is evaluated within the context of +YourApp::Application+.
-
-The +config+ object here is the same one that was set up when _config/application.rb_ was loaded, therefore the methods called in this object will fall to the +method_missing+ defined in +Rails::Configuration::Shared+:
-
-<ruby>
- def method_missing(name, *args, &blk)
- if name.to_s =~ config_key_regexp
- return $2 == '=' ? options[$1] = args.first : options[$1]
- end
- super
- end
-</ruby>
-
-This time we are using methods ending in +\=+, so it will set the key in the +options+ to be the value specified. The first couple of options, +cache_classes+, +whiny_nils+, +consider_all_requests_local+ are just simple keys on the +options+. If you recall how options were setup then you may be able to work out how the remaining +action_view+, +action_controller+ and +action_mailer+ methods work.
-
-Firstly, we'll cover how +config_key_regexp+ is defined:
-
-<ruby>
- def config_key_regexp
- bits = config_keys.map { |n| Regexp.escape(n.to_s) }.join('|')
- /^(#{bits})(?:=)?$/
- end
-</ruby>
-
-And also +config_keys+:
-
-<ruby>
- def config_keys
- (Railtie.railtie_names + Engine.engine_names).map { |n| n.to_s }.uniq
- end
-</ruby>
-
-+config_keys+ in here returns:
-
-<ruby>
- [:active_support, :i18n, :action_dispatch, :action_view, :action_controller, :active_record, :action_mailer, :active_resource, :test_unit]
-</ruby>
-
-With all of those keys coming from +Railtie::railtie_names+. If you've elected to not load some of the frameworks here they won't be available as configuration keys, so you'll need to remove them too.
-
-Now a reminder of how the +options+ key is defined:
-
-<ruby>
- def options
- @@options ||= Hash.new { |h,k| h[k] = ActiveSupport::OrderedOptions.new }
- end
-</ruby>
-
-The values for these framework keys are +ActiveSupport::OrderedOptions+ objects, with the class defined like this:
-
-<ruby>
- module ActiveSupport #:nodoc:
- class OrderedOptions < OrderedHash
- def []=(key, value)
- super(key.to_sym, value)
- end
-
- def [](key)
- super(key.to_sym)
- end
-
- def method_missing(name, *args)
- if name.to_s =~ /(.*)=$/
- self[$1.to_sym] = args.first
- else
- self[name]
- end
- end
- end
- end
-</ruby>
-
-We can determine when we call +config.action_view.debug_rjs+ it's falling back to the +method_missing+ defined on +ActiveSupport::OrderedOptions+, which ends up either setting or retrieving a key. In this case because we're using a setter, it will set the key for this hash. This completes the loading of _config/environments/development.rb_.
-
-h4. +load_all_active_support+
-
-This initializer does exactly what it says:
-
-<ruby>
- initializer :load_all_active_support do
- require "active_support/all" unless config.active_support.bare
- end
-</ruby>
-
-If you don't want this to happen you can specify the +config.active_support.bare+ option to +true+ in either _config/application.rb_ or any of your environment files.
-
-h4. +preload_frameworks+
-
-Remember earlier how we had all that stuff +eager_autoload+'d for Active Support?
-
-<ruby>
- initializer :preload_frameworks do
- require 'active_support/dependencies'
- ActiveSupport::Autoload.eager_autoload! if config.preload_frameworks
- end
-</ruby>
-
-This is where it gets loaded. The +eager_autoload!+ method is defined like this:
-
-<ruby>
- def self.eager_autoload!
- @@autoloads.values.each { |file| require file }
- end
-</ruby>
-
-With +@@autoloads+ being
-
-
-* load_all_active_support
-* preload_frameworks
-* initialize_logger
-* initialize_cache
-* initialize_subscriber
-* set_clear_dependencies_hook
-* initialize_dependency_mechanism
-
-h4. Active Support Initializers
-
-Active Support
-
-**Active Support Initializers**
-
-* active_support.initialize_whiny_nils
-* active_support.initialize_time_zone
-
-**I18n Initializers**
-
-* i18n.initialize
-
-The +I18n::Railtie+ also defines an +after_initialize+ which we will return to later when discussing the initializers in detail.
-
-**Action Dispatch Initializers**
-
-* action_dispatch.prepare_dispatcher
-
-**Action Controller Initializers**
-
-* action_controller.logger
-* action_controller.set_configs
-* action_controller.initialize_framework_caches
-* action_controller.set_helpers_path
-
-**Active Record Initializers**
-
-* active_record.initialize_time_zone
-* active_record.logger
-* active_record.set_configs
-* active_record.log_runtime
-* active_record.initialize_database_middleware
-* active_record.load_observers
-* active_record.set_dispatch_hooks
-
-**Action View Initializers **
-
-* action_view.cache_asset_ids
-
-**Action Mailer Initializers **
-
-* action_mailer.logger
-* action_mailer.set_configs
-* action_mailer.url_for
-
-**Active Resource Initializers**
-
-* active_resource.set_configs
-
-**Rails::Engine Initializers**
-
-* set_load_path
-* set_autoload_paths
-* add_routing_paths
-
-
-h4. +Rails::Engine.new+
-
-The +new+ method doesn't exist, but in Ruby classes calling +new+ on the class instantiates a new instance of that class and calls the instance method +initialize+ on it. This method for +Rails::Application+ goes like this:
-
-<ruby>
- def initialize
- require_environment
- Rails.application ||= self
- @route_configuration_files = []
- end
-</ruby>
-
-h4. +Rails::Application#require_environment+
-
-This is not a crafty method like the previous ones, it just does as it says on the box:
-
-<ruby>
- def require_environment
- require config.environment_path
- rescue LoadError
- end
-</ruby>
-
-The +config+ object here is actually another +delegate+'d method (along with +routes+), this time to +self.class+:
-
-<ruby>
- delegate :config, :routes, :to => :'self.class'
-</ruby>
-
-So the method call is actually +self.class.config+.
-
-
-h4. +Rails::Application.config+
-
-Defined back inside the +class << self+ for +Rails::Application+, +config+ makes a new +Rails::Application::Configuration+ object and caches it in a variable called +@config+:
-
-<ruby>
- def config
- @config ||= Configuration.new(Plugin::Configuration.default)
- end
-</ruby>
-
-h4. +Rails::Plugin::Configuration.default+
-
-The +Rails::Plugin::Configuration+ class may be a bit difficult to find at first, but if you look for _plugin.rb_ in Rails, you'll find it in _railties/lib/rails/plugin.rb_. In this file, we see the following:
-
-<ruby>
- module Rails
- class Plugin < Engine
- ...
- end
- end
-</ruby>
-
-So we note here that +Rails::Plugin+ descends from +Rails::Railtie+ and secondly we note that the class +Configuration+ is not actually included in the +Plugin+ class, but it **is** in the +Railtie+ class!
-
-h4. +Rails::Railtie::Configuration+
-
-We've now tracked down the +Plugin::Configuration.default+ method to being +Railtie::Configuration.default+, which is defined like this in _railties/lib/rails/configuration.rb_:
-
-<ruby>
- class Railtie::Configuration
- def self.default
- @default ||= new
- end
- ...
- end
-</ruby>
-
-In this case we have effectively seen that it's doing Configuration.new(Configuration.new). I'll explain why.
-
-h4. +Rails::Application::Configuration.new+
-
-TODO: CLEAN THIS UP! This subclassing is only temporary and will probably not be separate in Rails 3. This is based solely off what the comment at the top of the Railtie::Configuration class says!
-
-The first thing to note here is that this class is subclassed from +Railtie::Configuration+ and therefore the method here is actually +Railtie::Configuration.new+. As mentioned previously, calling +new+ will make a new object of this class and then call +initialize+ on it, which is defined like this:
-
-<ruby>
- def initialize(base = nil)
- if base
- @options = base.options.dup
- @middleware = base.middleware.dup
+ def self.on_load(name, options = {}, &block)
+ if base = @loaded[name]
+ execute_hook(base, options, block)
else
- @options = Hash.new { |h,k| h[k] = ActiveSupport::OrderedOptions.new }
- @middleware = self.class.default_middleware_stack
- end
- end
-</ruby>
-
-This method is not called with a +base+ argument for +Plugin::Configuration.default+ but it is for the +Configuration.new+ wrapped around it. We'll go for the internal one first, since that's the order Rails loads them in.
-
-h4. +default_middleware_stack+
-
-This method is defined like this:
-
-<ruby>
- def self.default_middleware_stack
- ActionDispatch::MiddlewareStack.new.tap do |middleware|
- middleware.use('ActionDispatch::Static', lambda { Rails.public_path }, :if => lambda { Rails.application.config.serve_static_assets })
- middleware.use('::Rack::Lock', :if => lambda { !ActionController::Base.allow_concurrency })
- middleware.use('::Rack::Runtime')
- middleware.use('ActionDispatch::ShowExceptions', lambda { ActionController::Base.consider_all_requests_local })
- middleware.use('ActionDispatch::Notifications')
- middleware.use('ActionDispatch::Callbacks', lambda { !Rails.application.config.cache_classes })
- middleware.use('ActionDispatch::Cookies')
- middleware.use(lambda { ActionController::Base.session_store }, lambda { ActionController::Base.session_options })
- middleware.use('ActionDispatch::Flash', :if => lambda { ActionController::Base.session_store })
- middleware.use('ActionDispatch::ParamsParser')
- middleware.use('::Rack::MethodOverride')
- middleware.use('::ActionDispatch::Head')
- end
- end
-</ruby>
-
-To really understand this method we need to dig a little deeper, down into where +ActionDispatch::MiddlewareStack.new+ is defined and what in particular it does for us.
-
-h4. +ActionDispatch::MiddlewareStack.new+
-
-+ActionDispatch+ is our first foray outside of the +railties+ gem, as this is actually defined in the +actionpack+ part of Rails. The class definition is as important as the method:
-
-<ruby>
- module ActionDispatch
- class MiddlewareStack < Array
-
- ...
-
- def initialize(*args, &block)
- super(*args)
- block.call(self) if block_given?
- end
+ @load_hooks[name] << [block, options]
end
end
</ruby>
-When it's calling +super+ here it's actually calling +initialize+ on the Array class and from this we can determine that an +ActionDispatch::MiddlewareStack+ object is just an +Array+ object with special powers. One of those special powers is the ability to take a block, and +call+ it with +self+, meaning the block's parameter is the object itself!
-
-h4. +ActionDispatch::MiddlewareStack.use+
-
-Previously we saw a chunk of code that I'll re-show you stripped down:
+The +@loaded+ variable here is a hash containing elements representing the different components of Rails that have been loaded at this stage. Currently, this hash is empty. So the +else+ is executed here, using the +@load_hooks+ variable defined in +active_support/lazy_load_hooks+:
<ruby>
- def self.default_middleware_stack
- ActionDispatch::MiddlewareStack.new.tap do |middleware|
- middleware.use('ActionDispatch::Static', lambda { Rails.public_path }, :if => lambda { Rails.application.config.serve_static_assets })
- ...
- end
- end
+ @load_hooks = Hash.new {|h,k| h[k] = [] }
</ruby>
-As explained in the previous section, we know that the +new+ on +ActionDispatch::MiddlewareStack+ takes a block and that block has one parameter which is the object itself. On this object we call the +use+ method to include middleware into our application. The use method simply does this:
+This defines a new hash which has keys that default to empty arrays. This saves Rails from having to do something like this instead:
<ruby>
- def use(*args, &block)
- middleware = Middleware.new(*args, &block)
- push(middleware)
- end
+ @load_hooks[name] = []
+ @load_hooks[name] << [block, options]
</ruby>
-We'll come back to this method later on.
+The value added to this array here consists of the block and options passed to +after_initialize+.
-h4. +ActionController::Middleware.new+
+We'll see these +@load_hooks+ used later on in the initialization process.
-This +initialize+ method also is in a class who's ancestry is important so once again I'll show the ancestry and we'll go up that particular chain:
+This rest of +i18n_railtie.rb+ defines the protected class methods +include_fallback_modules+, +init_fallbacks+ and +validate_fallbacks+.
-<ruby>
- module ActionController
- class Middleware < Metal
+h4. Back to +activesupport/lib/active_support/railtie.rb+
- ...
+This file defines the +ActiveSupport::Railtie+ constant which like the +I18n::Railtie+ constant just defined, inherits from +Rails::Railtie+ meaning the +inherited+ method would be called again here, including +Rails::Configurable+ into this class. This class makes use of +Rails::Railtie+'s +config+ method again, setting up the configuration options for Active Support.
- def initialize(app)
- super()
- @_app = app
- end
- end
- end
-</ruby>
+Then this Railtie sets up three more initializers:
-Here our method calls +super+ but with a difference: it's passing in no arguments intentionally by putting the two brackets at the end. The method called here is therefore +ActionController::Metal.initialize+.
+* +active_support.initialize_whiny_nils+
+* +active_support.deprecation_behavior+
+* +active_support.initialize_time_zone+
-h4. +ActionController::Metal.initialize+
+We will cover what each of these initializers do when they run.
-This is another subclassed class, this time from +ActionController::AbstractController+ and I'm sure you can guess what that means:
+Once the +active_support/railtie+ file has finished loading the next file required from +railties/lib/rails.rb+ is the +action_dispatch/railtie+.
-<ruby>
- class Metal < AbstractController::Base
+h4. +activesupport/lib/action_dispatch/railtie.rb+
- ...
+This file defines the +ActionDispatch::Railtie+ class, but not before requiring +action_dispatch+.
- def initialize(*)
- @_headers = {}
- super
- end
- end
-</ruby>
+h4. +activesupport/lib/action_dispatch.rb+
-The single +*+ in the argument listing means we can accept any number of arguments, we just don't care what they are.
-
-h4. +AbstractController::Base.initialize+
-
-This may be anti-climatic, but the initialize method here just returns an +AbstractController::Base+ object:
+This file attempts to locate the +active_support+ and +active_model+ libraries by looking a couple of directories back from the current file and then adds the +active_support+ and +active_model+ +lib+ directories to the load path, but only if they aren't already, which they are.
<ruby>
- # Initialize controller with nil formats.
- def initialize #:nodoc:
- @_formats = nil
- end
-</ruby>
-
-h4. +ActionDispatch::MiddlewareStack.use+
-
-Now we're back to this method, from our foray into the depths of how +Middleware.new+ works, we've showed that it is an instance of +AbstractController::Base+. Therefore it does
-
-TODO: ELABORATE ON THIS SECTION, including explaining what all the pieces of middleware do. Then explain how the default_middleware_stack does what it does, whatever that is.
-
-h4. Back to +Rails::Application::Configuration.new+
-
-Now that the first call to this method is complete (+Plugin::Configuration.default+), we can move onto the second call. Here's a refresher of what this method does:
+ activesupport_path = File.expand_path('../../../activesupport/lib', __FILE__)
+ $:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.include?(activesupport_path)
-<ruby>
- def initialize(base = nil)
- if base
- @options = base.options.dup
- @middleware = base.middleware.dup
- else
- @options = Hash.new { |h,k| h[k] = ActiveSupport::OrderedOptions.new }
- @middleware = self.class.default_middleware_stack
- end
- end
+ activemodel_path = File.expand_path('../../../activemodel/lib', __FILE__)
+ $:.unshift(activemodel_path) if File.directory?(activemodel_path) && !$:.include?(activemodel_path)
</ruby>
-You'll note now that this method is being called now is +Configuration.new(Plugin::Configuration.default)+ and with the argument, it's going to perform differently than before, this time duplicating the +options+ and +middleware+ of the object it was passed.
+In effect, these lines only define the +activesupport_path+ and +activemodel_path+ variables and nothing more.
-TODO: Find out what purpose the +@options+ and +@middleware+ variables serve.
-
-Finally, a +Rails::Application::Configuration+ object will be returned. On this class there are a couple of +attr_accessor+s and +attr_writer+s defined:
+The next two requires in this file are already done, so they are not run:
<ruby>
- attr_accessor :after_initialize_blocks, :cache_classes, :colorize_logging,
- :consider_all_requests_local, :dependency_loading,
- :load_once_paths, :logger, :plugins,
- :preload_frameworks, :reload_plugins, :serve_static_assets,
- :time_zone, :whiny_nils
-
- attr_writer :cache_store, :controller_paths,
- :database_configuration_file, :eager_load_paths,
- :i18n, :load_paths, :log_level, :log_path, :paths,
- :routes_configuration_file, :view_path
+ require 'active_support'
+ require 'active_support/dependencies/autoload'
</ruby>
-Along with these are a lot of helper methods, and one of them is +environment_path+:
+The following require is to +action_pack+ (+activesupport/lib/action_pack.rb+) which has a 22-line copyright notice at the top of it and ends in a simple require to +action_pack/version+. This file, like other +version.rb+ files before it, defines the +ActionPack::VERSION+ constant:
<ruby>
- def environment_path
- "#{root}/config/environments/#{Rails.env}.rb"
- end
-</ruby>
-
-h4. Back to +Rails::Application#require_environment+
-
-Now that we have a +Rails::Application::Configuration+ object for the +config+ method, we call the +environment_path+ which, as we've seen above, just requires the current environment file which in this case is _config/environments/development.rb_. If this file cannot be found, the +LoadError+ +require+ throws will be +rescue+'d and Rails will continue on its merry way.
-
-h4. _config/environments/development.rb_
-
-In a standard Rails application we have this in our _config/environments/development.rb_ file:
-
-<ruby>
- YourApp::Application.configure do
- # Settings specified here will take precedence over those in config/environment.rb
-
- # In the development environment your application's code is reloaded on
- # every request. This slows down response time but is perfect for development
- # since you don't have to restart the webserver when you make code changes.
- config.cache_classes = false
-
- # Log error messages when you accidentally call methods on nil.
- config.whiny_nils = true
-
- # Show full error reports and disable caching
- config.action_controller.consider_all_requests_local = true
- config.action_view.debug_rjs = true
- config.action_controller.perform_caching = false
+ module ActionPack
+ module VERSION #:nodoc:
+ MAJOR = 3
+ MINOR = 1
+ TINY = 0
+ PRE = "beta"
- # Don't care if the mailer can't send
- config.action_mailer.raise_delivery_errors = false
+ STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
+ end
end
</ruby>
-It's a little bit sneaky here, but +configure+ is +alias+'d to +class_eval+ on subclasses of +Rails::Application+ which of course includes +YourApp::Application+. This means that the code inside the +configure do+ block will be evaled within the context of +YourApp::Application+. The +config+ method here is the one mentioned before: the +Rails::Application::Configuration+ object. The methods on it should look familiar too: they're the ones that had +attr_accessor+ and +attr_writer+ definitions.
-
-The ones down the bottom, +config.action_controller+, +config.action_view+ and +config.action_mailer+ aren't defined by +attr_accessor+ or +attr_writer+, rather they're undefined methods and therefore will trigger the +method_missing+ on the +Rails::Application::Configuration+ option.
-
-h5. config.cache_classes=
-
-The first method call in this file, this tells Rails to not cache the classes for every request. This means for every single request Rails will reload the classes of your application. If you have a lot of classes, this will slow down the request cycle of your application. This is set to +false+ in the _development_ environment, and +true+ in the _test_ & _production_ environments.
+Once +action_pack+ is finished, then +active_model+ is required.
-h5. config.whiny_nils=
+h4. +activemodel/lib/active_model.rb+
-If this is set to +true+, like it is here in the _development_ environment, _activesupport/whiny_nil_ will be +require+'d. Have you ever seen this error:
+This file makes a require to +active_model/version+ which defines the version for Active Model:
<ruby>
- Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
-</ruby>
-
-Or perhaps this one?
-
-<ruby>
- You have a nil object when you didn't expect it!
- You might have expected an instance of Array.
- The error occurred while evaluating nil.flatten!
-</ruby>
-
-If you have, then this is _activesupport/whiny_nil_ at work.
-
-
-h5. The frameworks
-
-As mentioned before, the methods +action_controller+, +action_view+ and +action_mailer+ aren't defined on the +Rails::Application::Configuration+ object, rather they are caught by +method_missing+ which does this:
+ module ActiveModel
+ module VERSION #:nodoc:
+ MAJOR = 3
+ MINOR = 1
+ TINY = 0
+ PRE = "beta"
-<ruby>
- def method_missing(name, *args, &blk)
- if name.to_s =~ config_key_regexp
- return $2 == '=' ? @options[$1] = args.first : @options[$1]
+ STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
end
-
- super
end
</ruby>
-Whilst this code is not obvious at first, a little bit of further explanation will help you understand. +config_key_regexp+ is another method (a private one, like +method_missing+) defined here:
+Once the +version.rb+ file is loaded, the +ActiveModel+ module has its autoloaded constants defined as well as a sub-module called +ActiveModel::Serializers+ which has autoloads of its own. When the +ActiveModel+ module is closed the +active_support/i18n+ file is required.
-<ruby>
- def config_key_regexp
- bits = config_keys.map { |n| Regexp.escape(n.to_s) }.join('|')
- /^(#{bits})(?:=)?$/
- end
-</ruby>
+h4. +activesupport/lib/active_support/i18n.rb+
-As is +config_keys+:
+This is where the +i18n+ gem is required and first configured:
<ruby>
- def config_keys
- ([ :active_support, :action_view ] +
- Railtie.plugin_names).map { |n| n.to_s }.uniq
+ begin
+ require 'i18n'
+ require 'active_support/lazy_load_hooks'
+ rescue LoadError => e
+ $stderr.puts "You don't have i18n installed in your application. Please add it to your Gemfile and run bundle install"
+ raise e
end
-</ruby>
-
-Aha! There we've got mention of +action_view+, but what is in +Railtie.plugin_names+? Most likely in this case the other frameworks.
-
-h5. +Railtie.plugin_names+
-
-I'm going to show you two methods since the third one, +self.plugin_name+, calls the second one, +self.plugins+ and they're right after each other:
-
-<ruby>
- module Rails
- class Railtie
- def self.inherited(klass)
- @plugins ||= []
- @plugins << klass unless klass == Plugin
- end
- def self.plugins
- @plugins
- end
-
- def self.plugin_names
- plugins.map { |p| p.plugin_name }
- end
- end
- end
+ I18n.load_path << "#{File.dirname(__FILE__)}/locale/en.yml"
</ruby>
-In here we see that we get the +plugin_names+ from a variable called +@plugins+... which we haven't seen yet. Through the power of the wonderful +inherited+ the +@plugins+ variable is populated. +inherited+ is called when a class inherits, or subclasses, from this class. Therefore we can determine that the other classes are probably inheriting or subclassing from +Rails::Railtie+.
-
-h3. Serving a Request
-
-Now that your application is fully initialized, it's now ready to start serving requests.
-
-h4. _rails server_
-
-For servers running through _rails server_ you may recall that this uses +Rails::Server+ which is a subclass of +Rack::Server+. Previously we covered the initialization process of Rack but not completely up to the point where the server was running. Now that's what we'll do. Back when the +Rack::Server+ class was first covered there was a mention of the +start+ method which we only touched on. It goes a little like this:
-
-<ruby>
- def start
- if options[:debug]
- $DEBUG = true
- require 'pp'
- p options[:server]
- pp wrapped_app
- pp app
- end
+In effect, the +I18n+ module first defined by +i18n_railtie+ is extended by the +i18n+ gem, rather than the other way around. This has no ill effect. They both work on the same way.
- if options[:warn]
- $-w = true
- end
+This is another spot where +active_support/lazy_load_hooks+ is required, but it has already been required so it's not loaded again.
- if includes = options[:include]
- $LOAD_PATH.unshift *includes
- end
+If +i18n+ cannot be loaded, the user is presented with an error which says that it cannot be loaded and recommends that it's added to the +Gemfile+. However, in a normal Rails application this gem would be loaded.
- if library = options[:require]
- require library
- end
+Once it has finished loading, the +I18n.load_path+ method is used to add the +activesupport/lib/active_support/locale/en.yml+ file to I18n's load path. When the translations are loaded in the initialization process, this is one of the files where they will be sourced from.
- daemonize_app if options[:daemonize]
- write_pid if options[:pid]
- server.run wrapped_app, options
- end
-</ruby>
+The loading of this file finishes the loading of +active_model+ and so we go back to +action_dispatch+.
-We were at the point of explaining what +wrapped_app+ was before we dived into the Rails initialization process.Now that we have a +wrapped_app+ we pass it as the first argument to +server.run+. +server+ in this instance is defined like this:
+h4. Back to +activesupport/lib/action_dispatch.rb+
-<ruby>
- def server
- @_server ||= Rack::Handler.get(options[:server]) || Rack::Handler.default
- end
-</ruby>
-
-Our +options+ Hash is still the default, and there is no +server+ key set in +default_options+, so it will default to +Rack::Handler.default+. This code works like this:
+The remainder of this file requires the +rack+ file from the Rack gem which defines the +Rack+ module. After +rack+, there's autoloads defined for the +Rack+, +ActionDispatch+, +ActionDispatch::Http+, +ActionDispatch::Session+. A new method called +autoload_under+ is used here, and this simply prefixes the files where the modules are autoloaded from with the path specified. For example here:
<ruby>
- def self.default(options = {})
- # Guess.
- if ENV.include?("PHP_FCGI_CHILDREN")
- # We already speak FastCGI
- options.delete :File
- options.delete :Port
-
- Rack::Handler::FastCGI
- elsif ENV.include?("REQUEST_METHOD")
- Rack::Handler::CGI
- else
- begin
- Rack::Handler::Mongrel
- rescue LoadError => e
- Rack::Handler::WEBrick
- end
- end
- end
+ autoload_under 'testing' do
+ autoload :Assertions
+ ...
</ruby>
+The +Assertions+ module is in the +action_dispatch/testing+ folder rather than simply +action_dispatch+.
-We don't have +PHP_FCGI_CHILDREN+ in our +ENV+, so it's not going to be +FastCGI+. We also don't have +REQUEST_METHOD+ in there, so it's not going to be +CGI+. If we have Mongrel installed it'll default to that and then finally it'll use WEBrick. For this, we'll assume a bare-bones installation and assume WEBrick. So from this we can determine our default handler is +Rack::Handler::WEBrick+.
+Finally, this file defines a top-level autoload, the +Mime+ constant.
-(side-note: Mongrel doesn't install on 1.9. TODO: How do we format these anyway?)
+h4. Back to +activesupport/lib/action_dispatch/railtie.rb+
-h5. +Rack::Handler::WEBrick+
+After +action_dispatch+ is required in this file, the +ActionDispatch::Railtie+ class is defined and is yet another class that inherits from +Rails::Railtie+. This class defines some initial configuration option defaults for +config.action_dispatch+ before setting up a single initializer called +action_dispatch.configure+.
-This class is subclassed from +WEBrick::HTTPServlet::AbstractServlet+ which is a class that comes with the Ruby standard library. This is the magical class that serves the requests and deals with the comings (requests) and goings (responses) for your server.
+With +action_dispatch/railtie+ now complete, we go back to +railties/lib/rails.rb+.
+h4. Back to +railties/lib/rails.rb+
-+Rack::Server+ has handlers for the request and by default the handler for a _rails server_ server is
+With the Active Support and Action Dispatch railties now both loaded, the rest of this file deals with setting up UTF-8 to be the default encoding for Rails and then finally setting up the +Rails+ module. This module defines useful methods such as +Rails.logger+, +Rails.application+, +Rails.env+, and +Rails.root+.
-h3. Cruft!
+h4. Back to +railties/lib/rails/all.rb+
-The final line of _config/environment.rb_:
+Now that +rails.rb+ is required, the remaining railties are loaded next, beginning with +active_record/railtie+.
-<ruby>
- YourApp::Application.initialize!
-</ruby>
+h4. +activerecord/lib/active_record/railtie.rb+
-gets down to actually initializing the application!
+Before this file gets into the swing of defining the +ActiveRecord::Railtie+ class, there are a couple of files that are required first. The first one of these is +active_record+.
-TODO: Cover the other +config.*+ methods in perhaps a "Bonus" section near the end. If they aren't referenced in a config file they aren't that important, right?
+h4. +activerecord/lib/active_record.rb+
+This file begins by detecting if the +lib+ directories of +active_support+ and +active_model+ are not in the load path and if they aren't then adds them. As we saw back in +action_dispatch.rb+, these directories are already there.
-TODO: This belongs in the guide, I just don't know where yet. Maybe towards the end, since this is really the "final" thing to be done before being able to serve requests.
+The first three requires have already been done by other files and so aren't loaded here, but the 4th require, the one to +arel+ will require the file provided by the Arel gem, which defines the +Arel+ module.
<ruby>
- def build_app(app)
- middleware[options[:environment]].reverse_each do |middleware|
- middleware = middleware.call(self) if middleware.respond_to?(:call)
- next unless middleware
- klass = middleware.shift
- app = klass.new(app, *middleware)
- end
- app
- end
-</ruby>
-
-Because we don't have any middleware for our application, this returns the application itself( Guessing here!! TODO: Investigate if this is really the case.)
-
-Now that we have an app instance, the last line in +start+ calls +server.run wrapped_app, options+. We know what our app is, and that our options are just the default options, so what is +server+? +server+ is this:
-
-<ruby>
- def server
- @_server ||= Rack::Handler.get(options[:server]) || Rack::Handler.default
- end
+ require 'active_support'
+ require 'active_support/i18n'
+ require 'active_model'
+ require 'arel'
</ruby>
-Since we have default options, the server is obviously going to be +Rack::Handler.default+. The +default+ method goes like this:
+The 5th require in this file is one to +active_record/version+ which defines the +ActiveRecord::VERSION+ constant:
<ruby>
- def self.default(options = {})
- # Guess.
- if ENV.include?("PHP_FCGI_CHILDREN")
- # We already speak FastCGI
- options.delete :File
- options.delete :Port
-
- Rack::Handler::FastCGI
- elsif ENV.include?("REQUEST_METHOD")
- Rack::Handler::CGI
- else
- begin
- Rack::Handler::Mongrel
- rescue LoadError => e
- Rack::Handler::WEBrick
- end
- end
- end
-</ruby>
-
-h3. +Rails::Paths+
-
-
-The +super+ method it references comes from +Rails::Engine::Configuration+ which defines these paths:
+ module ActiveRecord
+ module VERSION #:nodoc:
+ MAJOR = 3
+ MINOR = 1
+ TINY = 0
+ PRE = "beta"
-<ruby>
- def paths
- @paths ||= begin
- paths = Rails::Paths::Root.new(@root)
- paths.app "app", :eager_load => true, :glob => "*"
- paths.app.controllers "app/controllers", :eager_load => true
- paths.app.helpers "app/helpers", :eager_load => true
- paths.app.models "app/models", :eager_load => true
- paths.app.views "app/views"
- paths.lib "lib", :load_path => true
- paths.lib.tasks "lib/tasks", :glob => "**/*.rake"
- paths.lib.templates "lib/templates"
- paths.config "config"
- paths.config.initializers "config/initializers", :glob => "**/*.rb"
- paths.config.locales "config/locales", :glob => "*.{rb,yml}"
- paths.config.routes "config/routes.rb"
- paths
+ STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.')
end
end
</ruby>
-h3. Appendix A
-
-This file is _activesupport/lib/active_support/inflector/inflections.rb_ and defines the +ActiveSupport::Inflector::Inflections+ class which defines the +singularize+, +pluralize+, +humanize+, +tableize+, +titleize+ and +classify+ methods as well as the code to defining how to work out the irregular, singular, plural and human versions of words. These methods are called +irregular+, +singular+, +plural+ and +human+ respectively, as is the Rails way.
-
-This file is _activesupport/lib/active_support/inflector/transliterate.rb_ and defines two methods, +transliterate+ and +parameterize+.
+Once these requires are finished, the base for the +ActiveRecord+ module is defined along with its autoloads.
-This file first requires _activesupport/lib/active_support/core_ext/string/multibyte.rb_, which requires _activesupport/lib/active_support/multibyte.rb_, which subsequently requires _activesupport/core_ext/module/attribute_accessors.rb_. The _attribute_accessors.rb_ file is needed to gain access to the +mattr_accessor+ (module attribute accessor) method, which is called in _active_suport/multibyte.rb_. The file _active_support/multibyte.rb_ also autoloads three other classes:
+Near the end of the file, we see this line:
<ruby>
-module ActiveSupport #:nodoc:
- module Multibyte
- autoload :EncodingError, 'active_support/multibyte/exceptions'
- autoload :Chars, 'active_support/multibyte/chars'
- autoload :Unicode, 'active_support/multibyte/unicode'
- ...
+ ActiveSupport.on_load(:active_record) do
+ Arel::Table.engine = self
end
-end
</ruby>
-There are also these method definitions:
+This will set the engine for +Arel::Table+ to be +ActiveRecord::Base+.
-<ruby>
- # The proxy class returned when calling mb_chars. You can use this accessor to configure your own proxy
- # class so you can support other encodings. See the ActiveSupport::Multibyte::Chars implementation for
- # an example how to do this.
- #
- # Example:
- # ActiveSupport::Multibyte.proxy_class = CharsForUTF32
- def self.proxy_class=(klass)
- @proxy_class = klass
- end
-
- # Returns the currect proxy class
- def self.proxy_class
- @proxy_class ||= ActiveSupport::Multibyte::Chars
- end
-</ruby>
-
-These methods are used in _activesupport/lib/active_support/core_ext/string/multibyte.rb_.
-
-The file _activesupport/lib/active_support/core_ext/string/chars.rb_ defines the default proxy class that will be returned by +mb_chars+.
-
-Because Ruby 1.9's +String+ class has support for multibyte encodings, some methods are defined only for Ruby 1.8:
-
-* +self.wants?+
-* +++
-* +=~+
-* +=~+
-* +center+
-* +include?+
-* +index+
-* +insert+
-* +ljust+
-* +lstrip+, +lstrip!+
-* +ord+
-* +rindex+
-* +rjust+
-* +rstrip+, +rstrip!+
-* +size+
-* +strip+, +strip!+
-
-However, Ruby 1.9 lacks support for some needed operations, so the following methods are defined for both Ruby 1.8 and Ruby 1.9:
-
-* +<=>+
-* +[]=+
-* +capitalize+, +capitalize!+
-* +compose+
-* +decompose+
-* +downcase+, +downcase!+
-* +g_length+
-* +limit+
-* +normalize+
-* +reverse+, +reverse+!
-* +slice+, +slice!+
-* +split+
-* +tidy_bytes+, +tidy_bytes!+
-* +titleize+
-* +upcase+, +upcase!+
+The file then finishes with this line:
<ruby>
- class String
- if RUBY_VERSION >= "1.9"
- def mb_chars
- if ActiveSupport::Multibyte.proxy_class.consumes?(self)
- ActiveSupport::Multibyte.proxy_class.new(self)
- else
- self
- end
- end
-
- def is_utf8? #:nodoc
- case encoding
- when Encoding::UTF_8
- valid_encoding?
- when Encoding::ASCII_8BIT, Encoding::US_ASCII
- dup.force_encoding(Encoding::UTF_8).valid_encoding?
- else
- false
- end
- end
- else
- def mb_chars
- if ActiveSupport::Multibyte.proxy_class.wants?(self)
- ActiveSupport::Multibyte.proxy_class.new(self)
- else
- self
- end
- end
-
- # Returns true if the string has UTF-8 semantics (a String used for purely byte resources is unlikely to have
- # them), returns false otherwise.
- def is_utf8?
- ActiveSupport::Multibyte::Chars.consumes?(self)
- end
- end
+ I18n.load_path << File.dirname(__FILE__) + '/active_record/locale/en.yml'
</ruby>
-As you can see, +mb_chars+ is where the +proxy_class+ property comes in handy. This method will create a new instance of the configured proxy class using the instance of +String+ as a constructor argument. By default, the new +String+-like object will be an instance of the proxy class +ActiveSupport::Multibyte::Chars+. You can use +ActiveSupport::Multibyte.proxy_class=+ to set a different proxy class if you wish.
-
-Here, +mb_chars+ invokes +is_utf8?+ to checks if the string can be treated as UTF-8. On 1.9, the string's +encoding+ property is checked. On 1.8, +wants?+ checks to see if +$KCODE+ is "UTF-8" and, and +consumes?+ checks whether the string can be unpacked as UTF-8 without raising an error.
-
-The keen eye will have seen +ActiveSupport::Multibyte::Chars+ was specified as an +autoload+ earlier: _activesupport/lib/active_support/multibyte/chars.rb_ will be loaded without an explicit +require+ when we call +is_utf8+ on 1.8, or +mb_chars+ on any Ruby version. This file includes _activesupport/lib/active_support/string/access.rb_ which defines methods such as +at+, +from+, +to+, +first+ and +last+. These methods will return parts of the string depending on what is passed to them.
-
-The second file included is _activesupport/lib/active_support/string/behavior.rb_ which only defines +acts_like_string?+ on +String+, a method which always returns +true+. This method is used by +Object#acts_like?+, which accepts a single argument representing the downcased and symbolised version of a class, and returns true if the object's behavior is like that class. In this case the code would be +acts_like?(:string)+.
-
-The +Chars+ class also defines other important methods such as the "spaceship" method +<=>+, which is needed by the +Comparable+ module, in order to allow UTF-8-aware sorting.
-
-h3. Common Includes
-
-TODO: I feel this section would be better at the end of the guide as it breaks the flow.
+This will add the translations from +activerecord/lib/active_record/locale/en.yml+ to the load path for +I18n+, with this file being parsed when all the translations are loaded.
-This section is for all the common includes in the Railties.
+h4. Back to +activerecord/lib/active_record/railtie.rb+
-h4. +require 'active_support/inflector'+
-
-This file is _activesupport/lib/active_support/inflector.rb_ and makes a couple of requires out different files tasked with putting inflections in place:
+The next two <tt>require</tt>s in this file aren't run because their files are already required, with +rails+ being required by +rails/all+ and +active_model/railtie+ being required from +action_dispatch+.
<ruby>
- require 'active_support/inflector/inflections'
- require 'active_support/inflector/transliterate'
- require 'active_support/inflector/methods'
-
- require 'active_support/inflections'
- require 'active_support/core_ext/string/inflections'
+ require "rails"
+ require "active_model/railtie"
</ruby>
-The files included here define methods for modifying strings, such as +transliterate+ which will convert a Unicode string to its ASCII version, +parameterize+ for making strings into url-safe versions, +camelize+ for camel-casing a string such as +string_other+ into +StringOther+ and +ordinalize+ converting a string such as +101+ into +101st+. More information about these methods can be found in the Active Support Core Extensions Guide. TODO: Link to AS Guide.
-
-h4. +require 'active_support/core_ext/module/delegation'+
-
-_activesupport/lib/active_support/core_ext/module/delegation.rb_ defines the +delegate+ method which can be used to delegate methods to other methods in your code. Take the following code example:
-
-<ruby>
- class Client < ActiveRecord::Base
- has_one :address
+The next +require+ in this file is to +action_controller/railtie+.
- delegate :address_line_1, :to => :address
- end
-</ruby>
+h4. +actionpack/lib/action_controller/railtie.rb+
-This defines an +address_line_1+ method which is defined as:
+This file begins with a couple more requires to files that have already been loaded:
<ruby>
- def address_line_1(*args, &block)
- address.__send__(:address_line_1, *args, &block)
- rescue NoMethodError
- if address.nil?
- raise "address_line_1 is delegated to address.address_line_1, but address is nil: #{client.inspect}"
- end
- end
+ require "rails"
+ require "action_controller"
+ require "action_dispatch/railtie"
</ruby>
-h4. +require 'active_support/core_ext/class/attribute_accessors'+
-
-The file, _activesupport/lib/active_support/core_ext/class/attribute_accessors.rb_, defines the class accessor methods +cattr_writer+, +cattr_reader+ and +cattr_accessor+. +cattr_accessor+ defines a +cattr_reader+ and +cattr_writer+ for the symbol passed in. These methods work by defining class variables when you call their dynamic methods.
-
-Throughout the Railties there a couple of common includes. They are listed here for your convenience.
-
-h4. +require 'active_support/core_ext/module/attr_internal+
-
-This file defines three methods +attr_internal_reader+, +attr_internal_writer+ and +attr_internal_accessor+. These work very similar to the +attr_reader+, +attr_writer+ and +attr_accessor+ methods, except the variables they define begin with +@_+. This was done to ensure that they do not clash with variables used people using Rails, as people are less-likely to define say, +@_request+ than they are to define +@request+. An example of where this method is used is for +params+ in the +ActionController::Metal+ class.
-
-h4. +require 'active_support/ruby/shim'+
-
-The _activesupport/lib/active_support/ruby/shim.rb_ file requires methods that have been implemented in Ruby versions greater than 1.9. This is done so you can use Rails 3 on versions earlier than 1.9, such as 1.8.7. These methods are:
-
-* +Date#next_month+
-* +Date#next_year+
-* +DateTime#to_date+
-* +DateTime#to_datetime+
-* +DateTime#xmlschema+
-* +Enumerable#group_by+
-* +Enumerable#each_with_object+
-* +Enumerable#none?+
-* +Process#daemon+
-* +String#ord+
-* +Time#to_date+
-* +Time.to_time+
-* +Time.to_datetime+
+However the require after these is to a file that hasn't yet been loaded, +action_view/railtie+, which begins by requiring +action_view+.
-For more information see the Active Support Core Extensions guide TODO: link to relevant sections for each method.
+h4. +actionpack/lib/action_view.rb+
-And "the REXML security fix detailed here":[http://weblog.rubyonrails.org/2008/8/23/dos-vulnerabilities-in-rexml]
++action_view.rb+
diff --git a/railties/guides/source/performance_testing.textile b/railties/guides/source/performance_testing.textile
index b9401f3559..341525a75c 100644
--- a/railties/guides/source/performance_testing.textile
+++ b/railties/guides/source/performance_testing.textile
@@ -60,8 +60,8 @@ Let's assume your application has the following controller and model:
<ruby>
# routes.rb
-map.root :controller => 'home'
-map.resources :posts
+root :to => 'home#index'
+resources :posts
# home_controller.rb
class HomeController < ApplicationController
@@ -436,7 +436,7 @@ h4. Model
Project.benchmark("Creating project") do
project = Project.create("name" => "stuff")
project.create_manager("name" => "David")
- project.milestones << Milestone.find(:all)
+ project.milestones << Milestone.all
end
</ruby>
diff --git a/railties/guides/source/plugins.textile b/railties/guides/source/plugins.textile
index cb43282ace..f7c4a6f85c 100644
--- a/railties/guides/source/plugins.textile
+++ b/railties/guides/source/plugins.textile
@@ -25,7 +25,7 @@ This guide describes how to build a test-driven plugin that will:
* Add a custom generator command
* A custom route method that can be used in routes.rb
-For the purpose of this guide pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness. First, you need to get setup for development.
+For the purpose of this guide pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness. First, you need to get setup for development.
endprologue.
@@ -33,7 +33,7 @@ h3. Setup
h4. Create the Basic Application
-The examples in this guide require that you have a working rails application. To create a simple one execute:
+The examples in this guide require that you have a working rails application. To create a simple one execute:
<shell>
gem install rails
@@ -45,9 +45,9 @@ rake db:migrate
rails server
</shell>
-Then navigate to http://localhost:3000/birds. Make sure you have a functioning rails application before continuing.
+Then navigate to http://localhost:3000/birds. Make sure you have a functioning rails application before continuing.
-NOTE: The aforementioned instructions will work for sqlite3. For more detailed instructions on how to create a rails application for other databases see the API docs.
+NOTE: The aforementioned instructions will work for SQLite3. For more detailed instructions on how to create a Rails application for other databases see the API docs.
h4. Generate the Plugin Skeleton
@@ -116,7 +116,7 @@ Now you can add any +require+ statements to +lib/yaffle.rb+ and keep +init.rb+ c
h3. Tests
-In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. To setup your plugin to allow for easy testing you'll need to add 3 files:
+In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. To setup your plugin to allow for easy testing you'll need to add 3 files:
* A +database.yml+ file with all of your connection strings
* A +schema.rb+ file with your table definitions
@@ -143,7 +143,7 @@ postgresql:
min_messages: ERROR
mysql:
- adapter: mysql
+ adapter: mysql2
host: localhost
username: root
password: password
@@ -268,7 +268,7 @@ Finished in 0.002236 seconds.
1 test, 2 assertion, 0 failures, 0 errors, 0 skips
</shell>
-By default the setup above runs your tests with sqlite or sqlite3. To run tests with one of the other connection strings specified in +database.yml+, pass the DB environment variable to rake:
+By default the setup above runs your tests with SQLite or SQLite3. To run tests with one of the other connection strings specified in +database.yml+, pass the DB environment variable to rake:
<shell>
rake DB=sqlite
@@ -281,9 +281,9 @@ Now you are ready to test-drive your plugin!
h3. Extending Core Classes
-This section will explain how to add a method to String that will be available anywhere in your rails application.
+This section will explain how to add a method to String that will be available anywhere in your Rails application.
-In this example you will add a method to String named +to_squawk+. To begin, create a new test file with a few assertions:
+In this example you will add a method to String named +to_squawk+. To begin, create a new test file with a few assertions:
<ruby>
# vendor/plugins/yaffle/test/core_ext_test.rb
@@ -345,7 +345,7 @@ $ rails console
h4. Working with +init.rb+
-When Rails loads plugins it looks for a file named +init.rb+. However, when the plugin is initialized, +init.rb+ is invoked via +eval+ (not +require+) so it has slightly different behavior.
+When Rails loads plugins it looks for a file named +init.rb+. However, when the plugin is initialized, +init.rb+ is invoked via +eval+ (not +require+) so it has slightly different behavior.
NOTE: The plugins loader also looks for +rails/init.rb+, but that one is deprecated in favor of the top-level +init.rb+ aforementioned.
@@ -377,7 +377,7 @@ end
h3. Add an "acts_as" Method to Active Record
-A common pattern in plugins is to add a method called 'acts_as_something' to models. In this case, you want to write a method called 'acts_as_yaffle' that adds a 'squawk' method to your models.
+A common pattern in plugins is to add a method called 'acts_as_something' to models. In this case, you want to write a method called 'acts_as_yaffle' that adds a 'squawk' method to your models.
To begin, set up your files so that you have:
@@ -433,7 +433,7 @@ With structure you can easily separate the methods that will be used for the cla
h4. Add a Class Method
-This plugin will expect that you've added a method to your model named 'last_squawk'. However, the plugin users might have already defined a method on their model named 'last_squawk' that they use for something else. This plugin will allow the name to be changed by adding a class method called 'yaffle_text_field'.
+This plugin will expect that you've added a method to your model named 'last_squawk'. However, the plugin users might have already defined a method on their model named 'last_squawk' that they use for something else. This plugin will allow the name to be changed by adding a class method called 'yaffle_text_field'.
To start out, write a failing test that shows the behavior you'd like:
@@ -486,7 +486,7 @@ ActiveRecord::Base.send :include, Yaffle
h4. Add an Instance Method
-This plugin will add a method named 'squawk' to any Active Record objects that call 'acts_as_yaffle'. The 'squawk' method will simply set the value of one of the fields in the database.
+This plugin will add a method named 'squawk' to any Active Record objects that call 'acts_as_yaffle'. The 'squawk' method will simply set the value of one of the fields in the database.
To start out, write a failing test that shows the behavior you'd like:
@@ -556,11 +556,11 @@ end
ActiveRecord::Base.send :include, Yaffle
</ruby>
-NOTE: The use of +write_attribute+ to write to the field in model is just one example of how a plugin can interact with the model, and will not always be the right method to use. For example, you could also use +send("#{self.class.yaffle_text_field}=", string.to_squawk)+.
+NOTE: The use of +write_attribute+ to write to the field in model is just one example of how a plugin can interact with the model, and will not always be the right method to use. For example, you could also use +send("#{self.class.yaffle_text_field}=", string.to_squawk)+.
h3. Models
-This section describes how to add a model named 'Woodpecker' to your plugin that will behave the same as a model in your main app. When storing models, controllers, views and helpers in your plugin, it's customary to keep them in directories that match the rails directories. For this example, create a file structure like this:
+This section describes how to add a model named 'Woodpecker' to your plugin that will behave the same as a model in your main app. When storing models, controllers, views and helpers in your plugin, it's customary to keep them in directories that match the rails directories. For this example, create a file structure like this:
<shell>
vendor/plugins/yaffle/
@@ -594,7 +594,7 @@ class WoodpeckerTest < Test::Unit::TestCase
end
</ruby>
-This is just a simple test to make sure the class is being loaded correctly. After watching it fail with +rake+, you can make it pass like so:
+This is just a simple test to make sure the class is being loaded correctly. After watching it fail with +rake+, you can make it pass like so:
* *vendor/plugins/yaffle/lib/yaffle.rb:*
@@ -607,7 +607,7 @@ This is just a simple test to make sure the class is being loaded correctly. Af
end
</ruby>
-Adding directories to the load path makes them appear just like files in the main app directory - except that they are only loaded once, so you have to restart the web server to see the changes in the browser. Removing directories from the 'load_once_paths' allow those changes to picked up as soon as you save the file - without having to restart the web server. This is particularly useful as you develop the plugin.
+Adding directories to the load path makes them appear just like files in the main app directory - except that they are only loaded once, so you have to restart the web server to see the changes in the browser. Removing directories from the 'load_once_paths' allow those changes to picked up as soon as you save the file - without having to restart the web server. This is particularly useful as you develop the plugin.
* *vendor/plugins/yaffle/lib/app/models/woodpecker.rb:*
@@ -630,7 +630,7 @@ Now your test should be passing, and you should be able to use the Woodpecker mo
h3. Controllers
-This section describes how to add a controller named 'woodpeckers' to your plugin that will behave the same as a controller in your main app. This is very similar to adding a model.
+This section describes how to add a controller named 'woodpeckers' to your plugin that will behave the same as a controller in your main app. This is very similar to adding a model.
You can test your plugin's controller as you would test any other controller:
@@ -661,7 +661,7 @@ class WoodpeckersControllerTest < Test::Unit::TestCase
end
</ruby>
-This is just a simple test to make sure the controller is being loaded correctly. After watching it fail with +rake+, you can make it pass like so:
+This is just a simple test to make sure the controller is being loaded correctly. After watching it fail with +rake+, you can make it pass like so:
* *vendor/plugins/yaffle/lib/yaffle.rb:*
@@ -686,11 +686,11 @@ class WoodpeckersController < ActionController::Base
end
</ruby>
-Now your test should be passing, and you should be able to use the Woodpeckers controller in your app. If you add a route for the woodpeckers controller you can start up your server and go to http://localhost:3000/woodpeckers to see your controller in action.
+Now your test should be passing, and you should be able to use the Woodpeckers controller in your app. If you add a route for the woodpeckers controller you can start up your server and go to http://localhost:3000/woodpeckers to see your controller in action.
h3. Helpers
-This section describes how to add a helper named 'WoodpeckersHelper' to your plugin that will behave the same as a helper in your main app. This is very similar to adding a model and a controller.
+This section describes how to add a helper named 'WoodpeckersHelper' to your plugin that will behave the same as a helper in your main app. This is very similar to adding a model and a controller.
You can test your plugin's helper as you would test any other helper:
@@ -707,7 +707,7 @@ class WoodpeckersHelperTest < Test::Unit::TestCase
end
</ruby>
-This is just a simple test to make sure the helper is being loaded correctly. After watching it fail with +rake+, you can make it pass like so:
+This is just a simple test to make sure the helper is being loaded correctly. After watching it fail with +rake+, you can make it pass like so:
* *vendor/plugins/yaffle/lib/yaffle.rb:*
@@ -736,9 +736,9 @@ Now your test should be passing, and you should be able to use the Woodpeckers h
h3. Routes
-In a standard 'routes.rb' file you use routes like 'map.connect' or 'map.resources'. You can add your own custom routes from a plugin. This section will describe how to add a custom method called that can be called with 'map.yaffles'.
+You can add your own custom routes from a plugin. This section will describe how to add a custom method that can be called with 'map.yaffles'.
-Testing routes from plugins is slightly different from testing routes in a standard rails application. To begin, add a test like this:
+Testing routes from plugins is slightly different from testing routes in a standard Rails application. To begin, add a test like this:
* *vendor/plugins/yaffle/test/routing_test.rb*
@@ -802,20 +802,20 @@ You can also see if your routes work by running +rake routes+ from your app dire
h3. Generators
-Many plugins ship with generators. When you created the plugin above, you specified the +--generator+ option, so you already have the generator stubs in 'vendor/plugins/yaffle/generators/yaffle'.
+Many plugins ship with generators. When you created the plugin above, you specified the +--generator+ option, so you already have the generator stubs in 'vendor/plugins/yaffle/generators/yaffle'.
Building generators is a complex topic unto itself and this section will cover one small aspect of generators: generating a simple text file.
h4. Testing Generators
-Many rails plugin authors do not test their generators, however testing generators is quite simple. A typical generator test does the following:
+Many rails plugin authors do not test their generators, however testing generators is quite simple. A typical generator test does the following:
* Creates a new fake rails root directory that will serve as destination
* Runs the generator
* Asserts that the correct files were generated
* Removes the fake rails root
-This section will describe how to create a simple generator that adds a file. For the generator in this section, the test could look something like this:
+This section will describe how to create a simple generator that adds a file. For the generator in this section, the test could look something like this:
* *vendor/plugins/yaffle/test/definition_generator_test.rb*
@@ -854,7 +854,7 @@ class DefinitionGeneratorTest < Test::Unit::TestCase
end
</ruby>
-You can run 'rake' from the plugin directory to see this fail. Unless you are doing more advanced generator commands it typically suffices to just test the Generate script, and trust that rails will handle the Destroy and Update commands for you.
+You can run 'rake' from the plugin directory to see this fail. Unless you are doing more advanced generator commands it typically suffices to just test the Generate script, and trust that rails will handle the Destroy and Update commands for you.
To make it pass, create the generator:
@@ -872,9 +872,9 @@ end
h4. The +USAGE+ File
-If you plan to distribute your plugin, developers will expect at least a minimum of documentation. You can add simple documentation to the generator by updating the USAGE file.
+If you plan to distribute your plugin, developers will expect at least a minimum of documentation. You can add simple documentation to the generator by updating the USAGE file.
-Rails ships with several built-in generators. You can see all of the generators available to you by typing the following at the command line:
+Rails ships with several built-in generators. You can see all of the generators available to you by typing the following at the command line:
<shell>
rails generate
@@ -899,9 +899,9 @@ Description:
h3. Add a Custom Generator Command
-You may have noticed above that you can used one of the built-in rails migration commands +migration_template+. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods.
+You may have noticed above that you can used one of the built-in rails migration commands +migration_template+. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods.
-This section describes how you you can create your own commands to add and remove a line of text from 'routes.rb'. This example creates a very simple method that adds or removes a text file.
+This section describes how you you can create your own commands to add and remove a line of text from 'routes.rb'. This example creates a very simple method that adds or removes a text file.
To start, add the following test method:
@@ -985,7 +985,7 @@ end
h3. Generator Commands
-You may have noticed above that you can used one of the built-in rails migration commands +migration_template+. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods.
+You may have noticed above that you can used one of the built-in rails migration commands +migration_template+. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods.
This section describes how you you can create your own commands to add and remove a line of text from 'config/routes.rb'.
@@ -1125,9 +1125,9 @@ NOTE: If you haven't set up the custom route from above, 'rails destroy' will fa
h3. Migrations
-If your plugin requires changes to the app's database you will likely want to somehow add migrations. Rails does not include any built-in support for calling migrations from plugins, but you can still make it easy for developers to call migrations from plugins.
+If your plugin requires changes to the app's database you will likely want to somehow add migrations. Rails does not include any built-in support for calling migrations from plugins, but you can still make it easy for developers to call migrations from plugins.
-If you have a very simple needs, like creating a table that will always have the same name and columns, then you can use a more simple solution, like creating a custom rake task or method. If your migration needs user input to supply table names or other options, you probably want to opt for generating a migration.
+If you have a very simple needs, like creating a table that will always have the same name and columns, then you can use a more simple solution, like creating a custom rake task or method. If your migration needs user input to supply table names or other options, you probably want to opt for generating a migration.
Let's say you have the following migration in your plugin:
@@ -1199,12 +1199,12 @@ NOTE: several plugin frameworks such as Desert and Engines provide more advanced
h4. Generate Migrations
-Generating migrations has several advantages over other methods. Namely, you can allow other developers to more easily customize the migration. The flow looks like this:
+Generating migrations has several advantages over other methods. Namely, you can allow other developers to more easily customize the migration. The flow looks like this:
* call your rails generate script and pass in whatever options they need
* examine the generated migration, adding/removing columns or other options as necessary
-This example will demonstrate how to use one of the built-in generator methods named 'migration_template' to create a migration file. Extending the rails migration generator requires a somewhat intimate knowledge of the migration generator internals, so it's best to write a test first:
+This example will demonstrate how to use one of the built-in generator methods named 'migration_template' to create a migration file. Extending the rails migration generator requires a somewhat intimate knowledge of the migration generator internals, so it's best to write a test first:
* *vendor/plugins/yaffle/test/yaffle_migration_generator_test.rb*
@@ -1254,7 +1254,7 @@ class MigrationGeneratorTest < Test::Unit::TestCase
end
</ruby>
-NOTE: the migration generator checks to see if a migation already exists, and it's hard-coded to check the 'db/migrate' directory. As a result, if your test tries to generate a migration that already exists in the app, it will fail. The easy workaround is to make sure that the name you generate in your test is very unlikely to actually appear in the app.
+NOTE: The migration generator checks to see if a migration already exists, and it's hard-coded to check the +db/migrate+ directory. As a result, if your test tries to generate a migration that already exists in the app, it will fail. The easy workaround is to make sure that the name you generate in your test is very unlikely to actually appear in the app.
After running the test with 'rake' you can make it pass with:
@@ -1288,9 +1288,9 @@ class YaffleMigrationGenerator < Rails::Generator::NamedBase
end
</ruby>
-The generator creates a new file in 'db/migrate' with a timestamp and an 'add_column' statement. It reuses the built-in rails +migration_template+ method, and reuses the built-in rails migration template.
+The generator creates a new file in 'db/migrate' with a timestamp and an 'add_column' statement. It reuses the built-in Rails +migration_template+ method, and reuses the built-in rails migration template.
-It's courteous to check to see if table names are being pluralized whenever you create a generator that needs to be aware of table names. This way people using your generator won't have to manually change the generated files if they've turned pluralization off.
+It's courteous to check to see if table names are being pluralized whenever you create a generator that needs to be aware of table names. This way people using your generator won't have to manually change the generated files if they've turned pluralization off.
To run the generator, type the following at the command line:
@@ -1314,9 +1314,9 @@ class AddYaffleFieldsToBirds < ActiveRecord::Migration
end
</ruby>
-h3. Rake tasks
+h3. Rake Tasks
-When you created the plugin with the built-in rails generator, it generated a rake file for you in 'vendor/plugins/yaffle/tasks/yaffle_tasks.rake'. Any rake task you add here will be available to the app.
+When you created the plugin with the built-in rails generator, it generated a rake file for you in 'vendor/plugins/yaffle/tasks/yaffle_tasks.rake'. Any rake task you add here will be available to the app.
Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so:
@@ -1343,11 +1343,11 @@ Note that tasks from +vendor/plugins/yaffle/Rakefile+ are not available to the m
h3. Plugins as Gems
-Turning your rails plugin into a gem is a simple and straightforward task. This section will cover how to turn your plugin into a gem. It will not cover how to distribute that gem.
+Turning your rails plugin into a gem is a simple and straightforward task. This section will cover how to turn your plugin into a gem. It will not cover how to distribute that gem.
Rails 3 ignores both <tt>init.rb</tt> and <tt>rails/init.rb</tt> file of a gem. Also, the name of the plugin now is relevant since +config.gem+ tries to load it. Either name the main file after your gem, or document that users should use the +:lib+ option.
-It's common practice to put any developer-centric rake tasks (such as tests, rdoc and gem package tasks) in +Rakefile+. A rake task that packages the gem might look like this:
+It's common practice to put any developer-centric rake tasks (such as tests, rdoc and gem package tasks) in +Rakefile+. A rake task that packages the gem might look like this:
* *vendor/plugins/yaffle/Rakefile:*
@@ -1395,14 +1395,14 @@ h3. RDoc Documentation
Once your plugin is stable and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy.
-The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are:
+The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are:
* Your name
* How to install
* How to add the functionality to the app (several examples of common use cases)
* Warning, gotchas or tips that might help save users time
-Once your README is solid, go through and add rdoc comments to all of the methods that developers will use. It's also customary to add '#:nodoc:' comments to those parts of the code that are not part of the public api.
+Once your README is solid, go through and add rdoc comments to all of the methods that developers will use. It's also customary to add '#:nodoc:' comments to those parts of the code that are not part of the public api.
Once your comments are good to go, navigate to your plugin directory and run:
@@ -1416,12 +1416,12 @@ If you prefer to use RSpec instead of Test::Unit, you may be interested in the "
h4. References
-* http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-i
-* http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-ii
-* http://github.com/technoweenie/attachment_fu/tree/master
-* http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html
-* http://www.mbleigh.com/2008/6/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins
-* http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2.
+* "Complete Guide to Rails Plugins - Part 1":http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-i
+* "Complete Guide to Rails Plugins - Part 2":http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-ii
+* "Attachment_fu Plugin":http://github.com/technoweenie/attachment_fu/tree/master
+* "Keeping init.rb thin":http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html
+* "GemPlugins":http://www.mbleigh.com/2008/06/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins
+* "Extending Routes":http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2
h4. Contents of +lib/yaffle.rb+
diff --git a/railties/guides/source/rails_application_templates.textile b/railties/guides/source/rails_application_templates.textile
index d4b887ad02..8f87b4cd58 100644
--- a/railties/guides/source/rails_application_templates.textile
+++ b/railties/guides/source/rails_application_templates.textile
@@ -20,7 +20,7 @@ $ rails new blog -m ~/template.rb
It's also possible to apply a template using a URL :
<shell>
-$ rails new blog -m http://gist.github.com/31208.txt
+$ rails new blog -m https://gist.github.com/755496.txt
</shell>
Alternatively, you can use the rake task +rails:template+ to apply a template to an existing Rails application :
@@ -37,7 +37,7 @@ Rails templates API is very self explanatory and easy to understand. Here's an e
# template.rb
run "rm public/index.html"
generate(:scaffold, "person name:string")
-route "map.root :controller => 'people'"
+route "root :to => 'people#index'"
rake("db:migrate")
git :init
@@ -49,7 +49,7 @@ The following sections outlines the primary methods provided by the API :
h4. gem(name, options = {})
-Adds a +config.gem+ entry for the supplied gem to the generated application’s +config/environment.rb+.
+Adds a +gem+ entry for the supplied gem to the generated application’s +Gemfile+.
For example, if your application depends on the gems +bj+ and +nokogiri+ :
@@ -66,6 +66,16 @@ rake "gems:install"
And let Rails take care of installing the required gems if they’re not already installed.
+h4. add_source(source, options = {})
+
+Adds the given source to the generated application's +Gemfile+.
+
+For example, if you need to source a gem from "http://code.whytheluckystiff.net":
+
+<ruby>
+add_source "http://code.whytheluckystiff.net"
+</ruby>
+
h4. plugin(name, options = {})
Installs a plugin to the generated application.
@@ -183,7 +193,7 @@ h4. route(routing_code)
This adds a routing entry to the +config/routes.rb+ file. In above steps, we generated a person scaffold and also removed +public/index.html+. Now to make +PeopleController#index+ as the default page for the application :
<ruby>
-route "map.root :controller => :person"
+route "root :to => 'person#index'"
</ruby>
h4. inside(dir)
diff --git a/railties/guides/source/rails_on_rack.textile b/railties/guides/source/rails_on_rack.textile
index 8338777480..c1b91da7a8 100644
--- a/railties/guides/source/rails_on_rack.textile
+++ b/railties/guides/source/rails_on_rack.textile
@@ -223,8 +223,8 @@ h4. Learning Rack
* "Official Rack Website":http://rack.github.com
* "Introducing Rack":http://chneukirchen.org/blog/archive/2007/02/introducing-rack.html
-* "Ruby on Rack #1 - Hello Rack!":http://m.onkey.org/2008/11/17/ruby-on-rack-1
-* "Ruby on Rack #2 - The Builder":http://m.onkey.org/2008/11/18/ruby-on-rack-2-rack-builder
+* "Ruby on Rack #1 - Hello Rack!":http://m.onkey.org/ruby-on-rack-1-hello-rack
+* "Ruby on Rack #2 - The Builder":http://m.onkey.org/ruby-on-rack-2-the-builder
h4. Understanding Middlewares
diff --git a/railties/guides/source/routing.textile b/railties/guides/source/routing.textile
index 32346e8f2b..15b26d8f9e 100644
--- a/railties/guides/source/routing.textile
+++ b/railties/guides/source/routing.textile
@@ -85,6 +85,9 @@ creates seven different routes in your application, all mapping to the +Photos+
|PUT |/photos/:id |update |update a specific photo |
|DELETE |/photos/:id |destroy |delete a specific photo |
+
+NOTE: Rails routes are matched in the order they are specified, so if you have a +resources :photos+ above a +get 'photos/poll'+ the +show+ action's route for the +resources+ line will be matched before the +get+ line. To fix this, move the +get+ line *above* the +resources+ line so that it is matched first.
+
h4. Paths and URLs
Creating a resourceful route will also expose a number of helpers to the controllers in your application. In the case of +resources :photos+:
diff --git a/railties/guides/source/security.textile b/railties/guides/source/security.textile
index fbafc40d93..7f303c3565 100644
--- a/railties/guides/source/security.textile
+++ b/railties/guides/source/security.textile
@@ -616,7 +616,7 @@ h5(#sql-injection-introduction). Introduction
SQL injection attacks aim at influencing database queries by manipulating web application parameters. A popular goal of SQL injection attacks is to bypass authorization. Another goal is to carry out data manipulation or reading arbitrary data. Here is an example of how not to use user input data in a query:
<ruby>
-Project.find(:all, :conditions => "name = '#{params[:name]}'")
+Project.all(:conditions => "name = '#{params[:name]}'")
</ruby>
This could be in a search action and the user may enter a project's name that he wants to find. If a malicious user enters ' OR 1 --, the resulting SQL query will be:
@@ -632,7 +632,7 @@ h5. Bypassing Authorization
Usually a web application includes access control. The user enters his login credentials, the web application tries to find the matching record in the users table. The application grants access when it finds a record. However, an attacker may possibly bypass this check with SQL injection. The following shows a typical database query in Rails to find the first record in the users table which matches the login credentials parameters supplied by the user.
<ruby>
-User.find(:first, "login = '#{params[:name]}' AND password = '#{params[:password]}'")
+User.first("login = '#{params[:name]}' AND password = '#{params[:password]}'")
</ruby>
If an attacker enters ' OR '1'='1 as the name, and ' OR '2'>'1 as the password, the resulting SQL query will be:
@@ -648,7 +648,7 @@ h5. Unauthorized Reading
The UNION statement connects two SQL queries and returns the data in one set. An attacker can use it to read arbitrary data from the database. Let's take the example from above:
<ruby>
-Project.find(:all, :conditions => "name = '#{params[:name]}'")
+Project.all(:conditions => "name = '#{params[:name]}'")
</ruby>
And now let's inject another query using the UNION statement:
@@ -675,13 +675,13 @@ Ruby on Rails has a built-in filter for special SQL characters, which will escap
Instead of passing a string to the conditions option, you can pass an array to sanitize tainted strings like this:
<ruby>
-Model.find(:first, :conditions => ["login = ? AND password = ?", entered_user_name, entered_password])
+Model.first(:conditions => ["login = ? AND password = ?", entered_user_name, entered_password])
</ruby>
As you can see, the first part of the array is an SQL fragment with question marks. The sanitized versions of the variables in the second part of the array replace the question marks. Or you can pass a hash for the same result:
<ruby>
-Model.find(:first, :conditions => {:login => entered_user_name, :password => entered_password})
+Model.first(:conditions => {:login => entered_user_name, :password => entered_password})
</ruby>
The array or hash form is only available in model instances. You can try +sanitize_sql()+ elsewhere. _(highlight)Make it a habit to think about the security consequences when using an external string in SQL_.
diff --git a/railties/guides/w3c_validator.rb b/railties/guides/w3c_validator.rb
index da5200c0b7..f1fe1e0f33 100644
--- a/railties/guides/w3c_validator.rb
+++ b/railties/guides/w3c_validator.rb
@@ -21,7 +21,7 @@
#
# Separate many using commas:
#
-# # validates only
+# # validates only association_basics.html and migrations.html
# ONLY=assoc,migrations rake validate_guides
#
# ---------------------------------------------------------------------------
@@ -88,4 +88,4 @@ module RailsGuides
end
end
-RailsGuides::Validator.new.validate \ No newline at end of file
+RailsGuides::Validator.new.validate