railties 3.0.0.beta2 → 3.0.0.beta3

Sign up to get free protection for your applications and to get access to all the features.
Files changed (147) hide show
  1. data/CHANGELOG +6 -2
  2. data/guides/{images → assets/images}/belongs_to.png +0 -0
  3. data/guides/{images → assets/images}/book_icon.gif +0 -0
  4. data/guides/{images → assets/images}/bullet.gif +0 -0
  5. data/guides/{images → assets/images}/challenge.png +0 -0
  6. data/guides/{images → assets/images}/chapters_icon.gif +0 -0
  7. data/guides/{images → assets/images}/check_bullet.gif +0 -0
  8. data/guides/{images → assets/images}/credits_pic_blank.gif +0 -0
  9. data/guides/{images → assets/images}/csrf.png +0 -0
  10. data/guides/{images → assets/images}/customized_error_messages.png +0 -0
  11. data/guides/{images → assets/images}/edge_badge.png +0 -0
  12. data/guides/{images → assets/images}/error_messages.png +0 -0
  13. data/guides/{images → assets/images}/feature_tile.gif +0 -0
  14. data/guides/{images → assets/images}/footer_tile.gif +0 -0
  15. data/guides/{images → assets/images}/fxn.png +0 -0
  16. data/guides/{images → assets/images}/grey_bullet.gif +0 -0
  17. data/guides/{images → assets/images}/habtm.png +0 -0
  18. data/guides/{images → assets/images}/has_many.png +0 -0
  19. data/guides/{images → assets/images}/has_many_through.png +0 -0
  20. data/guides/{images → assets/images}/has_one.png +0 -0
  21. data/guides/{images → assets/images}/has_one_through.png +0 -0
  22. data/guides/{images → assets/images}/header_backdrop.png +0 -0
  23. data/guides/{images → assets/images}/header_tile.gif +0 -0
  24. data/guides/{images → assets/images}/i18n/demo_localized_pirate.png +0 -0
  25. data/guides/{images → assets/images}/i18n/demo_translated_en.png +0 -0
  26. data/guides/{images → assets/images}/i18n/demo_translated_pirate.png +0 -0
  27. data/guides/{images → assets/images}/i18n/demo_translation_missing.png +0 -0
  28. data/guides/{images → assets/images}/i18n/demo_untranslated.png +0 -0
  29. data/guides/{images → assets/images}/icons/README +0 -0
  30. data/guides/{images → assets/images}/icons/callouts/1.png +0 -0
  31. data/guides/{images → assets/images}/icons/callouts/10.png +0 -0
  32. data/guides/{images → assets/images}/icons/callouts/11.png +0 -0
  33. data/guides/{images → assets/images}/icons/callouts/12.png +0 -0
  34. data/guides/{images → assets/images}/icons/callouts/13.png +0 -0
  35. data/guides/{images → assets/images}/icons/callouts/14.png +0 -0
  36. data/guides/{images → assets/images}/icons/callouts/15.png +0 -0
  37. data/guides/{images → assets/images}/icons/callouts/2.png +0 -0
  38. data/guides/{images → assets/images}/icons/callouts/3.png +0 -0
  39. data/guides/{images → assets/images}/icons/callouts/4.png +0 -0
  40. data/guides/{images → assets/images}/icons/callouts/5.png +0 -0
  41. data/guides/{images → assets/images}/icons/callouts/6.png +0 -0
  42. data/guides/{images → assets/images}/icons/callouts/7.png +0 -0
  43. data/guides/{images → assets/images}/icons/callouts/8.png +0 -0
  44. data/guides/{images → assets/images}/icons/callouts/9.png +0 -0
  45. data/guides/{images → assets/images}/icons/caution.png +0 -0
  46. data/guides/{images → assets/images}/icons/example.png +0 -0
  47. data/guides/{images → assets/images}/icons/home.png +0 -0
  48. data/guides/{images → assets/images}/icons/important.png +0 -0
  49. data/guides/{images → assets/images}/icons/next.png +0 -0
  50. data/guides/{images → assets/images}/icons/note.png +0 -0
  51. data/guides/{images → assets/images}/icons/prev.png +0 -0
  52. data/guides/{images → assets/images}/icons/tip.png +0 -0
  53. data/guides/{images → assets/images}/icons/up.png +0 -0
  54. data/guides/{images → assets/images}/icons/warning.png +0 -0
  55. data/guides/assets/images/jaimeiniesta.jpg +0 -0
  56. data/guides/{images → assets/images}/nav_arrow.gif +0 -0
  57. data/guides/{images → assets/images}/polymorphic.png +0 -0
  58. data/guides/{images → assets/images}/posts_index.png +0 -0
  59. data/guides/{images → assets/images}/rails_guides_logo.gif +0 -0
  60. data/guides/{images → assets/images}/rails_logo_remix.gif +0 -0
  61. data/guides/{images → assets/images}/rails_welcome.png +0 -0
  62. data/guides/{images → assets/images}/session_fixation.png +0 -0
  63. data/guides/{images → assets/images}/tab_grey.gif +0 -0
  64. data/guides/{images → assets/images}/tab_info.gif +0 -0
  65. data/guides/{images → assets/images}/tab_note.gif +0 -0
  66. data/guides/{images → assets/images}/tab_red.gif +0 -0
  67. data/guides/{images → assets/images}/tab_yellow.gif +0 -0
  68. data/guides/{images → assets/images}/tab_yellow.png +0 -0
  69. data/guides/{images → assets/images}/validation_error_messages.png +0 -0
  70. data/guides/{files → assets}/javascripts/code_highlighter.js +0 -0
  71. data/guides/{files → assets}/javascripts/guides.js +0 -0
  72. data/guides/{files → assets}/javascripts/highlighters.js +0 -0
  73. data/guides/{files → assets}/stylesheets/main.css +26 -15
  74. data/guides/{files → assets}/stylesheets/print.css +0 -0
  75. data/guides/{files → assets}/stylesheets/reset.css +0 -0
  76. data/guides/{files → assets}/stylesheets/style.css +0 -0
  77. data/guides/{files → assets}/stylesheets/syntax.css +0 -0
  78. data/guides/rails_guides/generator.rb +79 -29
  79. data/guides/rails_guides/helpers.rb +2 -2
  80. data/guides/rails_guides/indexer.rb +24 -11
  81. data/guides/source/2_2_release_notes.textile +1 -1
  82. data/guides/source/3_0_release_notes.textile +27 -1
  83. data/guides/source/action_controller_overview.textile +7 -7
  84. data/guides/source/action_view_overview.textile +15 -15
  85. data/guides/source/active_record_querying.textile +4 -3
  86. data/guides/source/active_support_core_extensions.textile +6 -6
  87. data/guides/source/activerecord_validations_callbacks.textile +1 -1
  88. data/guides/source/association_basics.textile +83 -82
  89. data/guides/source/command_line.textile +16 -12
  90. data/guides/source/configuring.textile +1 -1
  91. data/guides/source/contribute.textile +1 -1
  92. data/guides/source/contributing_to_rails.textile +3 -4
  93. data/guides/source/credits.html.erb +64 -0
  94. data/guides/source/debugging_rails_applications.textile +2 -1
  95. data/guides/source/form_helpers.textile +15 -13
  96. data/guides/source/getting_started.textile +9 -8
  97. data/guides/source/index.html.erb +154 -0
  98. data/guides/source/initialization.textile +4138 -0
  99. data/guides/source/layout.html.erb +15 -7
  100. data/guides/source/layouts_and_rendering.textile +6 -5
  101. data/guides/source/nested_model_forms.textile +3 -3
  102. data/guides/source/performance_testing.textile +4 -4
  103. data/guides/source/plugins.textile +15 -14
  104. data/guides/source/rails_on_rack.textile +1 -1
  105. data/guides/source/routing.textile +379 -490
  106. data/guides/source/security.textile +5 -5
  107. data/guides/source/testing.textile +3 -2
  108. data/lib/rails.rb +7 -2
  109. data/lib/rails/application.rb +9 -2
  110. data/lib/rails/application/configuration.rb +19 -10
  111. data/lib/rails/application/finisher.rb +4 -0
  112. data/lib/rails/backtrace_cleaner.rb +1 -1
  113. data/{bin/rails → lib/rails/cli.rb} +0 -0
  114. data/lib/rails/commands/runner.rb +1 -1
  115. data/lib/rails/configuration.rb +12 -0
  116. data/lib/rails/engine.rb +6 -10
  117. data/lib/rails/engine/configuration.rb +2 -3
  118. data/lib/rails/generators.rb +1 -6
  119. data/lib/rails/generators/erb/scaffold/scaffold_generator.rb +0 -7
  120. data/lib/rails/generators/erb/scaffold/templates/_form.html.erb +10 -1
  121. data/lib/rails/generators/erb/scaffold/templates/show.html.erb +2 -0
  122. data/lib/rails/generators/migration.rb +3 -3
  123. data/lib/rails/generators/rails/app/app_generator.rb +1 -1
  124. data/lib/rails/generators/rails/app/templates/Gemfile +2 -0
  125. data/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb +1 -0
  126. data/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt +14 -0
  127. data/lib/rails/generators/rails/app/templates/config/application.rb +4 -1
  128. data/lib/rails/generators/rails/app/templates/config/boot.rb +5 -13
  129. data/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt +3 -0
  130. data/lib/rails/generators/rails/app/templates/config/initializers/{cookie_verification_secret.rb.tt → secret_token.rb.tt} +1 -1
  131. data/lib/rails/generators/rails/app/templates/config/initializers/session_store.rb.tt +1 -3
  132. data/lib/rails/generators/rails/app/templates/public/index.html +2 -1
  133. data/lib/rails/generators/rails/app/templates/public/javascripts/rails.js +41 -32
  134. data/lib/rails/generators/rails/app/templates/test/{test_helper.rb → test_helper.rb.tt} +2 -0
  135. data/lib/rails/generators/rails/model/USAGE +15 -0
  136. data/lib/rails/generators/rails/stylesheets/templates/scaffold.css +3 -8
  137. data/lib/rails/paths.rb +17 -5
  138. data/lib/rails/plugin.rb +1 -1
  139. data/lib/rails/railtie.rb +3 -25
  140. data/lib/rails/test_unit/testing.rake +11 -7
  141. data/lib/rails/version.rb +1 -1
  142. data/lib/rails/webrick_server.rb +2 -2
  143. metadata +93 -92
  144. data/guides/source/credits.textile.erb +0 -60
  145. data/guides/source/index.textile.erb +0 -139
  146. data/lib/rails/generators/erb/scaffold/templates/layout.html.erb +0 -17
  147. data/lib/rails/generators/rails/app/templates/app/views/layouts/.empty_directory +0 -0
@@ -0,0 +1,4138 @@
1
+ h2. The Rails Initialization Process
2
+
3
+ This guide explains how the initialization process in Rails works as of Rails 3.
4
+
5
+ * Using +rails server+
6
+ * Using Passenger
7
+
8
+ endprologue.
9
+
10
+ This guide first describes the process of +rails server+ then explains the Passenger + Rack method, before delving into the common initialize pattern these two go through.
11
+
12
+ h3. Launch!
13
+
14
+ As of Rails 3, +script/server+ has become +rails server+. This was done to centralise all rails related commands to one common file.
15
+
16
+ The actual +rails+ command is kept in _railties/bin/rails_ and goes like this:
17
+
18
+ <ruby>
19
+ require 'rbconfig'
20
+
21
+ module Rails
22
+ module ScriptRailsLoader
23
+ RUBY = File.join(*RbConfig::CONFIG.values_at("bindir", "ruby_install_name")) + RbConfig::CONFIG["EXEEXT"]
24
+ SCRIPT_RAILS = File.join('script', 'rails')
25
+
26
+ def self.exec_script_rails!
27
+ cwd = Dir.pwd
28
+ exec RUBY, SCRIPT_RAILS, *ARGV if File.exists?(SCRIPT_RAILS)
29
+ Dir.chdir("..") do
30
+ # Recurse in a chdir block: if the search fails we want to be sure
31
+ # the application is generated in the original working directory.
32
+ exec_script_rails! unless cwd == Dir.pwd
33
+ end
34
+ rescue SystemCallError
35
+ # could not chdir, no problem just return
36
+ end
37
+ end
38
+ end
39
+
40
+ Rails::ScriptRailsLoader.exec_script_rails!
41
+
42
+ railties_path = File.expand_path('../../lib', __FILE__)
43
+ $:.unshift(railties_path) if File.directory?(railties_path) && !$:.include?(railties_path)
44
+
45
+ require 'rails/ruby_version_check'
46
+ Signal.trap("INT") { puts; exit }
47
+
48
+ require 'rails/commands/application'
49
+ </ruby>
50
+
51
+ The +Rails::ScriptRailsLoader+ module here defines two constants: +RUBY+ and +SCRIPT_RAILS+. +RUBY+ is the full path to your ruby executable, on a Snow Leopard system it's _/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/bin/ruby_. +SCRIPT_RAILS+ is simply _script/rails_. When +exec_script_rails+ is invoked, this will attempt to +exec+ the _rails_ file in the _script_ directory using the path to your Ruby executable, +RUBY+. If +exec+ is invoked, the program will stop at this point. If the _script/rails_ file doesn't exist in the current directory, Rails will recurse upwards until it finds it by calling +exec_script_rails+ from inside the +Dir.chdir("..")+. This is handy if you're currently in one of the sub-directories of the rails application and wish to launch a server or a console.
52
+
53
+ If Rails cannot execute _script/rails_ then it will fall back to the standard +rails+ command task of generating an application.
54
+
55
+ In +script/rails+ we see the following:
56
+
57
+ <ruby>
58
+ #!/usr/bin/env ruby
59
+ # This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application.
60
+
61
+ ENV_PATH = File.expand_path('../../config/environment', __FILE__)
62
+ BOOT_PATH = File.expand_path('../../config/boot', __FILE__)
63
+ APP_PATH = File.expand_path('../../config/application', __FILE__)
64
+
65
+ require BOOT_PATH
66
+ require 'rails/commands'
67
+ </ruby>
68
+
69
+ This obviously defines a couple of constants to some pretty important files, _config/environment.rb_, _config/boot.rb_ and _config/application.rb_ all within the context of +__FILE__+ which is of course +script/rails+ in the root of your application. Then it goes on to +require BOOT_PATH+ which leads us onto _config/boot.rb_.
70
+
71
+ h3. Passenger
72
+
73
+ Before we dive into what _config/boot.rb_ encompasses, we'll just glimpse at what Passenger does enough to get an understanding of how it requires a Rails application.
74
+
75
+ Passenger will require _config/environment.rb_ by way of its +PhusionPassenger::Railz::ApplicationSpawner#preload_application+ method. _config/environment.rb_ requires _config/application.rb_ which requires _config/boot.rb_. That's how the Rails boot process begins with Passenger in a nutshell.
76
+
77
+ h3. _config/boot.rb_
78
+
79
+ _config/boot.rb_ is the first stop for everything for initializing your application. This boot process does quite a bit of work for you and so this section attempts to go in-depth enough to explain what each of the pieces does.
80
+
81
+ <ruby>
82
+ # Use Bundler (preferred)
83
+ begin
84
+ require File.expand_path('../../.bundle/environment', __FILE__)
85
+ rescue LoadError
86
+ require 'rubygems'
87
+ require 'bundler'
88
+ Bundler.setup
89
+ end
90
+
91
+ </ruby>
92
+
93
+ h3. Bundled Rails (3.x)
94
+
95
+
96
+ Rails 3 now uses Bundler and the README for the project explains it better than I could:
97
+
98
+ > "Bundler is a tool that manages gem dependencies for your ruby application. It takes a gem manifest file and is able to fetch, download, and install the gems and all child dependencies specified in this manifest. It can manage any update to the gem manifest file and update the bundle's gems accordingly. It also lets you run any ruby code in context of the bundle's gem environment."
99
+
100
+ Now with Rails 3 we have a Gemfile which defines the basics our application needs to get going:
101
+
102
+ <ruby>
103
+ source 'http://rubygems.org'
104
+
105
+ gem 'rails', '3.0.0.beta1'
106
+
107
+ # Bundle edge Rails instead:
108
+ # gem 'rails', :git => 'git://github.com/rails/rails.git'
109
+
110
+ gem 'sqlite3-ruby', :require => 'sqlite3'
111
+
112
+ # Use unicorn as the web server
113
+ # gem 'unicorn'
114
+
115
+ # Deploy with Capistrano
116
+ # gem 'capistrano'
117
+
118
+ # Bundle the extra gems:
119
+ # gem 'bj'
120
+ # gem 'nokogiri', '1.4.1'
121
+ # gem 'sqlite3-ruby', :require => 'sqlite3'
122
+ # gem 'aws-s3', :require => 'aws/s3'
123
+
124
+ # Bundle gems for certain environments:
125
+ # gem 'rspec', :group => :test
126
+ # group :test do
127
+ # gem 'webrat'
128
+ # end
129
+
130
+ </ruby>
131
+
132
+ Here the only two gems we need are +rails+ and +sqlite3-ruby+, so it seems. This is until you run +bundle pack+. This command freezes all the gems required by your application into _vendor/cache_. The gems installed by default are:
133
+
134
+ * abstract-1.0.0.gem
135
+ * actionmailer-3.0.0.beta1.gem
136
+ * actionpack-3.0.0.beta1.gem
137
+ * activemodel-3.0.0.beta1.gem
138
+ * activerecord-3.0.0.beta1.gem
139
+ * activeresource-3.0.0.beta1.gem
140
+ * activesupport-3.0.0.beta1.gem
141
+ * arel-0.3.3.gem
142
+ * builder-2.1.2.gem
143
+ * bundler-0.9.14.gem
144
+ * erubis-2.6.5.gem
145
+ * i18n-0.3.6.gem
146
+ * mail-2.1.5.3.gem
147
+ * memcache-client-1.8.1.gem
148
+ * mime-types-1.16.gem
149
+ * polyglot-0.3.1.gem
150
+ * rack-1.1.0.gem
151
+ * rack-mount-0.6.1.gem
152
+ * rack-test-0.5.3.gem
153
+ * rails-3.0.0.beta1.gem
154
+ * railties-3.0.0.beta1.gem
155
+ * rake-0.8.7.gem
156
+ * sqlite3-ruby-1.2.5.gem
157
+ * text-format-1.0.0.gem
158
+ * text-hyphen-1.0.0.gem
159
+ * thor-0.13.4.gem
160
+ * treetop-1.4.5.gem
161
+ * tzinfo-0.3.18.gem
162
+
163
+ TODO: Prettify when it becomes more stable.
164
+
165
+ I won't go into what each of these gems are, as that is really something that needs covering on a case-by-case basis. We will however just dig a little under the surface of Bundler.
166
+
167
+ Back in _config/boot.rb_, the first line will try to include _.bundle/environment.rb_, which doesn't exist in a bare-bones Rails application and because this file does not exist Ruby will raise a +LoadError+ which will be rescued and run the following code:
168
+
169
+ <ruby>
170
+ require 'rubygems'
171
+ require 'bundler'
172
+ Bundler.setup
173
+ </ruby>
174
+
175
+ +Bundler.setup+ here will load and parse the +Gemfile+ and add the _lib_ directory of the gems mentioned **and** their dependencies (**and** their dependencies' dependencies, and so on) to the +$LOAD_PATH+.
176
+
177
+ Now we will go down the alternate timeline where we generate a _.bundle/environment.rb_ file using the +bundle lock+ command. This command also creates a _Gemfile.lock_ file which is actually a YAML file loaded by this method in Bundler before it moves on to check for _Gemfile_:
178
+
179
+ <ruby>
180
+ def definition(gemfile = default_gemfile)
181
+ configure
182
+ root = Pathname.new(gemfile).dirname
183
+ lockfile = root.join("Gemfile.lock")
184
+ if lockfile.exist?
185
+ Definition.from_lock(lockfile)
186
+ else
187
+ Definition.from_gemfile(gemfile)
188
+ end
189
+ end
190
+ </ruby>
191
+
192
+
193
+ The _.bundle/environment.rb_ file adds the _lib_ directory of all the gems specified in +Gemfile.lock+ to +$LOAD_PATH+.
194
+
195
+ h3. Requiring Rails
196
+
197
+ After _config/boot.rb_ is loaded, there's this +require+:
198
+
199
+ <ruby>
200
+ require 'rails/commands'
201
+ </ruby>
202
+
203
+ In this file, _railties/lib/rails/commands.rb_, there is a case statement for +ARGV.shift+:
204
+
205
+ <ruby>
206
+ case ARGV.shift
207
+ ...
208
+ when 's', 'server'
209
+ require 'rails/commands/server'
210
+ # Initialize the server first, so environment options are set
211
+ server = Rails::Server.new
212
+ require APP_PATH
213
+ ...
214
+ end
215
+ </ruby>
216
+
217
+ We're running +rails server+ and this means it will make a require out to _rails/commands/server_ (_railties/lib/rails/commands/server.rb_). Firstly, this file makes a couple of requires of its own:
218
+
219
+ <ruby>
220
+ require 'fileutils'
221
+ require 'optparse'
222
+ require 'action_dispatch'
223
+ </ruby>
224
+
225
+ The first two are Ruby core and this guide does not cover what they do, but _action_dispatch_ (_actionpack/lib/action_dispatch.rb_) is important. This file firstly make a require to _active_support_ (_activesupport/lib/active_support.rb_) which defines the +ActiveSupport+ module.
226
+
227
+ h4. +require 'active_support'+
228
+
229
+ _activesupport/lib/active_support.rb_ sets up +module ActiveSupport+:
230
+
231
+ <ruby>
232
+ module ActiveSupport
233
+ class << self
234
+ attr_accessor :load_all_hooks
235
+ def on_load_all(&hook) load_all_hooks << hook end
236
+ def load_all!; load_all_hooks.each { |hook| hook.call } end
237
+ end
238
+ self.load_all_hooks = []
239
+
240
+ on_load_all do
241
+ [Dependencies, Deprecation, Gzip, MessageVerifier, Multibyte, SecureRandom]
242
+ end
243
+ end
244
+ </ruby>
245
+
246
+ 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).
247
+
248
+ 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.
249
+
250
+ 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_:
251
+
252
+
253
+ <ruby>
254
+ require "active_support/inflector/methods"
255
+ require "active_support/lazy_load_hooks"
256
+
257
+ module ActiveSupport
258
+ module Autoload
259
+ def self.extended(base)
260
+ base.extend(LazyLoadHooks)
261
+ end
262
+
263
+ @@autoloads = {}
264
+ @@under_path = nil
265
+ @@at_path = nil
266
+ @@eager_autoload = false
267
+
268
+ def autoload(const_name, path = @@at_path)
269
+ full = [self.name, @@under_path, const_name.to_s, path].compact.join("::")
270
+ location = path || Inflector.underscore(full)
271
+
272
+ if @@eager_autoload
273
+ @@autoloads[const_name] = location
274
+ end
275
+ super const_name, location
276
+ end
277
+
278
+ ...
279
+ end
280
+ end
281
+ </ruby>
282
+
283
+ h4. Lazy Hooks
284
+
285
+ At the top if the +ActiveSupport::Autoload+ module is the +def self.extended+ method:
286
+
287
+ <ruby>
288
+ def self.extended(base)
289
+ base.extend(LazyLoadHooks)
290
+ end
291
+ </ruby>
292
+
293
+ This is called when we extend this module into one of our classes or modules, such is the case later on when we call +extend ActiveSupport::LazyLoadHooks+ not only in the +ActiveSupport+ module, but in all of the Railtie modules (+ActiveRecord+ and so on), as well as in a couple of places.
294
+
295
+ +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:
296
+
297
+ <ruby>
298
+ initializer "active_record.initialize_timezone" do
299
+ ActiveRecord.base_hook do
300
+ self.time_zone_aware_attributes = true
301
+ self.default_timezone = :utc
302
+ end
303
+ end
304
+ </ruby>
305
+
306
+ When the initializer is ran it defines a +base_hook+ for +ActiveRecord+ and will only run it when +run_base_hooks+ is called, which in the case of Active Record, is ran after the entirety of +activerecord/lib/active_record/base.rb+ has been evaluated.
307
+
308
+ h4. +require 'active_support'+ cont'd.
309
+
310
+ This file also uses the method +eager_autoload+ also defined in _active_support/dependencies/autoload.rb_:
311
+
312
+ <ruby>
313
+ def eager_autoload
314
+ old_eager, @@eager_autoload = @@eager_autoload, true
315
+ yield
316
+ ensure
317
+ @@eager_autoload = old_eager
318
+ end
319
+ </ruby>
320
+
321
+ 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_:
322
+
323
+ <ruby>
324
+ require "active_support/dependencies/autoload"
325
+
326
+ module ActiveSupport
327
+ extend ActiveSupport::Autoload
328
+
329
+ # TODO: Narrow this list down
330
+ eager_autoload do
331
+ autoload :BacktraceCleaner
332
+ autoload :Base64
333
+ autoload :BasicObject
334
+ autoload :Benchmarkable
335
+ autoload :BufferedLogger
336
+ autoload :Cache
337
+ autoload :Callbacks
338
+ autoload :Concern
339
+ autoload :Configurable
340
+ autoload :Deprecation
341
+ autoload :Gzip
342
+ autoload :Inflector
343
+ autoload :JSON
344
+ autoload :Memoizable
345
+ autoload :MessageEncryptor
346
+ autoload :MessageVerifier
347
+ autoload :Multibyte
348
+ autoload :OptionMerger
349
+ autoload :OrderedHash
350
+ autoload :OrderedOptions
351
+ autoload :Notifications
352
+ autoload :Rescuable
353
+ autoload :SecureRandom
354
+ autoload :StringInquirer
355
+ autoload :XmlMini
356
+ end
357
+
358
+ autoload :SafeBuffer, "active_support/core_ext/string/output_safety"
359
+ autoload :TestCase
360
+ end
361
+
362
+ autoload :I18n, "active_support/i18n"
363
+ </ruby>
364
+
365
+ 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_.
366
+
367
+ The classes and modules that are not +eager_autoload+'d are automatically loaded as they are references
368
+
369
+ 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.
370
+
371
+ h4. +require 'action_dispatch'+
372
+
373
+ 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:
374
+
375
+ <ruby>
376
+ require 'rack'
377
+ </ruby>
378
+
379
+ 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+.
380
+
381
+ This file then goes on to define the +ActionDispatch+ module and it's related autoloads:
382
+
383
+ <ruby>
384
+ module Rack
385
+ autoload :Test, 'rack/test'
386
+ end
387
+
388
+ module ActionDispatch
389
+ extend ActiveSupport::Autoload
390
+
391
+ autoload_under 'http' do
392
+ autoload :Request
393
+ autoload :Response
394
+ end
395
+
396
+ autoload_under 'middleware' do
397
+ autoload :Callbacks
398
+ autoload :Cascade
399
+ autoload :Cookies
400
+ autoload :Flash
401
+ autoload :Head
402
+ autoload :ParamsParser
403
+ autoload :RemoteIp
404
+ autoload :Rescue
405
+ autoload :ShowExceptions
406
+ autoload :Static
407
+ end
408
+
409
+ autoload :MiddlewareStack, 'action_dispatch/middleware/stack'
410
+ autoload :Routing
411
+
412
+ module Http
413
+ extend ActiveSupport::Autoload
414
+
415
+ autoload :Cache
416
+ autoload :Headers
417
+ autoload :MimeNegotiation
418
+ autoload :Parameters
419
+ autoload :FilterParameters
420
+ autoload :Upload
421
+ autoload :UploadedFile, 'action_dispatch/http/upload'
422
+ autoload :URL
423
+ end
424
+
425
+ module Session
426
+ autoload :AbstractStore, 'action_dispatch/middleware/session/abstract_store'
427
+ autoload :CookieStore, 'action_dispatch/middleware/session/cookie_store'
428
+ autoload :MemCacheStore, 'action_dispatch/middleware/session/mem_cache_store'
429
+ end
430
+
431
+ autoload_under 'testing' do
432
+ autoload :Assertions
433
+ autoload :Integration
434
+ autoload :PerformanceTest
435
+ autoload :TestProcess
436
+ autoload :TestRequest
437
+ autoload :TestResponse
438
+ end
439
+ end
440
+
441
+ autoload :Mime, 'action_dispatch/http/mime_type'
442
+ </ruby>
443
+
444
+ h4. +require "rails/commands/server"+
445
+
446
+ Now that Rails has required Action Dispatch and it has required Rack, Rails can now go about defining the +Rails::Server+ class:
447
+
448
+ <ruby>
449
+ module Rails
450
+ class Server < ::Rack::Server
451
+
452
+ ...
453
+
454
+ def initialize(*)
455
+ super
456
+ set_environment
457
+ end
458
+
459
+ ...
460
+
461
+ def set_environment
462
+ ENV["RAILS_ENV"] ||= options[:environment]
463
+ end
464
+ ...
465
+ end
466
+ end
467
+ </ruby>
468
+
469
+ h4. +require "rails/commands"+
470
+
471
+ 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:
472
+
473
+ <ruby>
474
+ def initialize(options = nil)
475
+ @options = options
476
+ end
477
+ </ruby>
478
+
479
+ The +options+ method like this:
480
+
481
+ <ruby>
482
+ def options
483
+ @options ||= parse_options(ARGV)
484
+ end
485
+ </ruby>
486
+
487
+ The +parse_options+ method like this:
488
+
489
+ <ruby>
490
+ def parse_options(args)
491
+ options = default_options
492
+
493
+ # Don't evaluate CGI ISINDEX parameters.
494
+ # http://hoohoo.ncsa.uiuc.edu/cgi/cl.html
495
+ args.clear if ENV.include?("REQUEST_METHOD")
496
+
497
+ options.merge! opt_parser.parse! args
498
+ options
499
+ end
500
+ </ruby>
501
+
502
+ And +default_options+ like this:
503
+
504
+ <ruby>
505
+ def default_options
506
+ {
507
+ :environment => "development",
508
+ :pid => nil,
509
+ :Port => 9292,
510
+ :Host => "0.0.0.0",
511
+ :AccessLog => [],
512
+ :config => "config.ru"
513
+ }
514
+ end
515
+ </ruby>
516
+
517
+ 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+:
518
+
519
+ <ruby>
520
+ def set_environment
521
+ ENV["RAILS_ENV"] ||= options[:environment]
522
+ end
523
+ </ruby>
524
+
525
+ From the information given we can determine that +ENV["RAILS_ENV"]+ will be set to _development_ if no other environment is specified.
526
+
527
+ Finally, after +Rails::Server.new+ has executed, there is one more require:
528
+
529
+ <ruby>
530
+ require APP_PATH
531
+ </ruby>
532
+
533
+ +APP_PATH+ was previously defined as _config/application.rb_ in the application's root, and so that is where Rails will go next.
534
+
535
+ h4. +require APP_PATH+
536
+
537
+ This file is _config/application.rb_ in your application and makes two requires to begin with:
538
+
539
+ <ruby>
540
+ require File.expand_path('../boot', __FILE__)
541
+ require 'rails/all'
542
+ </ruby>
543
+
544
+ The +../boot+ file it references is +config/boot.rb+, which was loaded earlier in the initialization process and so will not be loaded again.
545
+
546
+ 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:
547
+
548
+ <ruby>
549
+ # Pick the frameworks you want:
550
+ # require "active_record/railtie"
551
+ require "action_controller/railtie"
552
+ require "action_mailer/railtie"
553
+ require "active_resource/railtie"
554
+ require "rails/test_unit/railtie"
555
+ </ruby>
556
+
557
+ For the purposes of this guide, will will assume only:
558
+
559
+ <ruby>
560
+ require 'rails/all'
561
+ </ruby>
562
+
563
+ h4. +require "rails/all"+
564
+
565
+ 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:
566
+
567
+ <ruby>
568
+ require 'rails'
569
+ </ruby>
570
+
571
+ h4. +require 'rails'+
572
+
573
+ 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.
574
+
575
+ <ruby>
576
+ require 'pathname'
577
+
578
+ require 'active_support'
579
+ require 'active_support/core_ext/kernel/reporting'
580
+ require 'active_support/core_ext/logger'
581
+
582
+ require 'rails/application'
583
+ require 'rails/version'
584
+ require 'rails/deprecation'
585
+ require 'rails/log_subscriber'
586
+ require 'rails/ruby_version_check'
587
+
588
+ require 'active_support/railtie'
589
+ require 'action_dispatch/railtie'
590
+ </ruby>
591
+
592
+ +require 'pathname'+ requires the Pathname class which is used for returning a Pathname object for +Rails.root+ so that instead of doing:
593
+
594
+ <ruby>
595
+ File.join(Rails.root, "app/controllers")
596
+ </ruby>
597
+
598
+ You may do:
599
+
600
+ <ruby>
601
+ Rails.root.join("app/controllers")
602
+ </ruby>
603
+
604
+ Although this is not new to Rails 3 (it was available in 2.3.5), it is something worthwhile pointing out.
605
+
606
+ Inside this file there are other helpful helper methods defined, such as +Rails.root+, +Rails.env+, +Rails.logger+ and +Rails.application+.
607
+
608
+ The first require:
609
+
610
+ <ruby>
611
+ require 'active_support'
612
+ </ruby>
613
+
614
+ Is not ran as this was already required by _actionpack/lib/action_dispatch.rb_.
615
+
616
+
617
+ h4. +require 'active_support/core_ext/kernel/reporting'+
618
+
619
+ 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
620
+
621
+ For information on this file see the "Core Extensions" guide. TODO: link to guide.
622
+
623
+ h4. +require 'active_support/core_ext/logger'+
624
+
625
+ For information on this file see the "Core Extensions" guide. TODO: link to guide.
626
+
627
+ h4. +require 'rails/application'+
628
+
629
+ 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.
630
+
631
+ This file requires three important files before +Rails::Application+ is defined: _rails/railties_path.rb_, _rails/plugin.rb_ and _rails/engine.rb_.
632
+
633
+
634
+ h4. +require 'rails/railties_path'+
635
+
636
+ This file serves one purpose:
637
+
638
+ <ruby>
639
+ RAILTIES_PATH = File.expand_path(File.join(File.dirname(__FILE__), '..', '..'))
640
+ </ruby>
641
+
642
+ Helpful, hey? One must wonder why they just didn't define it outright.
643
+
644
+
645
+ h4. +require 'rails/plugin'+
646
+
647
+ Firstly this file requires _rails/engine.rb_, which defines our +Rails::Engine+ class, explained in the very next section.
648
+
649
+ This file defines a class called +Rails::Plugin+ which descends from +Rails::Engine+.
650
+
651
+ This defines the first few initializers for the Rails stack:
652
+
653
+ * load_init_rb
654
+ * sanity_check_railties_collisons
655
+
656
+ These are explained in the Initialization section. TODO: First write initialization section then come back here and link.
657
+ TODO: Expand.
658
+
659
+ h4. +require 'rails/engine'+
660
+
661
+ This file requires _rails/railtie.rb_ which defines +Rails::Railtie+.
662
+
663
+ +Rails::Engine+ defines a couple of further initializers for your application:
664
+
665
+ * set_load_path
666
+ * set_autoload_paths
667
+ * add_routing_paths
668
+ * add_routing_namespaces
669
+ * add_locales
670
+ * add_view_paths
671
+ * add_metals
672
+ * add_generator_templates
673
+ * load_application_initializers
674
+ * load_application_classes
675
+
676
+ These are explained in the Initialization section. TODO: First write initialization section then come back here and link.
677
+
678
+ Also in here we see that a couple of methods are +delegate+'d:
679
+
680
+ <ruby>
681
+ delegate :middleware, :paths, :root, :to => :config
682
+ </ruby>
683
+
684
+ 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.
685
+
686
+ +Rails::Engine+ descends from +Rails::Railtie+.
687
+
688
+ h4. +require 'rails/railtie'+
689
+
690
+ +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.
691
+
692
+ Here there's requires to _rails/initializable.rb_ and and _rails/configurable.rb_.
693
+
694
+ h4. +require 'rails/initializable'+
695
+
696
+ 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.
697
+
698
+ h4. +require 'rails/configuration'+
699
+
700
+ The +Rails::Configuration+ module sets up shared configuration for applications, engines and plugins alike.
701
+
702
+ At the top of this file there are three +require+s:
703
+
704
+ <ruby>
705
+ require 'active_support/ordered_options'
706
+ require 'rails/paths'
707
+ require 'rails/rack'
708
+ </ruby>
709
+
710
+ h4. +require 'active_support/ordered_options'+
711
+
712
+ +ActiveSupport::OrderedOptions+ is a special-purpose +OrderedHash+, used for keeping track of the options specified in the configuration of your application.
713
+
714
+ TODO: expand.
715
+
716
+ h4. +require 'rails/paths'+
717
+
718
+ 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:
719
+
720
+ <ruby>
721
+ def paths
722
+ @paths ||= begin
723
+ paths = Rails::Paths::Root.new(@root)
724
+ paths.app "app", :eager_load => true, :glob => "*"
725
+ paths.app.controllers "app/controllers", :eager_load => true
726
+ paths.app.helpers "app/helpers", :eager_load => true
727
+ paths.app.models "app/models", :eager_load => true
728
+ paths.app.mailers "app/mailers", :eager_load => true
729
+ paths.app.metals "app/metal", :eager_load => true
730
+ paths.app.views "app/views", :eager_load => true
731
+ paths.lib "lib", :load_path => true
732
+ paths.lib.tasks "lib/tasks", :glob => "**/*.rake"
733
+ paths.lib.templates "lib/templates"
734
+ paths.config "config"
735
+ paths.config.initializers "config/initializers", :glob => "**/*.rb"
736
+ paths.config.locales "config/locales", :glob => "*.{rb,yml}"
737
+ paths.config.routes "config/routes.rb"
738
+ paths.public "public"
739
+ paths.public.javascripts "public/javascripts"
740
+ paths.public.stylesheets "public/stylesheets"
741
+ paths
742
+ end
743
+ end
744
+ </ruby>
745
+
746
+ You can then get to these helper methods by calling +YourApp::Application.config.paths+.
747
+
748
+ h4. +require 'rails/rack'+
749
+
750
+ This file sets up some +autoload+'d constants for +Rails::Rack+:
751
+
752
+ <ruby>
753
+ module Rails
754
+ module Rack
755
+ autoload :Debugger, "rails/rack/debugger"
756
+ autoload :Logger, "rails/rack/logger"
757
+ autoload :LogTailer, "rails/rack/log_tailer"
758
+ autoload :Static, "rails/rack/static"
759
+ end
760
+ end
761
+ </ruby>
762
+
763
+ h4. +require 'rails/version'+
764
+
765
+ Now we're back to _rails.rb_. The line after +require 'rails/application'+ in _rails.rb_ is:
766
+
767
+ <ruby>
768
+ require 'rails/version'
769
+ </ruby>
770
+
771
+ 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+.
772
+
773
+ h4. +require 'rails/deprecation'+
774
+
775
+ 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.
776
+
777
+ If you wish to know more about how they're deprecated see the +require 'active_support/deprecation/proxy_wrappers'+ section. TODO: link to section.
778
+
779
+ h4. +require 'rails/log_subscriber'+
780
+
781
+ 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.
782
+
783
+ Each Railtie defines its own class that descends from +Rails::LogSubscriber+ with each defining its own methods for logging individual tasks.
784
+
785
+ h4. +require 'rails/ruby_version_check'+
786
+
787
+ This file ensures that you're running a minimum of 1.8.7. If you're running an older version, it will tell you:
788
+
789
+ <pre>
790
+ Rails requires Ruby version 1.8.7 or later.
791
+ You're running [your Ruby version here]; please upgrade to continue.
792
+ </pre>
793
+
794
+ h4. +require 'activesupport/railtie'+
795
+
796
+ This file declares two Railties, one for ActiveSupport and the other for I18n. In these Railties there's the following initializers defined:
797
+
798
+ * active_support.initialize_whiny_nils
799
+ * active_support.initialize_time_zone
800
+
801
+ * i18n.initialize
802
+
803
+ 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.
804
+
805
+ h4. +require 'action_dispatch/railtie'+
806
+
807
+ This file is explained in the ActionDispatch Railtie Section. TODO: link
808
+
809
+ h4. Return to _rails/all.rb_
810
+
811
+ Now that we've covered the extensive process of what the first line does in this file, lets cover the remainder:
812
+
813
+ <ruby>
814
+ %w(
815
+ active_record
816
+ action_controller
817
+ action_mailer
818
+ active_resource
819
+ rails/test_unit
820
+ ).each do |framework|
821
+ begin
822
+ require "#{framework}/railtie"
823
+ rescue LoadError
824
+ end
825
+ end
826
+ </ruby>
827
+
828
+ As you may be able to tell from the code, this is going through and loading all the Railties for ActiveRecord, ActionController, ActionMailer, ActiveResource. Two other Railties, one for ActiveSupport and one for ActionDispatch were required earlier, but are still covered in this section for continuity reasons. TODO: link.
829
+
830
+ h4. ActiveSupport Railtie
831
+
832
+ From ActiveSupport's README:
833
+
834
+ Active Support is a collection of various utility classes and standard library extensions that were found useful for Rails.
835
+
836
+ TODO: Quotify.
837
+
838
+ h5. +require 'active_support/railtie'+
839
+
840
+
841
+ h4. ActiveRecord Railtie
842
+
843
+ The ActiveRecord Railtie takes care of hooking ActiveRecord into Rails. This depends on ActiveSupport, ActiveModel and Arel. From ActiveRecord's readme:
844
+
845
+ TODO: Quotify.
846
+
847
+ <text>
848
+ 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:
849
+
850
+ "An object that wraps a row in a database table or view, encapsulates
851
+ the database access, and adds domain logic on that data."
852
+
853
+ Active Record's main contribution to the pattern is to relieve the original of two stunting problems:
854
+ lack of associations and inheritance. By adding a simple domain language-like set of macros to describe
855
+ the former and integrating the Single Table Inheritance pattern for the latter, Active Record narrows the
856
+ gap of functionality between the data mapper and active record approach.
857
+ </text>
858
+
859
+ h5. +require "active_record/railtie"+
860
+
861
+ The _activerecord/lib/active_record/railtie.rb_ file defines the Railtie for ActiveRecord.
862
+
863
+ This file first requires ActiveRecord, the _railties/lib/rails.rb_ file which has already been required and so will be ignored, and the ActiveModel Railtie:
864
+
865
+ <ruby>
866
+ require "active_record"
867
+ require "rails"
868
+ require "active_model/railtie"
869
+ </ruby>
870
+
871
+ ActiveModel's Railtie is covered in the next section. TODO: Section.
872
+
873
+ h5. +require "active_record"+
874
+
875
+ TODO: Why are +activesupport_path+ and +activemodel_path+ defined here?
876
+
877
+ The first three requires require ActiveSupport, ActiveModel and ARel in that order:
878
+
879
+ <ruby>
880
+ require 'active_support'
881
+ require 'active_model'
882
+ require 'arel'
883
+ </ruby>
884
+
885
+
886
+ h5. +require "active_support"+
887
+
888
+ This was loaded earlier by _railties/lib/rails.rb_. This line is here as a safeguard for when ActiveRecord is loaded outside the scope of Rails.
889
+
890
+ h5. +require "active_model"+
891
+
892
+ TODO: Again with the +activesupport_path+!
893
+
894
+ Here we see another +require "active_support"+ this is again, a safeguard for when ActiveModel is loaded outside the scope of Rails.
895
+
896
+ This file defines a few +autoload+'d modules for ActiveModel, requires +active_support/i18n+ and adds the default translation file for ActiveModel to +I18n.load_path+.
897
+
898
+ The +require 'active_support/i18n'+ just loads I18n and adds ActiveSupport's default translations file to +I18n.load_path+ too:
899
+
900
+ <ruby>
901
+ require 'i18n'
902
+ I18n.load_path << "#{File.dirname(__FILE__)}/locale/en.yml
903
+ </ruby>
904
+
905
+
906
+ h5. +require "arel"+
907
+
908
+ This file in _arel/lib/arel.rb_ loads a couple of ActiveSupport things first:
909
+
910
+ <ruby>
911
+ require 'active_support/inflector'
912
+ require 'active_support/core_ext/module/delegation'
913
+ require 'active_support/core_ext/class/attribute_accessors'
914
+ </ruby>
915
+
916
+ These files are explained in the "Common Includes" section.
917
+
918
+ h5. +require 'arel'+
919
+
920
+ Back in _arel/lib/arel.rb_, the next two lines require ActiveRecord parts:
921
+
922
+ <ruby>
923
+ require 'active_record'
924
+ require 'active_record/connection_adapters/abstract/quoting'
925
+ </ruby>
926
+
927
+ Because we're currently loading _active_record.rb_, it skips right over it.
928
+
929
+ h5. +require 'active_record/connection_adapters/abstract/quoting'+
930
+
931
+ _activerecord/lib/active_record/connection_adapters/abstract/quoting.rb_ defines methods used for quoting fields and table names in ActiveRecord.
932
+
933
+ TODO: Explain why this is loaded especially.
934
+
935
+ h5. +require 'active_record'+
936
+
937
+ Back the initial require from the _railtie.rb_.
938
+
939
+ The _active_support_ and _active_model_ requires are again just an insurance for if we're loading ActiveRecord 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+.
940
+
941
+ 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.
942
+
943
+ 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 ActiveRecord which are only for if a record is invalid or non-unique.
944
+
945
+ h5. +require 'rails'+
946
+
947
+ 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.
948
+
949
+ h5. +require 'active_model/railtie'+
950
+
951
+ This is covered in the ActiveModel Railtie section. TODO: link there.
952
+
953
+ h5. +require 'action_controller/railtie'+
954
+
955
+ This is covered in the ActionController Railtie section. TODO: link there.
956
+
957
+ h5. The ActiveRecord Railtie
958
+
959
+ Inside the ActiveRecord Railtie the +ActiveRecord::Railtie+ class is defined:
960
+
961
+ <ruby>
962
+ module ActiveRecord
963
+ class Railtie < Rails::Railtie
964
+
965
+ ...
966
+ end
967
+ end
968
+ </ruby>
969
+
970
+ TODO: Explain the logger.
971
+
972
+ 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:
973
+
974
+ * active_record.initialize_timezone
975
+ * active_record.logger
976
+ * active_record.set_configs
977
+ * active_record.initialize_database
978
+ * active_record.log_runtime
979
+ * active_record.initialize_database_middleware
980
+ * active_record.load_observers
981
+ * active_record.set_dispatch_hooks
982
+
983
+ As with the engine initializers, these are explained later.
984
+
985
+
986
+ h4. ActiveModel Railtie
987
+
988
+ This Railtie is +require+'d by ActiveRecord's Railtie.
989
+
990
+ From the ActiveModel readme:
991
+
992
+ <text>
993
+ 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.
994
+
995
+ Active Model is a solution for this problem.
996
+
997
+ Active Model provides a known set of interfaces that your objects can implement to then present a common interface to the Action Pack helpers.
998
+ </text>
999
+
1000
+
1001
+ h5. +require "active_model/railtie"+
1002
+
1003
+ 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.
1004
+
1005
+ <ruby>
1006
+ require "active_model"
1007
+ require "rails"
1008
+ </ruby>
1009
+
1010
+ h5. +require "active_model"+
1011
+
1012
+ ActiveModel depends on ActiveSupport 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 ActiveModel, such as "is not included in the list" and "is reserved".
1013
+
1014
+ h4. Action Controller Railtie
1015
+
1016
+ The ActionController 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.
1017
+
1018
+ h5. +require 'action_controller/railtie'+
1019
+
1020
+ This first makes a couple of requires:
1021
+
1022
+ <ruby>
1023
+ require "action_controller"
1024
+ require "rails"
1025
+ require "action_view/railtie"
1026
+ </ruby>
1027
+
1028
+ 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 ActionView Railtie section.
1029
+
1030
+ h5. +require 'action_controller+
1031
+
1032
+ This file, _actionpack/lib/action_controller.rb_, defines the ActionController 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.
1033
+
1034
+ h5. +require 'abstract_controller'+
1035
+
1036
+ +AbstractController+ provides the functionality of TODO.
1037
+
1038
+ This file is in _actionpack/lib/abstract_controller.rb_ and begins by attempting to add the path to ActiveSupport 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?).
1039
+
1040
+ The next thing in this file four +require+ calls:
1041
+
1042
+ <ruby>
1043
+ require 'active_support/ruby/shim'
1044
+ require 'active_support/dependencies/autoload'
1045
+ require 'active_support/core_ext/module/attr_internal'
1046
+ require 'active_support/core_ext/module/delegation'
1047
+ </ruby>
1048
+
1049
+ After these require calls the +AbstractController+ module is defined with some standard +autoload+'d classes.
1050
+
1051
+
1052
+ h5. +require 'active_support/ruby/shim'+
1053
+
1054
+ This file is explained in the "Common Includes" section beneath.
1055
+
1056
+ h5. +require 'active_support/dependencies/autoload+
1057
+
1058
+ 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.
1059
+
1060
+ h5. +require 'active_support/core_ext/module/attr_internal'+
1061
+
1062
+ 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 ActiveSupport Extensions guide.
1063
+
1064
+ h5. +require 'active_support/core_ext/module/delegation'+
1065
+
1066
+ 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!).
1067
+
1068
+ h5. +require 'action_controller'+
1069
+
1070
+ Back to _actionpack/lib/action_controller.rb_.
1071
+
1072
+ 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.
1073
+
1074
+ This file defines the +ActionController+ module and its autoloaded classes.
1075
+
1076
+ Here we have a new method called +autoload_under+. This was covered in the ActiveRecord 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.
1077
+
1078
+ Another new method we have here is called +autoload_at+:
1079
+
1080
+ <ruby>
1081
+ autoload_at "action_controller/metal/exceptions" do
1082
+ autoload :ActionControllerError
1083
+ autoload :RenderError
1084
+ autoload :RoutingError
1085
+ autoload :MethodNotAllowed
1086
+ autoload :NotImplemented
1087
+ autoload :UnknownController
1088
+ autoload :MissingFile
1089
+ autoload :RenderError
1090
+ autoload :SessionOverflowError
1091
+ autoload :UnknownHttpMethod
1092
+ end
1093
+ </ruby>
1094
+
1095
+ 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 ActiveSupport goes looking for them it will look in that file.
1096
+
1097
+ At the end of this file there are a couple more requires:
1098
+
1099
+ <ruby>
1100
+ # All of these simply register additional autoloads
1101
+ require 'action_view'
1102
+ require 'action_controller/vendor/html-scanner'
1103
+
1104
+ # Common ActiveSupport usage in ActionController
1105
+ require 'active_support/concern'
1106
+ require 'active_support/core_ext/class/attribute_accessors'
1107
+ require 'active_support/core_ext/load_error'
1108
+ require 'active_support/core_ext/module/attr_internal'
1109
+ require 'active_support/core_ext/module/delegation'
1110
+ require 'active_support/core_ext/name_error'
1111
+ require 'active_support/inflector'
1112
+ </ruby>
1113
+
1114
+ h5. +require 'action_view'+
1115
+
1116
+ This is best covered in the ActionView Railtie section, so skip there by TODO: Link / page?
1117
+
1118
+ h5. +require 'action_controller/vendor/html-scanner'+
1119
+
1120
+ TODO: What is the purpose of this? Find out.
1121
+
1122
+ h5. +require 'active_support/concern'+
1123
+
1124
+ TODO: I can kind of understand the purpose of this.. need to see where @_dependencies is used however.
1125
+
1126
+ h5. +require 'active_support/core_ext/class/attribute_accessors'+
1127
+
1128
+ This file defines, as the path implies, attribute accessors for class. These are +cattr_reader+, +cattr_writer+, +cattr_accessor+.
1129
+
1130
+ h5. +require 'active_support/core_ext/load_error'+
1131
+
1132
+ The ActiveSupport Core Extensions (TODO: LINK!) guide has a great coverage of what this file precisely provides.
1133
+
1134
+ h5. +require 'active_support/core_ext/module/attr_internal'+
1135
+
1136
+ This file is explained in the "Core Extension" guide.
1137
+
1138
+ This file was required through the earlier _abstract_controller.rb_ require.
1139
+
1140
+ h5. +require 'active_support/core_ext/module/delegation'+
1141
+
1142
+ This file is explained in the "Common Includes" section.
1143
+
1144
+ This file was required earlier by Arel and so is not required again.
1145
+
1146
+ h5. +require 'active_support/core_ext/name_error'+
1147
+
1148
+ This file includes extensions to the +NameError+ class, providing the +missing_name+ and +missing_name?+ methods. For more information see the ActiveSupport extensions guide.
1149
+
1150
+ h5. +require 'active_support/inflector'+
1151
+
1152
+ This file is explained in the "Common Includes" section.
1153
+
1154
+ This file was earlier required by Arel and so is not required again.
1155
+
1156
+ h5. ActionController Railtie
1157
+
1158
+ So now we come back to the ActionController Railtie with a couple more requires to go before +ActionController::Railtie+ is defined:
1159
+
1160
+ <ruby>
1161
+ require "action_view/railtie"
1162
+ require "active_support/core_ext/class/subclasses"
1163
+ require "active_support/deprecation/proxy_wrappers"
1164
+ require "active_support/deprecation"
1165
+ </ruby>
1166
+
1167
+ As explained previously the +action_view/railtie+ file will be explained in the ActionView Railtie section. TODO: link to it.
1168
+
1169
+ h5. +require 'active_support/core_ext/class/subclasses'+
1170
+
1171
+ For an explanation of this file _activesupport/lib/active_support/core_ext/class/subclasses_, see the ActiveSupport Core Extension guide.
1172
+
1173
+ h5. +require 'active_support/deprecation/proxy_wrappers'+
1174
+
1175
+ 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+.
1176
+
1177
+ 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 ActiveSupport, you too can use the +DeprecationProxy+ class (and it's subclasses) too.
1178
+
1179
+
1180
+ h6. +DeprecationProxy+
1181
+
1182
+ This class is used only in _railties/lib/rails/deprecation.rb_, loaded further on in the initialization process. It's used in this way:
1183
+
1184
+ <ruby>
1185
+ RAILS_ROOT = (Class.new(ActiveSupport::Deprecation::DeprecationProxy) do
1186
+ cattr_accessor :warned
1187
+ self.warned = false
1188
+
1189
+ def target
1190
+ Rails.root
1191
+ end
1192
+
1193
+ def replace(*args)
1194
+ warn(caller, :replace, *args)
1195
+ end
1196
+
1197
+ def warn(callstack, called, args)
1198
+ unless warned
1199
+ ActiveSupport::Deprecation.warn("RAILS_ROOT is deprecated! Use Rails.root instead", callstack)
1200
+ self.warned = true
1201
+ end
1202
+ end
1203
+ end).new
1204
+ </ruby>
1205
+
1206
+ 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.
1207
+
1208
+ h6. +DeprecatedObjectProxy+
1209
+
1210
+ This is used in one place _actionpack/lib/action_controller/railtie.rb_, which you may remember is how we got to the +DeprecationProxy+ section:
1211
+
1212
+ <ruby>
1213
+ ActiveSupport::Deprecation::DeprecatedObjectProxy.new(app.routes, message)
1214
+ </ruby>
1215
+
1216
+ This makes more sense in the wider scope of the initializer:
1217
+
1218
+ <ruby>
1219
+ initializer "action_controller.url_helpers" do |app|
1220
+ ActionController.base_hook do
1221
+ extend ::ActionController::Railtie::UrlHelpers.with(app.routes)
1222
+ end
1223
+
1224
+ message = "ActionController::Routing::Routes is deprecated. " \
1225
+ "Instead, use Rails.application.routes"
1226
+
1227
+ proxy = ActiveSupport::Deprecation::DeprecatedObjectProxy.new(app.routes, message)
1228
+ ActionController::Routing::Routes = proxy
1229
+ end
1230
+ </ruby>
1231
+
1232
+ +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.
1233
+
1234
+
1235
+ h6. +DeprecatedInstanceVariableProxy+
1236
+
1237
+ 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 ActiveSupport.
1238
+
1239
+ h6. +DeprecatedConstantProxy+
1240
+
1241
+ This method is used in a couple of places, _activesupport/lib/active_support/json/encoding.rb_ and _railties/lib/rails/rack.rb_.
1242
+
1243
+ In _encoding.rb_ it's used to define a constant that's now been deprecated:
1244
+
1245
+ <ruby>
1246
+ CircularReferenceError = Deprecation::DeprecatedConstantProxy.new('ActiveSupport::JSON::CircularReferenceError', Encoding::CircularReferenceError)
1247
+ </ruby>
1248
+
1249
+
1250
+ Now when you reference +ActiveSupport::JSON::CircularReferenceError+ you'll receive a warning:
1251
+
1252
+ <text>
1253
+ ActiveSupport::JSON::CircularReferenceError is deprecated! Use Encoding::CircularReferenceError instead.
1254
+ </text>
1255
+
1256
+ h5. +require "active_support/deprecation"+
1257
+
1258
+ This re-opens the +ActiveSupport::Deprecation+ module which was already defined by our deprecation proxies. Before this happens however we have 4 requires:
1259
+
1260
+ <ruby>
1261
+ require 'active_support/deprecation/behaviors'
1262
+ require 'active_support/deprecation/reporting'
1263
+ require 'active_support/deprecation/method_wrappers'
1264
+ require 'active_support/deprecation/proxy_wrappers'
1265
+ </ruby>
1266
+
1267
+ The remainder of this file goes about setting up the +silenced+ and +debug+ accessors:
1268
+
1269
+ <ruby>
1270
+ module ActiveSupport
1271
+ module Deprecation #:nodoc:
1272
+ class << self
1273
+ # The version the deprecated behavior will be removed, by default.
1274
+ attr_accessor :deprecation_horizon
1275
+ end
1276
+ self.deprecation_horizon = '3.0'
1277
+
1278
+ # By default, warnings are not silenced and debugging is off.
1279
+ self.silenced = false
1280
+ self.debug = false
1281
+ end
1282
+ end
1283
+ </ruby>
1284
+
1285
+ h5. +require "active_support/deprecation/behaviors"+
1286
+
1287
+ 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:
1288
+
1289
+ <ruby>
1290
+ # Default warning behaviors per Rails.env. Ignored in production.
1291
+ DEFAULT_BEHAVIORS = {
1292
+ 'test' => Proc.new { |message, callstack|
1293
+ $stderr.puts(message)
1294
+ $stderr.puts callstack.join("\n ") if debug
1295
+ },
1296
+ 'development' => Proc.new { |message, callstack|
1297
+ logger =
1298
+ if defined?(Rails) && Rails.logger
1299
+ Rails.logger
1300
+ else
1301
+ require 'logger'
1302
+ Logger.new($stderr)
1303
+ end
1304
+ logger.warn message
1305
+ logger.debug callstack.join("\n ") if debug
1306
+ }
1307
+ }
1308
+ </ruby>
1309
+
1310
+ 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 ActiveSupport can pass arguments to the +call+ method we call on it when ActiveSupport +warn+.
1311
+
1312
+ h5. +require 'active_support/deprecation/reporting'+
1313
+
1314
+ This file defines further extensions to the +ActiveSupport::Deprecation+ module, including the +warn+ method which is used from ActiveSupport'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.
1315
+
1316
+ This file also defines a +silence+ method on the module also which you can pass a block to temporarily silence errors:
1317
+
1318
+ <ruby>
1319
+ ActiveSupport::Deprecation.silence do
1320
+ puts "YOU CAN FIND ME HERE: #{RAILS_ROOT}"
1321
+ end
1322
+ </ruby>
1323
+
1324
+ TODO: may have to correct this example.
1325
+
1326
+ h5. +require 'active_support/deprecation/method_wrappers'+
1327
+
1328
+ 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:
1329
+
1330
+ <ruby>
1331
+ class Module
1332
+ # Declare that a method has been deprecated.
1333
+ # deprecate :foo
1334
+ # deprecate :bar => 'message'
1335
+ # deprecate :foo, :bar, :baz => 'warning!', :qux => 'gone!'
1336
+ def deprecate(*method_names)
1337
+ ActiveSupport::Deprecation.deprecate_methods(self, *method_names)
1338
+ end
1339
+ end
1340
+ </ruby>
1341
+
1342
+ h5. +require 'action_controller/railtie'+
1343
+
1344
+ Inside +ActionController::Railtie+ there are another two requires:
1345
+
1346
+ <ruby>
1347
+ require "action_controller/railties/log_subscriber"
1348
+ require "action_controller/railties/url_helpers"
1349
+ </ruby>
1350
+
1351
+
1352
+ h5. +require 'action_controller/railties/log_subscriber'+
1353
+
1354
+ +ActionController::Railties::LogSubscriber+ inherits from +Rails::LogSubscriber+ and defines methods for logging such things as action processing and file sending.
1355
+
1356
+ h5. +require 'action_controller/railties/url_helpers'+
1357
+
1358
+ 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.
1359
+
1360
+ h5. ActionController Railtie
1361
+
1362
+ After these requires it deprecates a couple of ex-ActionController methods and points whomever references them to their ActionDispatch equivalents. These methods are +session+, +session=+, +session_store+ and +session_store=+.
1363
+
1364
+ 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:
1365
+
1366
+ * action_controller.logger
1367
+ * action_controller.set_configs
1368
+ * action_controller.initialize_framework_caches
1369
+ * action_controller.set_helpers_path
1370
+ * action_controller.url_helpers
1371
+
1372
+ h4. ActionView Railtie
1373
+
1374
+ The ActionView 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.
1375
+
1376
+ h5. +require 'action_view/railtie'+
1377
+
1378
+ The Railtie is defined in a file called _actionpack/lib/action_view/railtie.rb_ and initially makes a call to +require 'action_view'+.
1379
+
1380
+ h5. +require 'action_view'+
1381
+
1382
+ Here again we have the addition of the path to ActiveSupport to the load path attempted, but because it's already in the load path it will not be added. Similarly, we have two requires:
1383
+
1384
+ <ruby>
1385
+ require 'active_support/ruby/shim'
1386
+ require 'active_support/core_ext/class/attribute_accessors'
1387
+ </ruby>
1388
+
1389
+ 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!
1390
+
1391
+ This file goes on to +require 'action_pack'+ which consists of all this code (comments stripped):
1392
+
1393
+ <ruby>
1394
+ require 'action_pack/version'
1395
+ </ruby>
1396
+
1397
+ the _version_ file contains this code (comments stripped):
1398
+
1399
+ <ruby>
1400
+ module ActionPack #:nodoc:
1401
+ module VERSION #:nodoc:
1402
+ MAJOR = 3
1403
+ MINOR = 0
1404
+ TINY = "0.beta1"
1405
+
1406
+ STRING = [MAJOR, MINOR, TINY].join('.')
1407
+ end
1408
+ end
1409
+ </ruby>
1410
+
1411
+ TODO: Why?!
1412
+
1413
+ This file goes on to define the +ActionView+ module and its +autoload+'d modules and then goes on to make two more requires:
1414
+
1415
+ <ruby>
1416
+ require 'active_support/core_ext/string/output_safety'
1417
+ require 'action_view/base'
1418
+ </ruby>
1419
+
1420
+ h5. +require 'active_support/core_ext/string/output_safety'+
1421
+
1422
+ 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.
1423
+
1424
+ h5. +require 'action_view/base'+
1425
+
1426
+ This file initially makes requires to the following files:
1427
+
1428
+ <ruby>
1429
+ require 'active_support/core_ext/module/attr_internal'
1430
+ require 'active_support/core_ext/module/delegation'
1431
+ require 'active_support/core_ext/class/attribute'
1432
+ </ruby>
1433
+
1434
+ These are explained in their relevant areas inside the "Common Includes" section.
1435
+
1436
+ 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:
1437
+
1438
+ <ruby>
1439
+ include Helpers, Rendering, Partials, Layouts, ::ERB::Util, Context
1440
+ </ruby>
1441
+
1442
+ h5. +ActionView::Helpers+
1443
+
1444
+ 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:
1445
+
1446
+ <ruby>
1447
+ def self.included(base)
1448
+ base.extend(ClassMethods)
1449
+ end
1450
+
1451
+ module ClassMethods
1452
+ include SanitizeHelper::ClassMethods
1453
+ end
1454
+ </ruby>
1455
+
1456
+ 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.
1457
+
1458
+ 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:
1459
+
1460
+ <ruby>
1461
+ benchmark("potentially long running thing") do
1462
+ Post.count
1463
+ end
1464
+ </ruby>
1465
+
1466
+ The "documentation":http://api.rails.info/classes/ActiveSupport/Benchmarkable.html#M000607 is great about explaining what precisely this does. (TODO: replace link with real documentation link when it becomes available.)
1467
+
1468
+ This module is also included into Active Record and +AbstractController+, meaning you can also use the +benchmark+ method in these methods.
1469
+
1470
+ 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.
1471
+
1472
+ h5. +ActionView::Rendering+
1473
+
1474
+ 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.
1475
+
1476
+ h5. +ActionView::Partials+
1477
+
1478
+ This module, from _actionpack/lib/action_view/render/partials.rb_, defines +ActionView::Partials::PartialRenderer+ which you can probably guess is used for rendering partials.
1479
+
1480
+ h5. +ActionView::Layouts+
1481
+
1482
+ This module, from _actionpack/lib/action_view/render/layouts.rb_, defines +ActionView::Layouts+ which defines methods such as +find_layout+ for locating layouts.
1483
+
1484
+ h5. +ERB::Util+
1485
+
1486
+ 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.
1487
+
1488
+ h5. +ActionView::Context+
1489
+
1490
+ TODO: Not entirely sure what this is all about. Something about the context of view rendering... can't work it out.
1491
+
1492
+ h5. ActionView Railtie
1493
+
1494
+ 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.
1495
+
1496
+ Next, the Railtie itself is defined:
1497
+
1498
+
1499
+ <ruby>
1500
+ module ActionView
1501
+ class Railtie < Rails::Railtie
1502
+ railtie_name :action_view
1503
+
1504
+ require "action_view/railties/log_subscriber"
1505
+ log_subscriber ActionView::Railties::LogSubscriber.new
1506
+
1507
+ initializer "action_view.cache_asset_timestamps" do |app|
1508
+ unless app.config.cache_classes
1509
+ ActionView.base_hook do
1510
+ ActionView::Helpers::AssetTagHelper.cache_asset_timestamps = false
1511
+ end
1512
+ end
1513
+ end
1514
+ end
1515
+ end
1516
+ </ruby>
1517
+
1518
+ 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.
1519
+
1520
+ The sole initializer defined here, _action_view.cache_asset_timestamps_ 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.
1521
+
1522
+ h4. ActionMailer Railtie
1523
+
1524
+ The ActionMailer Railtie is responsible for including all the emailing functionality into Rails by way of the ActionMailer gem itself. ActionMailer is:
1525
+
1526
+ Action Mailer is a framework for designing email-service layers. These layers
1527
+ are used to consolidate code for sending out forgotten passwords, welcome
1528
+ wishes on signup, invoices for billing, and any other use case that requires
1529
+ a written notification to either a person or another system.
1530
+
1531
+ Action Mailer is in essence a wrapper around Action Controller and the
1532
+ Mail gem. It provides a way to make emails using templates in the same
1533
+ way that Action Controller renders views using templates.
1534
+
1535
+ TODO: Quotify.
1536
+
1537
+ h5. +require 'action_mailer/railtie'+
1538
+
1539
+ This file first makes two requires:
1540
+
1541
+ <ruby>
1542
+ require "action_mailer"
1543
+ require "rails"
1544
+ </ruby>
1545
+
1546
+ The requires in +action_mailer+ are already loaded or are core extensions:
1547
+
1548
+ <ruby>
1549
+ require 'abstract_controller'
1550
+ require 'action_view'
1551
+
1552
+ # Common ActiveSupport usage in ActionMailer
1553
+ require 'active_support/core_ext/class'
1554
+ require 'active_support/core_ext/object/blank'
1555
+ require 'active_support/core_ext/array/uniq_by'
1556
+ require 'active_support/core_ext/module/attr_internal'
1557
+ require 'active_support/core_ext/module/delegation'
1558
+ require 'active_support/core_ext/string/inflections'
1559
+ require 'active_support/lazy_load_hooks'
1560
+ </ruby>
1561
+
1562
+ _abstract_controller_ is covered in the "ActionController Railtie" section. TODO: Cover AbstractController there and link to it.
1563
+ _action_view_ was required by the ActionView Railtie and will not be required again.
1564
+
1565
+ For the core extensions you may reference the "Core Extensions" guide. TODO: Link to guide.
1566
+
1567
+ _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.
1568
+
1569
+ The +require "rails"+ is referencing the _railties/lib/rails.rb_ file which was included back in TODO: link to section.
1570
+
1571
+ _actionmailer/lib/action_mailer.rb_ then goes on to define the +ActionMailer+ module:
1572
+
1573
+ <ruby>
1574
+ module ActionMailer
1575
+ extend ::ActiveSupport::Autoload
1576
+
1577
+ autoload :AdvAttrAccessor
1578
+ autoload :Collector
1579
+ autoload :Base
1580
+ autoload :DeliveryMethods
1581
+ autoload :DeprecatedApi
1582
+ autoload :MailHelper
1583
+ autoload :OldApi
1584
+ autoload :Quoting
1585
+ autoload :TestCase
1586
+ autoload :TestHelper
1587
+ end
1588
+ </ruby>
1589
+
1590
+ And a +Text+ module too:
1591
+
1592
+ <ruby>
1593
+ module Text
1594
+ extend ActiveSupport::Autoload
1595
+
1596
+ autoload :Format, 'text/format'
1597
+ end
1598
+ </ruby>
1599
+
1600
+ which is used by the +ActionMailer::MailerHelper+ method +block_format+:
1601
+
1602
+ <ruby>
1603
+ def block_format(text)
1604
+ formatted = text.split(/\n\r\n/).collect { |paragraph|
1605
+ Text::Format.new(
1606
+ :columns => 72, :first_indent => 2, :body_indent => 2, :text => paragraph
1607
+ ).format
1608
+ }.join("\n")
1609
+
1610
+ # Make list points stand on their own line
1611
+ formatted.gsub!(/[ ]*([*]+) ([^*]*)/) { |s| " #{$1} #{$2.strip}\n" }
1612
+ formatted.gsub!(/[ ]*([#]+) ([^#]*)/) { |s| " #{$1} #{$2.strip}\n" }
1613
+
1614
+ formatted
1615
+ end
1616
+ </ruby>
1617
+
1618
+ h5. ActionMailer Railtie
1619
+
1620
+ 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+.
1621
+
1622
+ The initializers defined in this Railtie are:
1623
+
1624
+ * action_mailer.url_for
1625
+ * action_mailer.logger
1626
+ * action_mailer.set_configs
1627
+
1628
+ These are covered later on the Initialization section. TODO: first write then link to Initialization section.
1629
+
1630
+ h4. ActiveResource Railtie
1631
+
1632
+ The ActiveResource Railtie is responsible for creating an interface into remote sites that offer a REST API. The ActiveResource Railtie depends on ActiveSupport and ActiveModel.
1633
+
1634
+ h5. +require 'active_resource/railtie'+
1635
+
1636
+ This file defines the ActiveResource Railtie:
1637
+
1638
+ <ruby>
1639
+ require "active_resource"
1640
+ require "rails"
1641
+
1642
+ module ActiveResource
1643
+ class Railtie < Rails::Railtie
1644
+ railtie_name :active_resource
1645
+
1646
+ require "active_resource/railties/log_subscriber"
1647
+ log_subscriber ActiveResource::Railties::LogSubscriber.new
1648
+
1649
+ initializer "active_resource.set_configs" do |app|
1650
+ app.config.active_resource.each do |k,v|
1651
+ ActiveResource::Base.send "#{k}=", v
1652
+ end
1653
+ end
1654
+ end
1655
+ end
1656
+ </ruby>
1657
+
1658
+ The +require 'rails'+ has already been done back in TODO: link to section.
1659
+
1660
+ h5. +require 'active_resource'+
1661
+
1662
+ This file, _activeresource/lib/active_resource.rb_, defines the +ActiveResource+ module, first off this will add the path to ActiveSupport and ActiveModel 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_)
1663
+
1664
+ <ruby>
1665
+ activesupport_path = File.expand_path('../../../activesupport/lib', __FILE__)
1666
+ $:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.include?(activesupport_path)
1667
+
1668
+ activemodel_path = File.expand_path('../../../activemodel/lib', __FILE__)
1669
+ $:.unshift(activemodel_path) if File.directory?(activemodel_path) && !$:.include?(activemodel_path)
1670
+
1671
+ require 'active_support'
1672
+ require 'active_model'
1673
+
1674
+ module ActiveResource
1675
+ extend ActiveSupport::Autoload
1676
+
1677
+ autoload :Base
1678
+ autoload :Connection
1679
+ autoload :CustomMethods
1680
+ autoload :Formats
1681
+ autoload :HttpMock
1682
+ autoload :Observing
1683
+ autoload :Schema
1684
+ autoload :Validations
1685
+ end
1686
+ </ruby>
1687
+
1688
+ h5. ActiveResource Railtie
1689
+
1690
+ The Railtie itself is fairly short as ActiveResource is the smallest component of Rails.
1691
+
1692
+ <ruby>
1693
+ module ActiveResource
1694
+ class Railtie < Rails::Railtie
1695
+ railtie_name :active_resource
1696
+
1697
+ require "active_resource/railties/log_subscriber"
1698
+ log_subscriber ActiveResource::Railties::LogSubscriber.new
1699
+
1700
+ initializer "active_resource.set_configs" do |app|
1701
+ app.config.active_resource.each do |k,v|
1702
+ ActiveResource::Base.send "#{k}=", v
1703
+ end
1704
+ end
1705
+ end
1706
+ end
1707
+ </ruby>
1708
+
1709
+ 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.
1710
+
1711
+ There is only one initializer defined here: +set_configs+. This is covered later in the Initialization section.
1712
+
1713
+
1714
+ h4. ActionDispatch Railtie
1715
+
1716
+ ActionDispatch handles all dispatch work for Rails. It interfaces with ActionController 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!
1717
+
1718
+ The ActionDispatch Railtie was previously required when we called +require 'rails'+, but we will cover the Railtie here too.
1719
+
1720
+ ActionDispatch depends on ActiveSupport.
1721
+
1722
+ h5. +require 'action_dispatch/railtie'+
1723
+
1724
+ This file defines the ActionDispatch Railtie:
1725
+
1726
+ <ruby>
1727
+ require "action_dispatch"
1728
+ require "rails"
1729
+
1730
+ module ActionDispatch
1731
+ class Railtie < Rails::Railtie
1732
+ railtie_name :action_dispatch
1733
+
1734
+ config.action_dispatch.x_sendfile_header = "X-Sendfile"
1735
+ config.action_dispatch.ip_spoofing_check = true
1736
+
1737
+ # Prepare dispatcher callbacks and run 'prepare' callbacks
1738
+ initializer "action_dispatch.prepare_dispatcher" do |app|
1739
+ # TODO: This used to say unless defined?(Dispatcher). Find out why and fix.
1740
+ require 'rails/dispatcher'
1741
+ ActionDispatch::Callbacks.to_prepare { app.routes_reloader.reload_if_changed }
1742
+ end
1743
+ end
1744
+ end
1745
+ </ruby>
1746
+
1747
+ The +require 'rails'+ has already been done back in TODO: link to section.
1748
+
1749
+
1750
+
1751
+
1752
+ h5. +require 'action_dispatch'+
1753
+
1754
+ This file was already loaded earlier in the initialization process. TODO: link to it.
1755
+
1756
+ h5. ActionDispatch Railtie
1757
+
1758
+ The ActionDispatch Railtie is almost as short as the ActiveResource Railtie:
1759
+
1760
+ <ruby>
1761
+ require "action_dispatch"
1762
+ require "rails"
1763
+
1764
+ module ActionDispatch
1765
+ class Railtie < Rails::Railtie
1766
+ railtie_name :action_dispatch
1767
+
1768
+ config.action_dispatch.x_sendfile_header = "X-Sendfile"
1769
+ config.action_dispatch.ip_spoofing_check = true
1770
+
1771
+ # Prepare dispatcher callbacks and run 'prepare' callbacks
1772
+ initializer "action_dispatch.prepare_dispatcher" do |app|
1773
+ # TODO: This used to say unless defined?(Dispatcher). Find out why and fix.
1774
+ require 'rails/dispatcher'
1775
+ ActionDispatch::Callbacks.to_prepare { app.routes_reloader.reload_if_changed }
1776
+ end
1777
+ end
1778
+ end
1779
+ </ruby>
1780
+
1781
+ 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_.
1782
+
1783
+ This Railtie does not define a +log_subscriber+ and only defines one initializer: +prepare_dispatcher+.
1784
+
1785
+ h3. Return to _config/application.rb_
1786
+
1787
+ Now that Rails has finished loading all the Railties by way of +require 'rails/all'+ Rails can now move on to the next line:
1788
+
1789
+ <ruby>
1790
+ Bundler.require :default, Rails.env
1791
+ </ruby>
1792
+
1793
+ 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_.
1794
+
1795
+ Bundler was +require+'d back in _config/boot.rb_ and now we'll dive into the internals of Bundler to determine precisely what this line accomplishes.
1796
+
1797
+ h4. +Bundler.require+
1798
+
1799
+ +Bundler.require+ is defined in _lib/bundler.rb_:
1800
+
1801
+ <ruby>
1802
+ def require(*groups)
1803
+ gemfile = default_gemfile
1804
+ load(gemfile).require(*groups)
1805
+ end
1806
+ </ruby>
1807
+
1808
+ The +groups+ variable here would be a two-element array of the arguments passed to +Bundler.require+. In this case we're going to assume, +Rails.env+ is +"development"+.
1809
+
1810
+ h4. Locating the Gemfile
1811
+
1812
+ +default_gemfile+ is defined in _lib/bundler.rb_ and makes a call out to the +SharedHelpers+ module:
1813
+
1814
+ <ruby>
1815
+ def default_gemfile
1816
+ SharedHelpers.default_gemfile
1817
+ end
1818
+ </ruby>
1819
+
1820
+ +SharedHelpers+ defines +default_gemfile+ like this:
1821
+
1822
+ <ruby>
1823
+ def default_gemfile
1824
+ gemfile = find_gemfile
1825
+ gemfile or raise GemfileNotFound, "The default Gemfile was not found"
1826
+ Pathname.new(gemfile)
1827
+ end
1828
+ </ruby>
1829
+
1830
+ +find_gemfile+ is defined like this:
1831
+
1832
+ <ruby>
1833
+ def find_gemfile
1834
+ return ENV['BUNDLE_GEMFILE'] if ENV['BUNDLE_GEMFILE']
1835
+
1836
+ previous = nil
1837
+ current = File.expand_path(Dir.pwd)
1838
+
1839
+ until !File.directory?(current) || current == previous
1840
+ filename = File.join(current, 'Gemfile')
1841
+ return filename if File.file?(filename)
1842
+ current, previous = File.expand_path("..", current), current
1843
+ end
1844
+ end
1845
+ </ruby>
1846
+
1847
+ The first line of course means if you define the environment variable +BUNDLE_GEMFILE+ this is the name of the file that will be used and returned. If not, then Bundler will look for a file called _Gemfile_ in the current directory and if it can find it then it will return the filename. If it cannot, it will recurse up the directory structure until it does. Once the file is found a +Pathname+ is made from the expanded path to _Gemfile_.
1848
+
1849
+ If the file cannot be found at all then +GemfileNotFound+ will be raised back in +default_gemfile+.
1850
+
1851
+ h4. Loading the Gemfile
1852
+
1853
+ Now that Bundler has determined what the _Gemfile_ is, it goes about loading it:
1854
+
1855
+ <ruby>
1856
+ def require(*groups)
1857
+ gemfile = default_gemfile
1858
+ load(gemfile).require(*groups)
1859
+ end
1860
+ </ruby>
1861
+
1862
+ +load+ is defined like this in _lib/bundler.rb_:
1863
+
1864
+ <ruby>
1865
+ def load(gemfile = default_gemfile)
1866
+ root = Pathname.new(gemfile).dirname
1867
+ Runtime.new root, definition(gemfile)
1868
+ end
1869
+ </ruby>
1870
+
1871
+ The next method to be called here would be +definition+ and it is defined like this:
1872
+
1873
+ <ruby>
1874
+ def definition(gemfile = default_gemfile)
1875
+ configure
1876
+ root = Pathname.new(gemfile).dirname
1877
+ lockfile = root.join("Gemfile.lock")
1878
+ if lockfile.exist?
1879
+ Definition.from_lock(lockfile)
1880
+ else
1881
+ Definition.from_gemfile(gemfile)
1882
+ end
1883
+ end
1884
+ </ruby>
1885
+
1886
+ +configure+ is responsible for setting up the path to gem home and gem path:
1887
+
1888
+ <ruby>
1889
+ def configure
1890
+ @configured ||= begin
1891
+ configure_gem_home_and_path
1892
+ true
1893
+ end
1894
+ end
1895
+ </ruby>
1896
+
1897
+ +configure_gem_home_and_path+ defined like this:
1898
+
1899
+ <ruby>
1900
+ def configure_gem_home_and_path
1901
+ if settings[:disable_shared_gems]
1902
+ ENV['GEM_HOME'] = File.expand_path(bundle_path, root)
1903
+ ENV['GEM_PATH'] = ''
1904
+ else
1905
+ gem_home, gem_path = Gem.dir, Gem.path
1906
+ ENV["GEM_PATH"] = [gem_home, gem_path].flatten.compact.join(File::PATH_SEPARATOR)
1907
+ ENV["GEM_HOME"] = bundle_path.to_s
1908
+ end
1909
+
1910
+ Gem.clear_paths
1911
+ end
1912
+ </ruby>
1913
+
1914
+ We do not have +settings[:disabled_shared_gems]+ set to true so this will execute the code under the +else+. The +ENV["GEM_PATH"]+ will resemble +/usr/local/lib/ruby/gems/1.9.1:/home/you/.gem/ruby/1.9.1+
1915
+
1916
+ And +ENV["GEM_HOME"]+ will be the path to the gems installed into your home directory by Bundler, something resembling +/home/you/.bundle/ruby/1.9.1+.
1917
+
1918
+ After +configure_gem_home_and_path+ is done the +definition+ method goes about creating a +Definition+ from either +Gemfile.lock+ if it exists, or the +gemfile+ previously located. +Gemfile.lock+ only exists if +bundle lock+ has been ran and so far it has not.
1919
+
1920
+ +Definition.from_gemfile+ is defined in _lib/bundler/definition.rb_:
1921
+
1922
+ <ruby>
1923
+ def self.from_gemfile(gemfile)
1924
+ gemfile = Pathname.new(gemfile).expand_path
1925
+
1926
+ unless gemfile.file?
1927
+ raise GemfileNotFound, "#{gemfile} not found"
1928
+ end
1929
+
1930
+ Dsl.evaluate(gemfile)
1931
+ end
1932
+ </ruby>
1933
+
1934
+ Now that the +gemfile+ is located +Dsl.evaluate+ goes about loading it. The code for this can be found in _lib/bundler/dsl.rb_:
1935
+
1936
+ <ruby>
1937
+ def self.evaluate(gemfile)
1938
+ builder = new
1939
+ builder.instance_eval(File.read(gemfile.to_s), gemfile.to_s, 1)
1940
+ builder.to_definition
1941
+ end
1942
+ </ruby>
1943
+
1944
+ +new+ here will, of course, call +initialize+ which sets up a couple of variables:
1945
+
1946
+ <ruby>
1947
+ def initialize
1948
+ @source = nil
1949
+ @sources = []
1950
+ @dependencies = []
1951
+ @group = nil
1952
+ end
1953
+ </ruby>
1954
+
1955
+ When Bundler calls +instance_eval+ on the new +Bundler::Dsl+ object it evaluates the content of the +gemfile+ file within the context of this instance. The Gemfile for a default Rails 3 project with all the comments stripped out looks like this:
1956
+
1957
+ <ruby>
1958
+ source 'http://rubygems.org'
1959
+
1960
+ gem 'rails', '3.0.0.beta1'
1961
+
1962
+ # Bundle edge Rails instead:
1963
+ # gem 'rails', :git => 'git://github.com/rails/rails.git'
1964
+
1965
+ gem 'sqlite3-ruby', :require => 'sqlite3'
1966
+ </ruby>
1967
+
1968
+ When Bundler loads this file it firstly calls the +source+ method on the +Bundler::Dsl+ object:
1969
+
1970
+ <ruby>
1971
+ def source(source, options = {})
1972
+ @source = case source
1973
+ when :gemcutter, :rubygems, :rubyforge then Source::Rubygems.new("uri" => "http://gemcutter.org")
1974
+ when String then Source::Rubygems.new("uri" => source)
1975
+ else source
1976
+ end
1977
+
1978
+ options[:prepend] ? @sources.unshift(@source) : @sources << @source
1979
+
1980
+ yield if block_given?
1981
+ @source
1982
+ ensure
1983
+ @source = nil
1984
+ end
1985
+ </ruby>
1986
+
1987
+ TODO: Perhaps make this a side-note. However you do that.
1988
+
1989
+ The interesting thing to note about this method is that it takes a block, so you may do:
1990
+
1991
+ <ruby>
1992
+ source 'http://someothergemhost.com' do
1993
+ gem 'your_favourite_gem'
1994
+ end
1995
+ </ruby>
1996
+
1997
+ if you wish to install _your_favourite_gem_ from _http://someothergemhost.com_.
1998
+
1999
+ In this instance however a block is not specified so this sets up the +@source+ instance variable to be +'http://rubygems.org'+.
2000
+
2001
+ The next method that is called is +gem+:
2002
+
2003
+ <ruby>
2004
+ def gem(name, *args)
2005
+ options = Hash === args.last ? args.pop : {}
2006
+ version = args.last || ">= 0"
2007
+ if options[:group]
2008
+ options[:group] = options[:group].to_sym
2009
+ end
2010
+
2011
+ _deprecated_options(options)
2012
+ _normalize_options(name, version, options)
2013
+
2014
+ @dependencies << Dependency.new(name, version, options)
2015
+ end
2016
+ </ruby>
2017
+
2018
+ This sets up a couple of important things initially. If you specify a gem like the following:
2019
+
2020
+ <ruby>
2021
+ gem 'rails', "2.3.4"
2022
+ </ruby>
2023
+
2024
+ This sets +options+ to be an empty hash, but +version+ to be +"2.3.4"+. TODO: How does one pass options and versions at the same time?
2025
+
2026
+ In the Gemfile for a default Rails project, the first +gem+ line is:
2027
+
2028
+ <ruby>
2029
+ gem 'rails', '3.0.0.beta2'
2030
+ </ruby>
2031
+
2032
+ TODO: change version number.
2033
+
2034
+ This line will check that +options+ contains no deprecated options by using the +_deprecated_options+ method, but the +options+ hash is empty. This is of course until +_normalize_options+ has its way:
2035
+
2036
+ <ruby>
2037
+ def _normalize_options(name, version, opts)
2038
+ _normalize_hash(opts)
2039
+
2040
+ group = opts.delete("group") || @group
2041
+
2042
+ # Normalize git and path options
2043
+ ["git", "path"].each do |type|
2044
+ if param = opts[type]
2045
+ options = _version?(version) ? opts.merge("name" => name, "version" => version) : opts.dup
2046
+ source = send(type, param, options, :prepend => true)
2047
+ opts["source"] = source
2048
+ end
2049
+ end
2050
+
2051
+ opts["source"] ||= @source
2052
+
2053
+ opts["group"] = group
2054
+ end
2055
+ </ruby>
2056
+
2057
+ +_normalize_hash+ will convert all the keys in the +opts+ hash to strings. There is neither a +git+ or a +path+ key in the +opts+ hash so the next couple of lines are ignored, then the +source+ and +group+ keys are set up.
2058
+
2059
+ TODO: Maybe it is best to cover what would happen in the case these lines did exist?
2060
+
2061
+ The next line goes about defining a dependency for this gem:
2062
+
2063
+ <ruby>
2064
+ @dependencies << Dependency.new(name, version, options)
2065
+ </ruby>
2066
+
2067
+ This class is defined like this:
2068
+
2069
+ <ruby>
2070
+ module Bundler
2071
+ class Dependency < Gem::Dependency
2072
+ attr_reader :autorequire
2073
+ attr_reader :groups
2074
+
2075
+ def initialize(name, version, options = {}, &blk)
2076
+ super(name, version)
2077
+
2078
+ @autorequire = nil
2079
+ @groups = Array(options["group"] || :default).map { |g| g.to_sym }
2080
+ @source = options["source"]
2081
+
2082
+ if options.key?('require')
2083
+ @autorequire = Array(options['require'] || [])
2084
+ end
2085
+ end
2086
+ end
2087
+ end
2088
+ </ruby>
2089
+
2090
+ The +initialize+ method in +Gem::Dependency+ is defined:
2091
+
2092
+ <ruby>
2093
+ def initialize(name, version_requirements, type=:runtime)
2094
+ @name = name
2095
+ unless TYPES.include? type
2096
+ raise ArgumentError, "Valid types are #{TYPES.inspect}, not #{@type.inspect}"
2097
+ end
2098
+ @type = type
2099
+ @version_requirements = Gem::Requirement.create version_requirements
2100
+ @version_requirement = nil # Avoid warnings.
2101
+ end
2102
+ </ruby>
2103
+
2104
+ The +version_requirements+ that was passed in here will be inspected by +Gem::Requirement.create+ and return, for our +3.0.0beta2+ version string a +Gem::Requirement+ object:
2105
+
2106
+ <ruby>
2107
+ #<Gem::Requirement:0x101dd8c20 @requirements=[["=", #<Gem::Version "3.0.0beta2">]]>
2108
+ </ruby>
2109
+
2110
+ Going back to +Bundler::Dependency+, the next line simply sets +@autorequire+ to +nil+ and the next line is a little more interesting:
2111
+
2112
+ <ruby>
2113
+ @autorequire = nil
2114
+ @groups = Array(options["group"] || :default).map { |g| g.to_sym }
2115
+ </ruby>
2116
+
2117
+ Here, bundler sets the +groups+ variable to be whatever +group+ we've set for this gem and also demonstrates through code that the +group+ option allows for multiple groups, so in the _Gemfile_ we can specify the same gem for multiple groups:
2118
+
2119
+ <ruby>
2120
+ group :test, :cucumber do
2121
+ gem 'faker'
2122
+ end
2123
+ </ruby>
2124
+
2125
+ The final lines in +initialize+ work on the +require+ option which is not passed:
2126
+
2127
+ <ruby>
2128
+ if options.key?('require')
2129
+ @autorequire = Array(options['require'] || [])
2130
+ end
2131
+ </ruby>
2132
+
2133
+ If it were to be used in the _Gemfile_, it would look like this:
2134
+
2135
+ <ruby>
2136
+ gem 'thinking-sphinx', :require => "thinking_sphinx"
2137
+ </ruby>
2138
+
2139
+ So far, this is what simply loading the _Gemfile_ does.
2140
+
2141
+ h3. Bring forth the gems
2142
+
2143
+ Now that the _Gemfile_ has finished being parsed, the next line is:
2144
+
2145
+ <ruby>
2146
+ builder.to_definition
2147
+ </ruby>
2148
+
2149
+ This method is defined in _lib/bundler/dsl.rb_ and does this:
2150
+
2151
+ <ruby>
2152
+ def to_definition
2153
+ Definition.new(@dependencies, @sources)
2154
+ end
2155
+ </ruby>
2156
+
2157
+ The +Bundler::Definition#initialize+ method is this:
2158
+
2159
+ <ruby>
2160
+ def initialize(dependencies, sources)
2161
+ @dependencies = dependencies
2162
+ @sources = sources
2163
+ end
2164
+ </ruby>
2165
+
2166
+ Now Bundler has a +Bundler::Definition+ object to be passed back to the +load+ method from _lib/bundler.rb_:
2167
+
2168
+ <ruby>
2169
+ def load(gemfile = default_gemfile)
2170
+ root = Pathname.new(gemfile).dirname
2171
+ Runtime.new root, definition(gemfile)
2172
+ end
2173
+ </ruby>
2174
+
2175
+ The +Bundler::Runtime+ class inherits from +Bundler::Environment+ and the reason this is pointed out is because +super+ is used in the +initialize+ method in +Bundler::Runtime+:
2176
+
2177
+ <ruby>
2178
+ super
2179
+ if locked?
2180
+ write_rb_lock
2181
+ end
2182
+ </ruby>
2183
+
2184
+ Thankfully, the +Bundler::Environment#initialize+ method is nothing too complex:
2185
+
2186
+ <ruby>
2187
+ def initialize(root, definition)
2188
+ @root = root
2189
+ @definition = definition
2190
+ end
2191
+ </ruby>
2192
+
2193
+ The +locked?+ method checks if the _Gemfile.lock_ or _.bundler/environment.rb_ files exist:
2194
+
2195
+ <ruby>
2196
+ def locked?
2197
+ File.exist?("#{root}/Gemfile.lock") || File.exist?("#{root}/.bundle/environment.rb")
2198
+ end
2199
+ </ruby>
2200
+
2201
+ And if they do will call +write_rb_lock+:
2202
+
2203
+ <ruby>
2204
+ def write_rb_lock
2205
+ shared_helpers = File.read(File.expand_path("../shared_helpers.rb", __FILE__))
2206
+ template = File.read(File.expand_path("../templates/environment.erb", __FILE__))
2207
+ erb = ERB.new(template, nil, '-')
2208
+ FileUtils.mkdir_p(rb_lock_file.dirname)
2209
+ File.open(rb_lock_file, 'w') do |f|
2210
+ f.puts erb.result(binding)
2211
+ end
2212
+ end
2213
+ </ruby>
2214
+
2215
+ This will write out to _.bundler/environment.rb_ the state of the current environment.
2216
+
2217
+ Now a quick refresher. Bundler is still evaulating the code for the +require+ in _lib/bundler.rb_, and the +groups+ variable here is an +Array+ containing two elements: +:default+ and the current Rails environment: +development+:
2218
+
2219
+ <ruby>
2220
+ def require(*groups)
2221
+ gemfile = default_gemfile
2222
+ load(gemfile).require(*groups)
2223
+ end
2224
+ </ruby>
2225
+
2226
+ The second +require+ method here:
2227
+
2228
+ <ruby>
2229
+ load(gemfile).require(*groups)
2230
+ </ruby>
2231
+
2232
+ Is defined on _bundler/runtime.rb_:
2233
+
2234
+ <ruby>
2235
+ def require(*groups)
2236
+ groups.map! { |g| g.to_sym }
2237
+ groups = [:default] if groups.empty?
2238
+ autorequires = autorequires_for_groups(*groups)
2239
+
2240
+ groups.each do |group|
2241
+ (autorequires[group] || [[]]).each do |path, explicit|
2242
+ if explicit
2243
+ Kernel.require(path)
2244
+ else
2245
+ begin
2246
+ Kernel.require(path)
2247
+ rescue LoadError
2248
+ end
2249
+ end
2250
+ end
2251
+ end
2252
+ end
2253
+ </ruby>
2254
+
2255
+ This method does TODO: Describe what magic this undertakes.
2256
+
2257
+ The first method to be called here is +autorequires_for_groups+:
2258
+
2259
+ <ruby>
2260
+ def autorequires_for_groups(*groups)
2261
+ groups.map! { |g| g.to_sym }
2262
+ autorequires = Hash.new { |h,k| h[k] = [] }
2263
+
2264
+ ordered_deps = []
2265
+ specs_for(*groups).each do |g|
2266
+ dep = @definition.dependencies.find{|d| d.name == g.name }
2267
+ ordered_deps << dep if dep && !ordered_deps.include?(dep)
2268
+ end
2269
+ </ruby>
2270
+
2271
+
2272
+ h3. Firing it up!
2273
+
2274
+ 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+:
2275
+
2276
+ <ruby>
2277
+ when 's', 'server'
2278
+ require 'rails/commands/server'
2279
+ Dir.chdir(ROOT_PATH)
2280
+ Rails::Server.start
2281
+ </ruby>
2282
+
2283
+ 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+.
2284
+
2285
+ 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:
2286
+
2287
+ <ruby>
2288
+ def start
2289
+ ENV["RAILS_ENV"] = options[:environment]
2290
+
2291
+ puts "=> Booting #{ActiveSupport::Inflector.demodulize(server)}"
2292
+ puts "=> Rails #{Rails.version} application starting in #{Rails.env} on http://#{options[:Host]}:#{options[:Port]}"
2293
+ puts "=> Call with -d to detach" unless options[:daemonize]
2294
+ trap(:INT) { exit }
2295
+ puts "=> Ctrl-C to shutdown server" unless options[:daemonize]
2296
+
2297
+ super
2298
+ ensure
2299
+ puts 'Exiting' unless options[:daemonize]
2300
+ end
2301
+ </ruby>
2302
+
2303
+ We can see here that there is usual output indicating that the server is booting up.
2304
+
2305
+ How the +options+ variable gets set and how Rack starts the server up is covered in the next section.
2306
+
2307
+ h3. Racking it up!
2308
+
2309
+
2310
+ This +Rack::Server.start+ method is defined like this:
2311
+
2312
+ <ruby>
2313
+ def self.start
2314
+ new.start
2315
+ end
2316
+ </ruby>
2317
+
2318
+ +new+ as you know calls +initialize+ in a class, and that is defined like this:
2319
+
2320
+ <ruby>
2321
+ def initialize(options = nil)
2322
+ @options = options
2323
+ end
2324
+ </ruby>
2325
+
2326
+ And then +options+, which are the options referenced by the +start+ method in +Rails::Server+.
2327
+
2328
+ <ruby>
2329
+ def options
2330
+ @options ||= parse_options(ARGV)
2331
+ end
2332
+ </ruby>
2333
+
2334
+ And +parse_options+:
2335
+
2336
+ <ruby>
2337
+ def parse_options(args)
2338
+ options = default_options
2339
+
2340
+ # Don't evaluate CGI ISINDEX parameters.
2341
+ # http://hoohoo.ncsa.uiuc.edu/cgi/cl.html
2342
+ args.clear if ENV.include?("REQUEST_METHOD")
2343
+
2344
+ options.merge! opt_parser.parse! args
2345
+ options
2346
+ end
2347
+ </ruby>
2348
+
2349
+ And +default_options+:
2350
+
2351
+ <ruby>
2352
+ def default_options
2353
+ {
2354
+ :environment => "development",
2355
+ :pid => nil,
2356
+ :Port => 9292,
2357
+ :Host => "0.0.0.0",
2358
+ :AccessLog => [],
2359
+ :config => "config.ru"
2360
+ }
2361
+ end
2362
+ </ruby>
2363
+
2364
+ 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:
2365
+
2366
+ <ruby>
2367
+ def start
2368
+ if options[:debug]
2369
+ $DEBUG = true
2370
+ require 'pp'
2371
+ p options[:server]
2372
+ pp wrapped_app
2373
+ pp app
2374
+ end
2375
+
2376
+ if options[:warn]
2377
+ $-w = true
2378
+ end
2379
+
2380
+ if includes = options[:include]
2381
+ $LOAD_PATH.unshift *includes
2382
+ end
2383
+
2384
+ if library = options[:require]
2385
+ require library
2386
+ end
2387
+
2388
+ daemonize_app if options[:daemonize]
2389
+ write_pid if options[:pid]
2390
+ server.run wrapped_app, options
2391
+ end
2392
+ </ruby>
2393
+
2394
+ 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:
2395
+
2396
+ <ruby>
2397
+ def wrapped_app
2398
+ @wrapped_app ||= build_app app
2399
+ end
2400
+ </ruby>
2401
+
2402
+ and +build_app+'s first and only argument is +app+ which is defined like this:
2403
+
2404
+
2405
+ <ruby>
2406
+ def app
2407
+ @app ||= begin
2408
+ if !::File.exist? options[:config]
2409
+ abort "configuration #{options[:config]} not found"
2410
+ end
2411
+
2412
+ app, options = Rack::Builder.parse_file(self.options[:config], opt_parser)
2413
+ self.options.merge! options
2414
+ app
2415
+ end
2416
+ end
2417
+ </ruby>
2418
+
2419
+ +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_:
2420
+
2421
+ <ruby>
2422
+ def self.parse_file(config, opts = Server::Options.new)
2423
+ options = {}
2424
+ if config =~ /\.ru$/
2425
+ cfgfile = ::File.read(config)
2426
+ if cfgfile[/^#\\(.*)/] && opts
2427
+ options = opts.parse! $1.split(/\s+/)
2428
+ end
2429
+ cfgfile.sub!(/^__END__\n.*/, '')
2430
+ app = eval "Rack::Builder.new {( " + cfgfile + "\n )}.to_app",
2431
+ TOPLEVEL_BINDING, config
2432
+ else
2433
+ require config
2434
+ app = Object.const_get(::File.basename(config, '.rb').capitalize)
2435
+ end
2436
+ return app, options
2437
+ end
2438
+ </ruby>
2439
+
2440
+ 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:
2441
+
2442
+ <ruby>
2443
+ #\\ -E production
2444
+ # This file is used by Rack-based servers to start the application.
2445
+
2446
+ require ::File.expand_path('../config/environment', __FILE__)
2447
+ run YourApp::Application.instance
2448
+
2449
+ </ruby>
2450
+
2451
+ TODO: Is the above correct? I am simply guessing!
2452
+
2453
+ 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.
2454
+
2455
+ h3. _config/environment.rb_
2456
+
2457
+ 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.
2458
+
2459
+ <ruby>
2460
+ # Load the rails application
2461
+ require File.expand_path('../application', __FILE__)
2462
+
2463
+ # Initialize the rails application
2464
+ YourApp::Application.initialize!
2465
+
2466
+ </ruby>
2467
+
2468
+ As you can see, there's a require in here for _config/application.rb_, and this file looks like this:
2469
+
2470
+
2471
+ <ruby>
2472
+ module YourApp
2473
+ class Application < Rails::Application
2474
+ # Settings in config/environments/* take precedence over those specified here.
2475
+ # Application configuration should go into files in config/initializers
2476
+ # -- all .rb files in that directory are automatically loaded.
2477
+
2478
+ # Add additional load paths for your own custom dirs
2479
+ # config.load_paths += %W( #{config.root}/extras )
2480
+
2481
+ # Only load the plugins named here, in the order given (default is alphabetical).
2482
+ # :all can be used as a placeholder for all plugins not explicitly named
2483
+ # config.plugins = [ :exception_notification, :ssl_requirement, :all ]
2484
+
2485
+ # Activate observers that should always be running
2486
+ # config.active_record.observers = :cacher, :garbage_collector, :forum_observer
2487
+
2488
+ # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
2489
+ # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
2490
+ # config.time_zone = 'Central Time (US & Canada)'
2491
+
2492
+ # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
2493
+ # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
2494
+ # config.i18n.default_locale = :de
2495
+
2496
+ # Configure generators values. Many other options are available, be sure to check the documentation.
2497
+ # config.generators do |g|
2498
+ # g.orm :active_record
2499
+ # g.template_engine :erb
2500
+ # g.test_framework :test_unit, :fixture => true
2501
+ # end
2502
+ end
2503
+ end
2504
+ </ruby>
2505
+
2506
+ 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.
2507
+
2508
+
2509
+ h3. Rails Initialization Process
2510
+
2511
+ 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.
2512
+
2513
+ h3. +Rails::Application+
2514
+
2515
+ 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+:
2516
+
2517
+ <ruby>
2518
+ def inherited(base)
2519
+ raise "You cannot have more than one Rails::Application" if Rails.application
2520
+ super
2521
+ Rails.application = base.instance
2522
+ end
2523
+ </ruby>
2524
+
2525
+ This goes up the chain by using +super+ to calling +Rails::Engine.inherited+:
2526
+
2527
+ <ruby>
2528
+ def inherited(base)
2529
+ unless abstract_railtie?(base)
2530
+ base.called_from = begin
2531
+ call_stack = caller.map { |p| p.split(':').first }
2532
+ File.dirname(call_stack.detect { |p| p !~ %r[railties/lib/rails|rack/lib/rack] })
2533
+ end
2534
+ end
2535
+
2536
+ super
2537
+ end
2538
+ </ruby>
2539
+
2540
+ +called_from+ references where this code was called from. This is covered later on in the "Bootstrap Initializers" section.
2541
+
2542
+ Which then calls +Rails::Railtie.inherited+:
2543
+
2544
+ <ruby>
2545
+ def inherited(base)
2546
+ unless abstract_railtie?(base)
2547
+ base.send(:include, self::Configurable)
2548
+ subclasses << base
2549
+ end
2550
+ end
2551
+ </ruby>
2552
+
2553
+ 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+.
2554
+
2555
+ Then this adds to +Rails::Railtie.subclasses+ your application's class because... TODO: explain.
2556
+
2557
+ 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:
2558
+
2559
+ <ruby>
2560
+ Rails.application = base.instance
2561
+ </ruby>
2562
+
2563
+ 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:
2564
+
2565
+ <ruby>
2566
+ def instance
2567
+ if self == Rails::Application
2568
+ Rails.application
2569
+ else
2570
+ @@instance ||= new
2571
+ end
2572
+ end
2573
+ </ruby>
2574
+
2575
+ The +new+ method here simply creates a new +Rails::Application+ and sets it to the +@@instance+ class variable. No magic.
2576
+
2577
+ h3. Your Application's Configuration
2578
+
2579
+ 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:
2580
+
2581
+ <ruby>
2582
+ def config
2583
+ @config ||= Railtie::Configuration.new
2584
+ end
2585
+ </ruby>
2586
+
2587
+ All the methods for +Rails::Railtie::Configuration+ are defined like this in _railties/lib/rails/railtie/configuration.rb_:
2588
+
2589
+ <ruby>
2590
+ require 'rails/configuration'
2591
+
2592
+ module Rails
2593
+ class Railtie
2594
+ class Configuration
2595
+ include Rails::Configuration::Shared
2596
+ end
2597
+ end
2598
+ end
2599
+ </ruby>
2600
+
2601
+ As you can probably guess here, the +Rails::Configuration+ module is defined by _rails/configuration_ (_railties/lib/rails/configuration.rb_).
2602
+
2603
+ h3. +Rails::Configuration::Shared+
2604
+
2605
+ In a standard application, the +application.rb+ looks like this with all the comments stripped out:
2606
+
2607
+ <ruby>
2608
+ require File.expand_path('../boot', __FILE__)
2609
+
2610
+ module YourApp
2611
+ class Application < Rails::Application
2612
+ config.filter_parameters << :password
2613
+ end
2614
+ end
2615
+ </ruby>
2616
+
2617
+ The +config+ method being the one defined on +Rails::Application::Configurable+:
2618
+
2619
+ <ruby>
2620
+ def config
2621
+ @config ||= Application::Configuration.new(self.class.find_root_with_flag("config.ru", Dir.pwd))
2622
+ end
2623
+ </ruby>
2624
+
2625
+ 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:
2626
+
2627
+ <ruby>
2628
+ def find_root_with_flag(flag, default=nil)
2629
+ root_path = self.called_from
2630
+
2631
+ while root_path && File.directory?(root_path) && !File.exist?("#{root_path}/#{flag}")
2632
+ parent = File.dirname(root_path)
2633
+ root_path = parent != root_path && parent
2634
+ end
2635
+
2636
+ root = File.exist?("#{root_path}/#{flag}") ? root_path : default
2637
+ raise "Could not find root path for #{self}" unless root
2638
+
2639
+ RUBY_PLATFORM =~ /(:?mswin|mingw)/ ?
2640
+ Pathname.new(root).expand_path : Pathname.new(root).realpath
2641
+ end
2642
+ </ruby>
2643
+
2644
+ +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:
2645
+
2646
+ <pre>
2647
+ /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.0.beta1/lib/rails/application.rb:30:in `inherited'
2648
+ /home/you/yourapp/config/application.rb:4:in `<module:TestApp>'
2649
+ /home/you/yourapp/config/application.rb:3:in `<top (required)>'
2650
+ /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0.beta1/lib/active_support/dependencies.rb:167:in `require'
2651
+ /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0.beta1/lib/active_support/dependencies.rb:167:in `block in require'
2652
+ /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0.beta1/lib/active_support/dependencies.rb:537:in `new_constants_in'
2653
+ /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0.beta1/lib/active_support/dependencies.rb:167:in `require'
2654
+ /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.0.beta1/lib/rails/commands.rb:33:in `<top (required)>'
2655
+ /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0.beta1/lib/active_support/dependencies.rb:167:in `require'
2656
+ /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0.beta1/lib/active_support/dependencies.rb:167:in `block in require'
2657
+ /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0.beta1/lib/active_support/dependencies.rb:537:in `new_constants_in'
2658
+ /usr/local/lib/ruby/gems/1.9.1/gems/activesupport-3.0.0.beta1/lib/active_support/dependencies.rb:167:in `require'
2659
+ /var/www/rboard/script/rails:10:in `<main>'
2660
+ </pre>
2661
+
2662
+ +called_from+ is defined in the +inherited+ method for +Rails::Engine+ which looks like this:
2663
+
2664
+ <ruby>
2665
+ base.called_from = begin
2666
+ call_stack = caller.map { |p| p.split(':').first }
2667
+ File.dirname(call_stack.detect { |p| p !~ %r[railties/lib/rails|rack/lib/rack] })
2668
+ end
2669
+ </ruby>
2670
+
2671
+ 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.beta1/lib/rails_. Yours may vary slightly, but should always end in _railties-x.x.x/lib/rails_.
2672
+
2673
+ The code in +find_root_with_flag+ will go up this directory structure until it reaches the top, which in this case is +/+.
2674
+
2675
+ <ruby>
2676
+ while root_path && File.directory?(root_path) && !File.exist?("#{root_path}/#{flag}")
2677
+ parent = File.dirname(root_path)
2678
+ root_path = parent != root_path && parent
2679
+ end
2680
+
2681
+ root = File.exist?("#{root_path}/#{flag}") ? root_path : default
2682
+ raise "Could not find root path for #{self}" unless root
2683
+ </ruby>
2684
+
2685
+ TODO: What is all this for?
2686
+
2687
+ 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:
2688
+
2689
+ <ruby>
2690
+ def initialize(*)
2691
+ super
2692
+ @allow_concurrency = false
2693
+ @colorize_logging = true
2694
+ @filter_parameters = []
2695
+ @dependency_loading = true
2696
+ @serve_static_assets = true
2697
+ @time_zone = "UTC"
2698
+ @consider_all_requests_local = true
2699
+ end
2700
+ </ruby>
2701
+
2702
+ The +super+ method here is the +initialize+ method in +Rails::Engine::Configuration+:
2703
+
2704
+ <ruby>
2705
+ def initialize(root=nil)
2706
+ @root = root
2707
+ end
2708
+ </ruby>
2709
+
2710
+ 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+.
2711
+
2712
+ 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:
2713
+
2714
+ <ruby>
2715
+ def method_missing(name, *args, &blk)
2716
+ if name.to_s =~ config_key_regexp
2717
+ return $2 == '=' ? options[$1] = args.first : options[$1]
2718
+ end
2719
+ super
2720
+ end
2721
+ </ruby>
2722
+
2723
+ 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:
2724
+
2725
+ <ruby>
2726
+ def options
2727
+ @@options ||= Hash.new { |h,k| h[k] = ActiveSupport::OrderedOptions.new }
2728
+ end
2729
+ </ruby>
2730
+
2731
+ OrderedOptions exists... TODO: explain.
2732
+
2733
+
2734
+ 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.
2735
+
2736
+ h3. Application Configured!
2737
+
2738
+ 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!+.
2739
+
2740
+ h3. Initialization begins
2741
+
2742
+ 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.
2743
+
2744
+ +Rails::Application+ has a +method_missing+ definition which does this:
2745
+
2746
+ <ruby>
2747
+ def method_missing(*args, &block)
2748
+ instance.send(*args, &block)
2749
+ end
2750
+ </ruby>
2751
+
2752
+ 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:
2753
+
2754
+ <ruby>
2755
+ def initialize!
2756
+ run_initializers(self)
2757
+ self
2758
+ end
2759
+ </ruby>
2760
+
2761
+ The initializers it is talking about running here are the initializers for our application. The object passed in to +run_initializers+ is +YourApp::Application+.
2762
+
2763
+
2764
+ h3. +run_initializers+
2765
+
2766
+ 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.
2767
+
2768
+ +run_initializers+ looks like this:
2769
+
2770
+ <ruby>
2771
+ def run_initializers(*args)
2772
+ return if instance_variable_defined?(:@ran)
2773
+ initializers.each do |initializer|
2774
+ initializer.run(*args)
2775
+ end
2776
+ @ran = true
2777
+ end
2778
+ </ruby>
2779
+
2780
+ Here the +initializers+ method is defined in _railties/lib/rails/application.rb_:
2781
+
2782
+ <ruby>
2783
+ def initializers
2784
+ initializers = Bootstrap.initializers_for(self)
2785
+ railties.all { |r| initializers += r.initializers }
2786
+ initializers += super
2787
+ initializers += Finisher.initializers_for(self)
2788
+ initializers
2789
+ end
2790
+ </ruby>
2791
+
2792
+ h3. +Bootstrap+ initializers
2793
+
2794
+ 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+:
2795
+
2796
+ <ruby>
2797
+ autoload :Bootstrap, 'rails/application/bootstrap'
2798
+ </ruby>
2799
+
2800
+ 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.
2801
+
2802
+ * load_environment_config
2803
+ * load_all_active_support
2804
+ * preload_frameworks
2805
+ * initialize_logger
2806
+ * initialize_cache
2807
+ * initialize_subscriber
2808
+ * set_clear_dependencies_hook
2809
+ * initialize_dependency_mechanism
2810
+ * bootstrap_load_path
2811
+
2812
+ These are all defined using the +initializer+ method:
2813
+
2814
+ <ruby>
2815
+ def initializer(name, opts = {}, &blk)
2816
+ raise ArgumentError, "A block must be passed when defining an initializer" unless blk
2817
+ opts[:after] ||= initializers.last.name unless initializers.empty? || initializers.find { |i| i.name == opts[:before] }
2818
+ initializers << Initializer.new(name, nil, opts, &blk)
2819
+ end
2820
+ </ruby>
2821
+
2822
+ The +initializers+ method defined here just references an +@initializers+ variable:
2823
+
2824
+ <ruby>
2825
+ def initializers
2826
+ @initializers ||= []
2827
+ end
2828
+ </ruby>
2829
+
2830
+ 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:
2831
+
2832
+ <ruby>
2833
+ class Initializer
2834
+ attr_reader :name, :block
2835
+
2836
+ def initialize(name, context, options, &block)
2837
+ @name, @context, @options, @block = name, context, options, block
2838
+ end
2839
+
2840
+ def before
2841
+ @options[:before]
2842
+ end
2843
+
2844
+ def after
2845
+ @options[:after]
2846
+ end
2847
+
2848
+ def run(*args)
2849
+ @context.instance_exec(*args, &block)
2850
+ end
2851
+
2852
+ def bind(context)
2853
+ return self if @context
2854
+ Initializer.new(@name, context, @options, &block)
2855
+ end
2856
+ end
2857
+ </ruby>
2858
+
2859
+ Now that +Rails::Application::Bootstrap+ has finished loading, we can continue on with our initialization. We saw that it called this:
2860
+
2861
+ <ruby>
2862
+ initializers = Bootstrap.initializers_for(self)
2863
+ </ruby>
2864
+
2865
+ Calling +initializers_for+, defined like this:
2866
+
2867
+ <ruby>
2868
+ def initializers_for(binding)
2869
+ Collection.new(initializers_chain.map { |i| i.bind(binding) })
2870
+ end
2871
+ </ruby>
2872
+
2873
+ 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:
2874
+
2875
+ <ruby>
2876
+ def initializers_chain
2877
+ initializers = Collection.new
2878
+ ancestors.reverse_each do |klass|
2879
+ next unless klass.respond_to?(:initializers)
2880
+ initializers = initializers + klass.initializers
2881
+ end
2882
+ initializers
2883
+ end
2884
+ </ruby>
2885
+
2886
+ 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.
2887
+
2888
+ After +initializers_chain+ is finished, then they are +map+'d like this, with the +binding+ of course being +YourApp::Application+ as explained previously.
2889
+
2890
+ <ruby>
2891
+ def initializers_for(binding)
2892
+ Collection.new(initializers_chain.map { |i| i.bind(binding) })
2893
+ end
2894
+ </ruby>
2895
+
2896
+ Wow. All that to cover just the first line in the +initializers+ method for +Rails::Application+.
2897
+
2898
+ h3. Railties Initializers
2899
+
2900
+ 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.
2901
+
2902
+ The second line in +Rails::Application#initializers+:
2903
+
2904
+ <ruby>
2905
+ def initializers
2906
+ railties.all { |r| initializers += r.initializers }
2907
+ end
2908
+ </ruby>
2909
+
2910
+ calls +railties+, which is defined like this:
2911
+
2912
+ <ruby>
2913
+ def railties
2914
+ @railties ||= Railties.new(config)
2915
+ end
2916
+ </ruby>
2917
+
2918
+ This sets up a new +Rails::Application::Railties+ object like this:
2919
+
2920
+ <ruby>
2921
+ def initialize(config)
2922
+ @config = config
2923
+ end
2924
+ </ruby>
2925
+
2926
+ And calls +all+ on it:
2927
+
2928
+ <ruby>
2929
+ def all(&block)
2930
+ @all ||= railties + engines + plugins
2931
+ @all.each(&block) if block
2932
+ @all
2933
+ end
2934
+ </ruby>
2935
+
2936
+ 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+:
2937
+
2938
+ <ruby>
2939
+ def railties
2940
+ @railties ||= ::Rails::Railtie.subclasses.map(&:new)
2941
+ end
2942
+
2943
+ def engines
2944
+ @engines ||= ::Rails::Engine.subclasses.map(&:new)
2945
+ end
2946
+ </ruby>
2947
+
2948
+ By default, the railties are:
2949
+
2950
+ * +ActiveSupport::Railtie+
2951
+ * +I18n::Railtie+
2952
+ * +ActionDispatch::Railtie+
2953
+ * +ActionController::Railtie+
2954
+ * +ActiveRecord::Railtie+
2955
+ * +ActionView::Railtie+
2956
+ * +ActionMailer::Railtie+
2957
+ * +ActiveResource::Railtie+
2958
+ * +Rails::TestUnitRailtie+
2959
+
2960
+ And these all descend from +Rails::Railtie+.
2961
+
2962
+ The default +engines+ are +[]+.
2963
+
2964
+ The +plugins+ method it calls is a little more complex:
2965
+
2966
+ <ruby>
2967
+ def plugins
2968
+ @plugins ||= begin
2969
+ plugin_names = (@config.plugins || [:all]).map { |p| p.to_sym }
2970
+ Plugin.all(plugin_names, @config.paths.vendor.plugins)
2971
+ end
2972
+ end
2973
+ </ruby>
2974
+
2975
+ +@config.paths+ is defined in the +Rails::Application::Configuration+ like this:
2976
+
2977
+ <ruby>
2978
+ def paths
2979
+ @paths ||= begin
2980
+ paths = super
2981
+ paths.app.controllers << builtin_controller if builtin_controller
2982
+ paths.config.database "config/database.yml"
2983
+ paths.config.environment "config/environments", :glob => "#{Rails.env}.rb"
2984
+ paths.log "log/#{Rails.env}.log"
2985
+ paths.tmp "tmp"
2986
+ paths.tmp.cache "tmp/cache"
2987
+ paths.vendor "vendor", :load_path => true
2988
+ paths.vendor.plugins "vendor/plugins"
2989
+
2990
+ if File.exists?("#{root}/test/mocks/#{Rails.env}")
2991
+ ActiveSupport::Deprecation.warn "\"RAILS_ROOT/test/mocks/#{Rails.env}\" won't be added " <<
2992
+ "automatically to load paths anymore in future releases"
2993
+ paths.mocks_path "test/mocks", :load_path => true, :glob => Rails.env
2994
+ end
2995
+
2996
+ paths
2997
+ end
2998
+ end
2999
+ </ruby>
3000
+
3001
+ When we call +@config.paths.vendor.plugins+ it will return +"vendor/plugins"+.
3002
+
3003
+
3004
+ If you've defined specific plugin requirements for your application in _config/application.rb_ by using this code:
3005
+
3006
+ <ruby>
3007
+ config.plugins = [:will_paginate, :by_star]
3008
+ </ruby>
3009
+
3010
+ or specific plugin loading using a similar statement such as this next one:
3011
+
3012
+ <ruby>
3013
+ config.plugins = [:will_paginate, :by_star, :all]
3014
+ </ruby>
3015
+
3016
+
3017
+ 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.
3018
+
3019
+ 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_):
3020
+
3021
+ <ruby>
3022
+ def self.all(list, paths)
3023
+ plugins = []
3024
+ paths.each do |path|
3025
+ Dir["#{path}/*"].each do |plugin_path|
3026
+ plugin = new(plugin_path)
3027
+ next unless list.include?(plugin.name) || list.include?(:all)
3028
+ plugins << plugin
3029
+ end
3030
+ end
3031
+
3032
+ plugins.sort_by do |p|
3033
+ [list.index(p.name) || list.index(:all), p.name.to_s]
3034
+ end
3035
+ end
3036
+ </ruby>
3037
+
3038
+ 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:
3039
+
3040
+ <ruby>
3041
+ def initialize(root)
3042
+ @name = File.basename(root).to_sym
3043
+ config.root = root
3044
+ end
3045
+ </ruby>
3046
+
3047
+ 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:
3048
+
3049
+ <ruby>
3050
+ def config
3051
+ @config ||= Engine::Configuration.new
3052
+ end
3053
+ </ruby>
3054
+
3055
+ 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:
3056
+
3057
+ <ruby>
3058
+ initializer :load_init_rb, :before => :load_application_initializers do |app|
3059
+ file = Dir["#{root}/{rails/init,init}.rb"].first
3060
+ config = app.config
3061
+ eval(File.read(file), binding, file) if file && File.file?(file)
3062
+ end
3063
+ </ruby>
3064
+
3065
+ A little more on that later, however.
3066
+
3067
+ 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:
3068
+
3069
+ <ruby>
3070
+ plugins.sort_by do |p|
3071
+ [list.index(p.name) || list.index(:all), p.name.to_s]
3072
+ end
3073
+ </ruby>
3074
+
3075
+ 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.
3076
+
3077
+ Now that we have our railties, engines, and plugins in a line we can finally get back to the +all+ code:
3078
+
3079
+ <ruby>
3080
+ def initializers
3081
+ railties.all { |r| initializers += r.initializers }
3082
+ end
3083
+ </ruby>
3084
+
3085
+ This block will gather add the railties' initializers to it.
3086
+
3087
+ h3. Engine Initializers
3088
+
3089
+ The third line in this +initializers+ method:
3090
+
3091
+ <ruby>
3092
+ initializers += super
3093
+ </ruby>
3094
+
3095
+ 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+.
3096
+
3097
+ h3. Finisher Initializers
3098
+
3099
+ 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_.
3100
+
3101
+ h3. Running the Initializers
3102
+
3103
+ Now that we have all the initializers we can go back to the +run_initializers+ in +Rails::Initializable+:
3104
+
3105
+ <ruby>
3106
+ def run_initializers(*args)
3107
+ return if instance_variable_defined?(:@ran)
3108
+ initializers.each do |initializer|
3109
+ initializer.run(*args)
3110
+ end
3111
+ @ran = true
3112
+ end
3113
+ </ruby>
3114
+
3115
+ Now we finally have all the +initializers+ we can go through them and call +run+:
3116
+
3117
+ <ruby>
3118
+ def run(*args)
3119
+ @context.instance_exec(*args, &block)
3120
+ end
3121
+ </ruby>
3122
+
3123
+ 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.
3124
+
3125
+ h3. Bootstrap Initializers
3126
+
3127
+ These initializers are the very first initializers that will be used to get your application going.
3128
+
3129
+ h4. +load_environment_config+
3130
+
3131
+ <ruby>
3132
+ initializer :load_environment_config do
3133
+ require_environment!
3134
+ end
3135
+ </ruby>
3136
+
3137
+ This quite simply makes a call to +require_environment!+ which is defined like this in +Rails::Application+:
3138
+
3139
+ <ruby>
3140
+ def require_environment!
3141
+ environment = config.paths.config.environment.to_a.first
3142
+ require environment if environment
3143
+ end
3144
+ </ruby>
3145
+
3146
+ 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:
3147
+
3148
+ <ruby>
3149
+ paths.config.environment "config/environments", :glob => "#{Rails.env}.rb"
3150
+ </ruby>
3151
+
3152
+ +Rails.env+ was defined way back in the boot process when +railties/lib/rails.rb+ was required:
3153
+
3154
+ <ruby>
3155
+ module Rails
3156
+ class << self
3157
+
3158
+ ...
3159
+
3160
+ def env
3161
+ @_env ||= ActiveSupport::StringInquirer.new(ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development")
3162
+ end
3163
+
3164
+ ...
3165
+
3166
+ end
3167
+ end
3168
+ </ruby>
3169
+
3170
+ With +ENV["RAILS_ENV"]+ and +ENV["RACK_ENV"]+ not set to anything for our server booting process, this will default to +"development"+.
3171
+
3172
+ Therefore the path to this config file line would look like this with a substitution made:
3173
+
3174
+ <ruby>
3175
+ paths.config.environment "config/environments", :glob => "development.rb"
3176
+ </ruby>
3177
+
3178
+ This method returns a +Path+ object (which acts as an +Enumerable+).
3179
+
3180
+ Back to +require_environment+ now:
3181
+
3182
+ <ruby>
3183
+ def require_environment!
3184
+ environment = config.paths.config.environment.to_a.first
3185
+ require environment if environment
3186
+ end
3187
+ </ruby>
3188
+
3189
+ 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:
3190
+
3191
+ <ruby>
3192
+ alias to_a paths
3193
+ </ruby>
3194
+
3195
+ <ruby>
3196
+ def paths
3197
+ raise "You need to set a path root" unless @root.path
3198
+ result = @paths.map do |p|
3199
+ path = File.expand_path(p, @root.path)
3200
+ @glob ? Dir[File.join(path, @glob)] : path
3201
+ end
3202
+ result.flatten!
3203
+ result.uniq!
3204
+ result
3205
+ end
3206
+ </ruby>
3207
+
3208
+ 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:
3209
+
3210
+ <ruby>
3211
+ Dir[File.join(path, @glob)]
3212
+ </ruby>
3213
+
3214
+ 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"+.
3215
+
3216
+ This file contains the following by default:
3217
+
3218
+ <ruby>
3219
+ YourApp::Application.configure do
3220
+ # Settings specified here will take precedence over those in config/environment.rb
3221
+
3222
+ # In the development environment your application's code is reloaded on
3223
+ # every request. This slows down response time but is perfect for development
3224
+ # since you don't have to restart the webserver when you make code changes.
3225
+ config.cache_classes = false
3226
+
3227
+ # Log error messages when you accidentally call methods on nil.
3228
+ config.whiny_nils = true
3229
+
3230
+ # Show full error reports and disable caching
3231
+ config.consider_all_requests_local = true
3232
+ config.action_view.debug_rjs = true
3233
+ config.action_controller.perform_caching = false
3234
+
3235
+ # Don't care if the mailer can't send
3236
+ config.action_mailer.raise_delivery_errors = false
3237
+ end
3238
+ </ruby>
3239
+
3240
+ This +configure+ method is an +alias+ of +class_eval+ on +Rails::Application+:
3241
+
3242
+ <ruby>
3243
+ alias :configure :class_eval
3244
+ </ruby>
3245
+
3246
+ therefore, the code inside of the +configure+ is evaluated within the context of +YourApp::Application+.
3247
+
3248
+ 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+:
3249
+
3250
+ <ruby>
3251
+ def method_missing(name, *args, &blk)
3252
+ if name.to_s =~ config_key_regexp
3253
+ return $2 == '=' ? options[$1] = args.first : options[$1]
3254
+ end
3255
+ super
3256
+ end
3257
+ </ruby>
3258
+
3259
+ 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.
3260
+
3261
+ Firstly, we'll cover how +config_key_regexp+ is defined:
3262
+
3263
+ <ruby>
3264
+ def config_key_regexp
3265
+ bits = config_keys.map { |n| Regexp.escape(n.to_s) }.join('|')
3266
+ /^(#{bits})(?:=)?$/
3267
+ end
3268
+ </ruby>
3269
+
3270
+ And also +config_keys+:
3271
+
3272
+ <ruby>
3273
+ def config_keys
3274
+ (Railtie.railtie_names + Engine.engine_names).map { |n| n.to_s }.uniq
3275
+ end
3276
+ </ruby>
3277
+
3278
+ +config_keys+ in here returns:
3279
+
3280
+ <ruby>
3281
+ [:active_support, :i18n, :action_dispatch, :action_view, :action_controller, :active_record, :action_mailer, :active_resource, :test_unit]
3282
+ </ruby>
3283
+
3284
+ 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.
3285
+
3286
+ Now a reminder of how the +options+ key is defined:
3287
+
3288
+ <ruby>
3289
+ def options
3290
+ @@options ||= Hash.new { |h,k| h[k] = ActiveSupport::OrderedOptions.new }
3291
+ end
3292
+ </ruby>
3293
+
3294
+ The values for these framework keys are +ActiveSupport::OrderedOptions+ objects, with the class defined like this:
3295
+
3296
+ <ruby>
3297
+ module ActiveSupport #:nodoc:
3298
+ class OrderedOptions < OrderedHash
3299
+ def []=(key, value)
3300
+ super(key.to_sym, value)
3301
+ end
3302
+
3303
+ def [](key)
3304
+ super(key.to_sym)
3305
+ end
3306
+
3307
+ def method_missing(name, *args)
3308
+ if name.to_s =~ /(.*)=$/
3309
+ self[$1.to_sym] = args.first
3310
+ else
3311
+ self[name]
3312
+ end
3313
+ end
3314
+ end
3315
+ end
3316
+ </ruby>
3317
+
3318
+ 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_.
3319
+
3320
+ h4. +load_all_active_support+
3321
+
3322
+ This initializer does exactly what it says:
3323
+
3324
+ <ruby>
3325
+ initializer :load_all_active_support do
3326
+ require "active_support/all" unless config.active_support.bare
3327
+ end
3328
+ </ruby>
3329
+
3330
+ 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.
3331
+
3332
+ h4. +preload_frameworks+
3333
+
3334
+ Remember earlier how we had all that stuff +eager_autoload+'d for ActiveSupport?
3335
+
3336
+ <ruby>
3337
+ initializer :preload_frameworks do
3338
+ require 'active_support/dependencies'
3339
+ ActiveSupport::Autoload.eager_autoload! if config.preload_frameworks
3340
+ end
3341
+ </ruby>
3342
+
3343
+ This is where it gets loaded. The +eager_autoload!+ method is defined like this:
3344
+
3345
+ <ruby>
3346
+ def self.eager_autoload!
3347
+ @@autoloads.values.each { |file| require file }
3348
+ end
3349
+ </ruby>
3350
+
3351
+ With +@@autoloads+ being
3352
+
3353
+
3354
+ * load_all_active_support
3355
+ * preload_frameworks
3356
+ * initialize_logger
3357
+ * initialize_cache
3358
+ * initialize_subscriber
3359
+ * set_clear_dependencies_hook
3360
+ * initialize_dependency_mechanism
3361
+ * bootstrap_load_path
3362
+
3363
+ h4. ActiveSupport Initializers
3364
+
3365
+ ActiveSupport
3366
+
3367
+ **ActiveSupport Initializers**
3368
+
3369
+ * active_support.initialize_whiny_nils
3370
+ * active_support.initialize_time_zone
3371
+
3372
+ **I18n Initializers**
3373
+
3374
+ * i18n.initialize
3375
+
3376
+ The +I18n::Railtie+ also defines an +after_initialize+ which we will return to later when discussing the initializers in detail.
3377
+
3378
+ **ActionDispatch Initializers**
3379
+
3380
+ * action_dispatch.prepare_dispatcher
3381
+
3382
+ **ActionController Initializers**
3383
+
3384
+ * action_controller.logger
3385
+ * action_controller.set_configs
3386
+ * action_controller.initialize_framework_caches
3387
+ * action_controller.set_helpers_path
3388
+
3389
+ **ActiveRecord Initializers**
3390
+
3391
+ * active_record.initialize_time_zone
3392
+ * active_record.logger
3393
+ * active_record.set_configs
3394
+ * active_record.log_runtime
3395
+ * active_record.initialize_database_middleware
3396
+ * active_record.load_observers
3397
+ * active_record.set_dispatch_hooks
3398
+
3399
+ **ActionView Initializers **
3400
+
3401
+ * action_view.cache_asset_timestamps
3402
+
3403
+ **ActionMailer Initializers **
3404
+
3405
+ * action_mailer.logger
3406
+ * action_mailer.set_configs
3407
+ * action_mailer.url_for
3408
+
3409
+ **ActiveResource Initializers**
3410
+
3411
+ * active_resource.set_configs
3412
+
3413
+ **Rails::Engine Initializers**
3414
+
3415
+ * set_load_path
3416
+ * set_autoload_paths
3417
+ * add_routing_paths
3418
+
3419
+
3420
+ h4. +Rails::Engine.new+
3421
+
3422
+ 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:
3423
+
3424
+ <ruby>
3425
+ def initialize
3426
+ require_environment
3427
+ Rails.application ||= self
3428
+ @route_configuration_files = []
3429
+ end
3430
+ </ruby>
3431
+
3432
+ h4. +Rails::Application#require_environment+
3433
+
3434
+ This is not a crafty method like the previous ones, it just does as it says on the box:
3435
+
3436
+ <ruby>
3437
+ def require_environment
3438
+ require config.environment_path
3439
+ rescue LoadError
3440
+ end
3441
+ </ruby>
3442
+
3443
+ The +config+ object here is actually another +delegate+'d method (along with +routes+), this time to +self.class+:
3444
+
3445
+ <ruby>
3446
+ delegate :config, :routes, :to => :'self.class'
3447
+ </ruby>
3448
+
3449
+ So the method call is actually +self.class.config+.
3450
+
3451
+
3452
+ h4. +Rails::Application.config+
3453
+
3454
+ 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+:
3455
+
3456
+ <ruby>
3457
+ def config
3458
+ @config ||= Configuration.new(Plugin::Configuration.default)
3459
+ end
3460
+ </ruby>
3461
+
3462
+ h4. +Rails::Plugin::Configuration.default+
3463
+
3464
+ 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:
3465
+
3466
+ <ruby>
3467
+ module Rails
3468
+ class Plugin < Railtie
3469
+ ...
3470
+ end
3471
+ end
3472
+ </ruby>
3473
+
3474
+ 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!
3475
+
3476
+ h4. +Rails::Railtie::Configuration+
3477
+
3478
+ 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_:
3479
+
3480
+ <ruby>
3481
+ class Railtie::Configuration
3482
+ def self.default
3483
+ @default ||= new
3484
+ end
3485
+ ...
3486
+ end
3487
+ </ruby>
3488
+
3489
+ In this case we have effectively seen that it's doing Configuration.new(Configuration.new). I'll explain why.
3490
+
3491
+ h4. +Rails::Application::Configuration.new+
3492
+
3493
+ 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!
3494
+
3495
+ 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:
3496
+
3497
+ <ruby>
3498
+ def initialize(base = nil)
3499
+ if base
3500
+ @options = base.options.dup
3501
+ @middleware = base.middleware.dup
3502
+ else
3503
+ @options = Hash.new { |h,k| h[k] = ActiveSupport::OrderedOptions.new }
3504
+ @middleware = self.class.default_middleware_stack
3505
+ end
3506
+ end
3507
+ </ruby>
3508
+
3509
+ 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.
3510
+
3511
+ h4. +default_middleware_stack+
3512
+
3513
+ This method is defined like this:
3514
+
3515
+ <ruby>
3516
+ def self.default_middleware_stack
3517
+ ActionDispatch::MiddlewareStack.new.tap do |middleware|
3518
+ middleware.use('ActionDispatch::Static', lambda { Rails.public_path }, :if => lambda { Rails.application.config.serve_static_assets })
3519
+ middleware.use('::Rack::Lock', :if => lambda { !ActionController::Base.allow_concurrency })
3520
+ middleware.use('::Rack::Runtime')
3521
+ middleware.use('ActionDispatch::ShowExceptions', lambda { ActionController::Base.consider_all_requests_local })
3522
+ middleware.use('ActionDispatch::Notifications')
3523
+ middleware.use('ActionDispatch::Callbacks', lambda { !Rails.application.config.cache_classes })
3524
+ middleware.use('ActionDispatch::Cookies')
3525
+ middleware.use(lambda { ActionController::Base.session_store }, lambda { ActionController::Base.session_options })
3526
+ middleware.use('ActionDispatch::Flash', :if => lambda { ActionController::Base.session_store })
3527
+ middleware.use(lambda { Rails::Rack::Metal.new(Rails.application.config.paths.app.metals.to_a, Rails.application.config.metals) })
3528
+ middleware.use('ActionDispatch::ParamsParser')
3529
+ middleware.use('::Rack::MethodOverride')
3530
+ middleware.use('::ActionDispatch::Head')
3531
+ end
3532
+ end
3533
+ </ruby>
3534
+
3535
+ 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.
3536
+
3537
+ h4. +ActionDispatch::MiddlewareStack.new+
3538
+
3539
+ +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:
3540
+
3541
+ <ruby>
3542
+ module ActionDispatch
3543
+ class MiddlewareStack < Array
3544
+
3545
+ ...
3546
+
3547
+ def initialize(*args, &block)
3548
+ super(*args)
3549
+ block.call(self) if block_given?
3550
+ end
3551
+ end
3552
+ end
3553
+ </ruby>
3554
+
3555
+ 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!
3556
+
3557
+ h4. +ActionDispatch::MiddlewareStack.use+
3558
+
3559
+ Previously we saw a chunk of code that I'll re-show you stripped down:
3560
+
3561
+ <ruby>
3562
+ def self.default_middleware_stack
3563
+ ActionDispatch::MiddlewareStack.new.tap do |middleware|
3564
+ middleware.use('ActionDispatch::Static', lambda { Rails.public_path }, :if => lambda { Rails.application.config.serve_static_assets })
3565
+ ...
3566
+ end
3567
+ end
3568
+ </ruby>
3569
+
3570
+ 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:
3571
+
3572
+ <ruby>
3573
+ def use(*args, &block)
3574
+ middleware = Middleware.new(*args, &block)
3575
+ push(middleware)
3576
+ end
3577
+ </ruby>
3578
+
3579
+ We'll come back to this method later on.
3580
+
3581
+ h4. +ActionController::Middleware.new+
3582
+
3583
+ 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:
3584
+
3585
+ <ruby>
3586
+ module ActionController
3587
+ class Middleware < Metal
3588
+
3589
+ ...
3590
+
3591
+ def initialize(app)
3592
+ super()
3593
+ @_app = app
3594
+ end
3595
+ end
3596
+ end
3597
+ </ruby>
3598
+
3599
+ 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+.
3600
+
3601
+ h4. +ActionController::Metal.initialize+
3602
+
3603
+ This is another subclassed class, this time from +ActionController::AbstractController+ and I'm sure you can guess what that means:
3604
+
3605
+ <ruby>
3606
+ class Metal < AbstractController::Base
3607
+
3608
+ ...
3609
+
3610
+ def initialize(*)
3611
+ @_headers = {}
3612
+ super
3613
+ end
3614
+ end
3615
+ </ruby>
3616
+
3617
+ The single +*+ in the argument listing means we can accept any number of arguments, we just don't care what they are.
3618
+
3619
+ h4. +AbstractController::Base.initialize+
3620
+
3621
+ This may be anti-climatic, but the initialize method here just returns an +AbstractController::Base+ object:
3622
+
3623
+ <ruby>
3624
+ # Initialize controller with nil formats.
3625
+ def initialize #:nodoc:
3626
+ @_formats = nil
3627
+ end
3628
+ </ruby>
3629
+
3630
+ h4. +ActionDispatch::MiddlewareStack.use+
3631
+
3632
+ 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
3633
+
3634
+ 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.
3635
+
3636
+ h4. Back to +Rails::Application::Configuration.new+
3637
+
3638
+ 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:
3639
+
3640
+ <ruby>
3641
+ def initialize(base = nil)
3642
+ if base
3643
+ @options = base.options.dup
3644
+ @middleware = base.middleware.dup
3645
+ else
3646
+ @options = Hash.new { |h,k| h[k] = ActiveSupport::OrderedOptions.new }
3647
+ @middleware = self.class.default_middleware_stack
3648
+ end
3649
+ end
3650
+ </ruby>
3651
+
3652
+ 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.
3653
+
3654
+ TODO: Find out what purpose the +@options+ and +@middleware+ variables serve.
3655
+
3656
+ 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:
3657
+
3658
+ <ruby>
3659
+ attr_accessor :after_initialize_blocks, :cache_classes, :colorize_logging,
3660
+ :consider_all_requests_local, :dependency_loading,
3661
+ :load_once_paths, :logger, :metals, :plugins,
3662
+ :preload_frameworks, :reload_plugins, :serve_static_assets,
3663
+ :time_zone, :whiny_nils
3664
+
3665
+ attr_writer :cache_store, :controller_paths,
3666
+ :database_configuration_file, :eager_load_paths,
3667
+ :i18n, :load_paths, :log_level, :log_path, :paths,
3668
+ :routes_configuration_file, :view_path
3669
+ </ruby>
3670
+
3671
+ Along with these are a lot of helper methods, and one of them is +environment_path+:
3672
+
3673
+ <ruby>
3674
+ def environment_path
3675
+ "#{root}/config/environments/#{Rails.env}.rb"
3676
+ end
3677
+ </ruby>
3678
+
3679
+ h4. Back to +Rails::Application#require_environment+
3680
+
3681
+ 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.
3682
+
3683
+ h4. _config/environments/development.rb_
3684
+
3685
+ In a standard Rails application we have this in our _config/environments/development.rb_ file:
3686
+
3687
+ <ruby>
3688
+ YourApp::Application.configure do
3689
+ # Settings specified here will take precedence over those in config/environment.rb
3690
+
3691
+ # In the development environment your application's code is reloaded on
3692
+ # every request. This slows down response time but is perfect for development
3693
+ # since you don't have to restart the webserver when you make code changes.
3694
+ config.cache_classes = false
3695
+
3696
+ # Log error messages when you accidentally call methods on nil.
3697
+ config.whiny_nils = true
3698
+
3699
+ # Show full error reports and disable caching
3700
+ config.action_controller.consider_all_requests_local = true
3701
+ config.action_view.debug_rjs = true
3702
+ config.action_controller.perform_caching = false
3703
+
3704
+ # Don't care if the mailer can't send
3705
+ config.action_mailer.raise_delivery_errors = false
3706
+ end
3707
+ </ruby>
3708
+
3709
+ 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.
3710
+
3711
+ 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.
3712
+
3713
+ h5. config.cache_classes=
3714
+
3715
+ 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.
3716
+
3717
+ h5. config.whiny_nils=
3718
+
3719
+ 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:
3720
+
3721
+ <ruby>
3722
+ Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
3723
+ </ruby>
3724
+
3725
+ Or perhaps this one?
3726
+
3727
+ <ruby>
3728
+ You have a nil object when you didn't expect it!
3729
+ You might have expected an instance of Array.
3730
+ The error occurred while evaluating nil.flatten!
3731
+ </ruby>
3732
+
3733
+ If you have, then this is _activesupport/whiny_nil_ at work.
3734
+
3735
+
3736
+ h5. The frameworks
3737
+
3738
+ 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:
3739
+
3740
+ <ruby>
3741
+ def method_missing(name, *args, &blk)
3742
+ if name.to_s =~ config_key_regexp
3743
+ return $2 == '=' ? @options[$1] = args.first : @options[$1]
3744
+ end
3745
+
3746
+ super
3747
+ end
3748
+ </ruby>
3749
+
3750
+ 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:
3751
+
3752
+ <ruby>
3753
+ def config_key_regexp
3754
+ bits = config_keys.map { |n| Regexp.escape(n.to_s) }.join('|')
3755
+ /^(#{bits})(?:=)?$/
3756
+ end
3757
+ </ruby>
3758
+
3759
+ As is +config_keys+:
3760
+
3761
+ <ruby>
3762
+ def config_keys
3763
+ ([ :active_support, :action_view ] +
3764
+ Railtie.plugin_names).map { |n| n.to_s }.uniq
3765
+ end
3766
+ </ruby>
3767
+
3768
+ Aha! There we've got mention of +action_view+, but what is in +Railtie.plugin_names+? Most likely in this case the other frameworks.
3769
+
3770
+ h5. +Railtie.plugin_names+
3771
+
3772
+ 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:
3773
+
3774
+ <ruby>
3775
+ module Rails
3776
+ class Railtie
3777
+ def self.inherited(klass)
3778
+ @plugins ||= []
3779
+ @plugins << klass unless klass == Plugin
3780
+ end
3781
+
3782
+ def self.plugins
3783
+ @plugins
3784
+ end
3785
+
3786
+ def self.plugin_names
3787
+ plugins.map { |p| p.plugin_name }
3788
+ end
3789
+ end
3790
+ end
3791
+ </ruby>
3792
+
3793
+ 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+.
3794
+
3795
+ h3. Serving a Request
3796
+
3797
+ Now that your application is fully initialized, it's now ready to start serving requests.
3798
+
3799
+ h4. _rails server_
3800
+
3801
+ 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:
3802
+
3803
+ <ruby>
3804
+ def start
3805
+ if options[:debug]
3806
+ $DEBUG = true
3807
+ require 'pp'
3808
+ p options[:server]
3809
+ pp wrapped_app
3810
+ pp app
3811
+ end
3812
+
3813
+ if options[:warn]
3814
+ $-w = true
3815
+ end
3816
+
3817
+ if includes = options[:include]
3818
+ $LOAD_PATH.unshift *includes
3819
+ end
3820
+
3821
+ if library = options[:require]
3822
+ require library
3823
+ end
3824
+
3825
+ daemonize_app if options[:daemonize]
3826
+ write_pid if options[:pid]
3827
+ server.run wrapped_app, options
3828
+ end
3829
+ </ruby>
3830
+
3831
+ 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:
3832
+
3833
+ <ruby>
3834
+ def server
3835
+ @_server ||= Rack::Handler.get(options[:server]) || Rack::Handler.default
3836
+ end
3837
+ </ruby>
3838
+
3839
+ 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:
3840
+
3841
+ <ruby>
3842
+ def self.default(options = {})
3843
+ # Guess.
3844
+ if ENV.include?("PHP_FCGI_CHILDREN")
3845
+ # We already speak FastCGI
3846
+ options.delete :File
3847
+ options.delete :Port
3848
+
3849
+ Rack::Handler::FastCGI
3850
+ elsif ENV.include?("REQUEST_METHOD")
3851
+ Rack::Handler::CGI
3852
+ else
3853
+ begin
3854
+ Rack::Handler::Mongrel
3855
+ rescue LoadError => e
3856
+ Rack::Handler::WEBrick
3857
+ end
3858
+ end
3859
+ end
3860
+ </ruby>
3861
+
3862
+
3863
+ 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+.
3864
+
3865
+ (side-note: Mongrel doesn't install on 1.9. TODO: How do we format these anyway?)
3866
+
3867
+ h5. +Rack::Handler::WEBrick+
3868
+
3869
+ 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.
3870
+
3871
+
3872
+ +Rack::Server+ has handlers for the request and by default the handler for a _rails server_ server is
3873
+
3874
+ h3. Cruft!
3875
+
3876
+ The final line of _config/environment.rb_:
3877
+
3878
+ <ruby>
3879
+ YourApp::Application.initialize!
3880
+ </ruby>
3881
+
3882
+ gets down to actually initializing the application!
3883
+
3884
+ 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?
3885
+
3886
+
3887
+ 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.
3888
+
3889
+ <ruby>
3890
+ def build_app(app)
3891
+ middleware[options[:environment]].reverse_each do |middleware|
3892
+ middleware = middleware.call(self) if middleware.respond_to?(:call)
3893
+ next unless middleware
3894
+ klass = middleware.shift
3895
+ app = klass.new(app, *middleware)
3896
+ end
3897
+ app
3898
+ end
3899
+ </ruby>
3900
+
3901
+ 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.)
3902
+
3903
+ 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:
3904
+
3905
+ <ruby>
3906
+ def server
3907
+ @_server ||= Rack::Handler.get(options[:server]) || Rack::Handler.default
3908
+ end
3909
+ </ruby>
3910
+
3911
+ Since we have default options, the server is obviously going to be +Rack::Handler.default+. The +default+ method goes like this:
3912
+
3913
+ <ruby>
3914
+ def self.default(options = {})
3915
+ # Guess.
3916
+ if ENV.include?("PHP_FCGI_CHILDREN")
3917
+ # We already speak FastCGI
3918
+ options.delete :File
3919
+ options.delete :Port
3920
+
3921
+ Rack::Handler::FastCGI
3922
+ elsif ENV.include?("REQUEST_METHOD")
3923
+ Rack::Handler::CGI
3924
+ else
3925
+ begin
3926
+ Rack::Handler::Mongrel
3927
+ rescue LoadError => e
3928
+ Rack::Handler::WEBrick
3929
+ end
3930
+ end
3931
+ end
3932
+ </ruby>
3933
+
3934
+ h3. +Rails::Paths+
3935
+
3936
+
3937
+ The +super+ method it references comes from +Rails::Engine::Configuration+ which defines these paths:
3938
+
3939
+ <ruby>
3940
+ def paths
3941
+ @paths ||= begin
3942
+ paths = Rails::Paths::Root.new(@root)
3943
+ paths.app "app", :eager_load => true, :glob => "*"
3944
+ paths.app.controllers "app/controllers", :eager_load => true
3945
+ paths.app.helpers "app/helpers", :eager_load => true
3946
+ paths.app.models "app/models", :eager_load => true
3947
+ paths.app.metals "app/metal"
3948
+ paths.app.views "app/views"
3949
+ paths.lib "lib", :load_path => true
3950
+ paths.lib.tasks "lib/tasks", :glob => "**/*.rake"
3951
+ paths.lib.templates "lib/templates"
3952
+ paths.config "config"
3953
+ paths.config.initializers "config/initializers", :glob => "**/*.rb"
3954
+ paths.config.locales "config/locales", :glob => "*.{rb,yml}"
3955
+ paths.config.routes "config/routes.rb"
3956
+ paths
3957
+ end
3958
+ end
3959
+ </ruby>
3960
+
3961
+ h3. Appendix A
3962
+
3963
+ 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.
3964
+
3965
+ This file is _activesupport/lib/active_support/inflector/transliterate.rb_ and defines two methods, +transliterate+ and +parameterize+. What +transliterate+ does depends on your Ruby version. If you have something greater than 1.9 installed it will just print out a warning message using the +Kernel#warn+ method (simply called using +warn+) reading "Ruby 1.9 doesn't support Unicode normalization yet". If you're running something that's not 1.9 it will attempt to convert +"föö"+ to +foo+ and if that fails then it'll redefine it.
3966
+
3967
+ This file first makes a require to _activesupport/lib/active_support/core_ext/string/multibyte.rb_ which then goes on to require _activesupport/lib/active_support/multibyte.rb_ and that requires _activesupport/core_ext/module/attribute_accessors.rb_. The _attribute_accessors.rb_ file is used to gain access to the +mattr_accessor+ (module attribute accessor) method which is called in _active_suport/multibyte.rb_. Also in _active_support/multibyte.rb_ there's a couple of autoloaded classes:
3968
+
3969
+ <ruby>
3970
+ module ActiveSupport #:nodoc:
3971
+ module Multibyte
3972
+ autoload :EncodingError, 'active_support/multibyte/exceptions'
3973
+ autoload :Chars, 'active_support/multibyte/chars'
3974
+ autoload :UnicodeDatabase, 'active_support/multibyte/unicode_database'
3975
+ autoload :Codepoint, 'active_support/multibyte/unicode_database'
3976
+ autoload :UCD, 'active_support/multibyte/unicode_database'
3977
+ ...
3978
+ end
3979
+ end
3980
+ </ruby>
3981
+
3982
+ There's also these method definitions:
3983
+
3984
+ <ruby>
3985
+ self.default_normalization_form = :kc
3986
+
3987
+ # The proxy class returned when calling mb_chars. You can use this accessor to configure your own proxy
3988
+ # class so you can support other encodings. See the ActiveSupport::Multibyte::Chars implementation for
3989
+ # an example how to do this.
3990
+ #
3991
+ # Example:
3992
+ # ActiveSupport::Multibyte.proxy_class = CharsForUTF32
3993
+ def self.proxy_class=(klass)
3994
+ @proxy_class = klass
3995
+ end
3996
+
3997
+ # Returns the currect proxy class
3998
+ def self.proxy_class
3999
+ @proxy_class ||= ActiveSupport::Multibyte::Chars
4000
+ end
4001
+ </ruby>
4002
+
4003
+ These methods are used in _activesupport/lib/active_support/core_ext/string/multibyte.rb_.
4004
+
4005
+ If we go back to _activesupport/lib/active_support/core_ext/string/multibyte.rb_, this file makes a couple of extensions to the +String+ class based on if your version of Ruby's +String+ class responds to the +force_encoding+ method. This method was introduced in Ruby 1.9. If you're using 1.9 the methods are defined like this:
4006
+
4007
+ <ruby>
4008
+ def mb_chars #:nodoc
4009
+ self
4010
+ end
4011
+
4012
+ def is_utf8? #:nodoc
4013
+ case encoding
4014
+ when Encoding::UTF_8
4015
+ valid_encoding?
4016
+ when Encoding::ASCII_8BIT, Encoding::US_ASCII
4017
+ dup.force_encoding(Encoding::UTF_8).valid_encoding?
4018
+ else
4019
+ false
4020
+ end
4021
+ end
4022
+ </ruby>
4023
+
4024
+ You can see that calling +mb_chars+ on a +String+ instance in Ruby 1.9 will simply return that +String+ object. +String+ objects in Ruby 1.9 are already multibyte strings, so Rails does not need to do any conversion on them.
4025
+
4026
+ The second method, +is_utf8?+ return +true+ if the +String+ object is of the UTF8 encoding or if it's able to be forced into that encoding and +false+ if it can't force its encoding or if the encoding of the string is neither +UTF8+, +ASCII_8BIT+ or +US_ASCII+.
4027
+
4028
+ If you're using a Ruby version less than 1.9 there are 3 methods defined instead of 2, and they are defined like this:
4029
+
4030
+ <ruby>
4031
+ def mb_chars
4032
+ if ActiveSupport::Multibyte.proxy_class.wants?(self)
4033
+ ActiveSupport::Multibyte.proxy_class.new(self)
4034
+ else
4035
+ self
4036
+ end
4037
+ end
4038
+
4039
+ # Returns true if the string has UTF-8 semantics (a String used for purely byte resources is unlikely to have
4040
+ # them), returns false otherwise.
4041
+ def is_utf8?
4042
+ ActiveSupport::Multibyte::Chars.consumes?(self)
4043
+ end
4044
+
4045
+ unless '1.8.7 and later'.respond_to?(:chars)
4046
+ def chars
4047
+ ActiveSupport::Deprecation.warn('String#chars has been deprecated in favor of String#mb_chars.', caller)
4048
+ mb_chars
4049
+ end
4050
+ end
4051
+
4052
+ </ruby>
4053
+
4054
+
4055
+ As you can see, +mb_chars+ is where the +proxy_class+ method comes in handy. This will create a new instance of that class and pass in the +String+ object in order to make it multibyte-compatible. In this case the new +String+ object will be an instance of the +ActiveSupport::Multibyte::Chars+ class. You can use +ActiveSupport::Multibyte.proxy_class=+ to set this to be a different class if you're that way inclined.
4056
+
4057
+ Here, +is_utf8?+ calls a +consumes+ method on the not-yet-loaded +ActiveSupport::Multibyte::Chars+ class. The keen-eye would have seen this was specified as an auto-load earlier, so that is what is going to happen if we call this method or +mb_chars+. This means that it'll require the file located at _activesupport/lib/active_support/multibyte/chars.rb_. 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 and they are defined differently depending on if you're using Ruby 1.9 or not. The second file included is _activesupport/lib/active_support/string/behaviour.rb_ which defines a single method +acts_like_string?+ on +String+ which always returns +true+. This method is used through the +acts_like?+ method which is passed a single argument representing the downcased and symbolised version of the class you want to know if it acts like. In this case the code would be +acts_like?(:string)+.
4058
+
4059
+ The +Chars+ class defines, along with +consumes?+, other methods such as the "spaceship" method +<=>+. This method is referenced by the methods defined in the included +Comparable+ module and will return either +-1+, +0+ or +1+ depending on if the word is before, identical or after the compared word. For example, +'é'.mb_chars <=> 'ü'.mb_chars+ returns +-1+ as e comes before u in the alphabet. Other methods are the commonly used +split+, +=~+, +insert+ and +include?+.
4060
+
4061
+
4062
+
4063
+ h3. Common Includes
4064
+
4065
+ TODO: I feel this section would be better at the end of the guide as it breaks the flow.
4066
+
4067
+ This section is for all the common includes in the Railties.
4068
+
4069
+ h4. +require 'active_support/inflector'+
4070
+
4071
+ This file is _activesupport/lib/active_support/inflector.rb_ and makes a couple of requires out different files tasked with putting inflections in place:
4072
+
4073
+ <ruby>
4074
+ require 'active_support/inflector/inflections'
4075
+ require 'active_support/inflector/transliterate'
4076
+ require 'active_support/inflector/methods'
4077
+
4078
+ require 'active_support/inflections'
4079
+ require 'active_support/core_ext/string/inflections'
4080
+ </ruby>
4081
+
4082
+ 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 ActiveSupport Guide. TODO: Link to AS Guide.
4083
+
4084
+ h4. +require 'active_support/core_ext/module/delegation'+
4085
+
4086
+ _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:
4087
+
4088
+ <ruby>
4089
+ class Client < ActiveRecord::Base
4090
+ has_one :address
4091
+
4092
+ delegate :address_line_1, :to => :address
4093
+ end
4094
+ </ruby>
4095
+
4096
+ This defines an +address_line_1+ method which is defined as:
4097
+
4098
+ <ruby>
4099
+ def address_line_1(*args, &block)
4100
+ address.__send__(:address_line_1, *args, &block)
4101
+ rescue NoMethodError
4102
+ if address.nil?
4103
+ raise "address_line_1 is delegated to address.address_line_1, but address is nil: #{client.inspect}"
4104
+ end
4105
+ end
4106
+ </ruby>
4107
+
4108
+ h4. +require 'active_support/core_ext/class/attribute_accessors'+
4109
+
4110
+ 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.
4111
+
4112
+ Throughout the Railties there a couple of common includes. They are listed here for your convenience.
4113
+
4114
+ h4. +require 'active_support/core_ext/module/attr_internal+
4115
+
4116
+ 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.
4117
+
4118
+ h4. +require 'active_support/ruby/shim'+
4119
+
4120
+ 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:
4121
+
4122
+ * +Date#next_month+
4123
+ * +Date#next_year+
4124
+ * +DateTime#to_date+
4125
+ * +DateTime#to_datetime+
4126
+ * +DateTime#xmlschema+
4127
+ * +Enumerable#group_by+
4128
+ * +Enumerable#each_with_object+
4129
+ * +Enumerable#none?+
4130
+ * +Process#daemon+
4131
+ * +String#ord+
4132
+ * +Time#to_date+
4133
+ * +Time.to_time+
4134
+ * +Time.to_datetime+
4135
+
4136
+ For more information see the ActiveSupport Extensions guide TODO: link to relevant sections for each method.
4137
+
4138
+ And "the REXML security fix detailed here":[http://weblog.rubyonrails.org/2008/8/23/dos-vulnerabilities-in-rexml]