Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 508 lines (436 sloc) 19.255 kb
accd9b4 Joshua Peek Restore "Start Rails::Application object
josh authored
1 module Rails
2 class Application
6d6ae08 Start moving the initializers into the application object
Carl Lerche authored
3 extend Initializable
4
e4d7e50 Moving more initializers into the application object
Carl Lerche authored
5 class << self
d859402 Joshua Peek Use Rails.initialize! where we just want to run the initializers and are...
josh authored
6 # Stub out App initialize
7 def initialize!
8 new
9 end
10
e4d7e50 Moving more initializers into the application object
Carl Lerche authored
11 def config
12 @config ||= Configuration.new
13 end
6f6a589 Create the application object from config/environment.rb
Yehuda Katz + Carl Lerche authored
14
e4d7e50 Moving more initializers into the application object
Carl Lerche authored
15 # TODO: change the plugin loader to use config
16 alias configuration config
c9d4529 Change Rails::Application to a class that is inherited from.
Carl Lerche authored
17
e4d7e50 Moving more initializers into the application object
Carl Lerche authored
18 def config=(config)
19 @config = config
20 end
c9d4529 Change Rails::Application to a class that is inherited from.
Carl Lerche authored
21
e4d7e50 Moving more initializers into the application object
Carl Lerche authored
22 def plugin_loader
23 @plugin_loader ||= config.plugin_loader.new(self)
24 end
accd9b4 Joshua Peek Restore "Start Rails::Application object
josh authored
25
bf9819f Have Rails.root be based off of config.ru
Carl Lerche authored
26 def root
27 config.root
28 end
29
e4d7e50 Moving more initializers into the application object
Carl Lerche authored
30 def routes
31 ActionController::Routing::Routes
32 end
6f6a589 Create the application object from config/environment.rb
Yehuda Katz + Carl Lerche authored
33
e4d7e50 Moving more initializers into the application object
Carl Lerche authored
34 def middleware
35 config.middleware
36 end
37
38 def call(env)
39 @app ||= middleware.build(routes)
40 @app.call(env)
41 end
6d6ae08 Start moving the initializers into the application object
Carl Lerche authored
42
e4d7e50 Moving more initializers into the application object
Carl Lerche authored
43 def new
44 initializers.run
45 self
46 end
6d6ae08 Start moving the initializers into the application object
Carl Lerche authored
47 end
48
49 initializer :initialize_rails do
50 Rails.initializers.run
51 end
52
53 # Set the <tt>$LOAD_PATH</tt> based on the value of
54 # Configuration#load_paths. Duplicates are removed.
55 initializer :set_load_path do
56 config.paths.add_to_load_path
57 $LOAD_PATH.uniq!
58 end
59
60 # Bail if boot.rb is outdated
61 initializer :freak_out_if_boot_rb_is_outdated do
62 unless defined?(Rails::BOOTSTRAP_VERSION)
63 abort %{Your config/boot.rb is outdated: Run "rake rails:update".}
64 end
65 end
e4d7e50 Moving more initializers into the application object
Carl Lerche authored
66
67 # Requires all frameworks specified by the Configuration#frameworks
68 # list. By default, all frameworks (Active Record, Active Support,
69 # Action Pack, Action Mailer, and Active Resource) are loaded.
70 initializer :require_frameworks do
71 begin
72 require 'active_support'
73 require 'active_support/core_ext/kernel/reporting'
74 require 'active_support/core_ext/logger'
75
76 # TODO: This is here to make Sam Ruby's tests pass. Needs discussion.
77 require 'active_support/core_ext/numeric/bytes'
78 config.frameworks.each { |framework| require(framework.to_s) }
79 rescue LoadError => e
80 # Re-raise as RuntimeError because Mongrel would swallow LoadError.
81 raise e.to_s
82 end
83 end
84
85 # Set the paths from which Rails will automatically load source files, and
86 # the load_once paths.
87 initializer :set_autoload_paths do
88 require 'active_support/dependencies'
89 ActiveSupport::Dependencies.load_paths = config.load_paths.uniq
90 ActiveSupport::Dependencies.load_once_paths = config.load_once_paths.uniq
91
92 extra = ActiveSupport::Dependencies.load_once_paths - ActiveSupport::Dependencies.load_paths
93 unless extra.empty?
94 abort <<-end_error
95 load_once_paths must be a subset of the load_paths.
96 Extra items in load_once_paths: #{extra * ','}
97 end_error
98 end
99
100 # Freeze the arrays so future modifications will fail rather than do nothing mysteriously
101 config.load_once_paths.freeze
102 end
103
104 # Adds all load paths from plugins to the global set of load paths, so that
105 # code from plugins can be required (explicitly or automatically via ActiveSupport::Dependencies).
106 initializer :add_plugin_load_paths do
107 require 'active_support/dependencies'
108 plugin_loader.add_plugin_load_paths
109 end
feb04bf Move the ensure_tmp_directories_exist initializer to the application obj...
Carl Lerche authored
110
111 # Create tmp directories
112 initializer :ensure_tmp_directories_exist do
113 %w(cache pids sessions sockets).each do |dir_to_make|
bf9819f Have Rails.root be based off of config.ru
Carl Lerche authored
114 FileUtils.mkdir_p(File.join(config.root, 'tmp', dir_to_make))
ed77e84 Ported over more initializers
Carl Lerche authored
115 end
116 end
117
118 # Loads the environment specified by Configuration#environment_path, which
119 # is typically one of development, test, or production.
120 initializer :load_environment do
121 silence_warnings do
122 next if @environment_loaded
123 next unless File.file?(config.environment_path)
124
125 @environment_loaded = true
126 constants = self.class.constants
127
5c42157 Even more initializers ported over
Carl Lerche authored
128 eval(IO.read(config.environment_path), binding, config.environment_path)
ed77e84 Ported over more initializers
Carl Lerche authored
129
130 (self.class.constants - constants).each do |const|
131 Object.const_set(const, self.class.const_get(const))
132 end
133 end
134 end
135
136 initializer :add_gem_load_paths do
137 require 'rails/gem_dependency'
138 Rails::GemDependency.add_frozen_gem_path
139 unless config.gems.empty?
140 require "rubygems"
141 config.gems.each { |gem| gem.add_load_paths }
142 end
143 end
144
145 # Preload all frameworks specified by the Configuration#frameworks.
146 # Used by Passenger to ensure everything's loaded before forking and
147 # to avoid autoload race conditions in JRuby.
148 initializer :preload_frameworks do
149 if config.preload_frameworks
150 config.frameworks.each do |framework|
151 # String#classify and #constantize aren't available yet.
152 toplevel = Object.const_get(framework.to_s.gsub(/(?:^|_)(.)/) { $1.upcase })
153 toplevel.load_all! if toplevel.respond_to?(:load_all!)
154 end
feb04bf Move the ensure_tmp_directories_exist initializer to the application obj...
Carl Lerche authored
155 end
156 end
5c42157 Even more initializers ported over
Carl Lerche authored
157
158 # This initialization routine does nothing unless <tt>:active_record</tt>
159 # is one of the frameworks to load (Configuration#frameworks). If it is,
160 # this sets the database configuration from Configuration#database_configuration
161 # and then establishes the connection.
162 initializer :initialize_database do
163 if config.frameworks.include?(:active_record)
164 ActiveRecord::Base.configurations = config.database_configuration
165 ActiveRecord::Base.establish_connection
166 end
167 end
168
169 # Include middleware to serve up static assets
170 initializer :initialize_static_server do
171 if config.frameworks.include?(:action_controller) && config.serve_static_assets
172 config.middleware.use(ActionDispatch::Static, Rails.public_path)
173 end
174 end
175
176 initializer :initialize_middleware_stack do
177 if config.frameworks.include?(:action_controller)
178 config.middleware.use(::Rack::Lock) unless ActionController::Base.allow_concurrency
179 config.middleware.use(ActionDispatch::ShowExceptions, ActionController::Base.consider_all_requests_local)
180 config.middleware.use(ActionDispatch::Callbacks, ActionController::Dispatcher.prepare_each_request)
181 config.middleware.use(lambda { ActionController::Base.session_store }, lambda { ActionController::Base.session_options })
182 config.middleware.use(ActionDispatch::ParamsParser)
183 config.middleware.use(::Rack::MethodOverride)
184 config.middleware.use(::Rack::Head)
185 config.middleware.use(ActionDispatch::StringCoercion)
186 end
187 end
188
189 initializer :initialize_cache do
190 unless defined?(RAILS_CACHE)
191 silence_warnings { Object.const_set "RAILS_CACHE", ActiveSupport::Cache.lookup_store(config.cache_store) }
192
193 if RAILS_CACHE.respond_to?(:middleware)
194 # Insert middleware to setup and teardown local cache for each request
195 config.middleware.insert_after(:"Rack::Lock", RAILS_CACHE.middleware)
196 end
197 end
198 end
199
200 initializer :initialize_framework_caches do
201 if config.frameworks.include?(:action_controller)
202 ActionController::Base.cache_store ||= RAILS_CACHE
203 end
204 end
205
206 initializer :initialize_logger do
207 # if the environment has explicitly defined a logger, use it
208 next if Rails.logger
209
210 unless logger = config.logger
211 begin
212 logger = ActiveSupport::BufferedLogger.new(config.log_path)
213 logger.level = ActiveSupport::BufferedLogger.const_get(config.log_level.to_s.upcase)
214 if RAILS_ENV == "production"
215 logger.auto_flushing = false
216 end
217 rescue StandardError => e
218 logger = ActiveSupport::BufferedLogger.new(STDERR)
219 logger.level = ActiveSupport::BufferedLogger::WARN
220 logger.warn(
221 "Rails Error: Unable to access log file. Please ensure that #{config.log_path} exists and is chmod 0666. " +
222 "The log level has been raised to WARN and the output directed to STDERR until the problem is fixed."
223 )
224 end
225 end
226
227 # TODO: Why are we silencing warning here?
228 silence_warnings { Object.const_set "RAILS_DEFAULT_LOGGER", logger }
229 end
230
231 # Sets the logger for Active Record, Action Controller, and Action Mailer
232 # (but only for those frameworks that are to be loaded). If the framework's
233 # logger is already set, it is not changed, otherwise it is set to use
234 # RAILS_DEFAULT_LOGGER.
235 initializer :initialize_framework_logging do
236 for framework in ([ :active_record, :action_controller, :action_mailer ] & config.frameworks)
237 framework.to_s.camelize.constantize.const_get("Base").logger ||= Rails.logger
238 end
239
240 ActiveSupport::Dependencies.logger ||= Rails.logger
241 Rails.cache.logger ||= Rails.logger
242 end
243
244 # Sets the dependency loading mechanism based on the value of
245 # Configuration#cache_classes.
246 initializer :initialize_dependency_mechanism do
247 # TODO: Remove files from the $" and always use require
248 ActiveSupport::Dependencies.mechanism = config.cache_classes ? :require : :load
249 end
250
251 # Loads support for "whiny nil" (noisy warnings when methods are invoked
252 # on +nil+ values) if Configuration#whiny_nils is true.
253 initializer :initialize_whiny_nils do
254 require('active_support/whiny_nil') if config.whiny_nils
255 end
256
257 # Sets the default value for Time.zone, and turns on ActiveRecord::Base#time_zone_aware_attributes.
258 # If assigned value cannot be matched to a TimeZone, an exception will be raised.
259 initializer :initialize_time_zone do
260 if config.time_zone
261 zone_default = Time.__send__(:get_zone, config.time_zone)
262
263 unless zone_default
264 raise \
265 'Value assigned to config.time_zone not recognized.' +
266 'Run "rake -D time" for a list of tasks for finding appropriate time zone names.'
267 end
268
269 Time.zone_default = zone_default
270
271 if config.frameworks.include?(:active_record)
272 ActiveRecord::Base.time_zone_aware_attributes = true
273 ActiveRecord::Base.default_timezone = :utc
274 end
275 end
276 end
277
278 # Set the i18n configuration from config.i18n but special-case for the load_path which should be
279 # appended to what's already set instead of overwritten.
280 initializer :initialize_i18n do
281 config.i18n.each do |setting, value|
282 if setting == :load_path
283 I18n.load_path += value
284 else
285 I18n.send("#{setting}=", value)
286 end
287 end
288 end
992c2db Finish porting over the initializers to the app object and fix all the t...
Carl Lerche authored
289
290 # Initializes framework-specific settings for each of the loaded frameworks
291 # (Configuration#frameworks). The available settings map to the accessors
292 # on each of the corresponding Base classes.
293 initializer :initialize_framework_settings do
294 config.frameworks.each do |framework|
295 base_class = framework.to_s.camelize.constantize.const_get("Base")
296
297 config.send(framework).each do |setting, value|
298 base_class.send("#{setting}=", value)
299 end
300 end
301 config.active_support.each do |setting, value|
302 ActiveSupport.send("#{setting}=", value)
303 end
304 end
305
306 # Sets +ActionController::Base#view_paths+ and +ActionMailer::Base#template_root+
307 # (but only for those frameworks that are to be loaded). If the framework's
308 # paths have already been set, it is not changed, otherwise it is
309 # set to use Configuration#view_path.
310 initializer :initialize_framework_views do
311 if config.frameworks.include?(:action_view)
312 view_path = ActionView::PathSet.type_cast(config.view_path, config.cache_classes)
313 ActionMailer::Base.template_root = view_path if config.frameworks.include?(:action_mailer) && ActionMailer::Base.view_paths.blank?
314 ActionController::Base.view_paths = view_path if config.frameworks.include?(:action_controller) && ActionController::Base.view_paths.blank?
315 end
316 end
317
318 initializer :initialize_metal do
319 # TODO: Make Rails and metal work without ActionController
320 if config.frameworks.include?(:action_controller)
321 Rails::Rack::Metal.requested_metals = config.metals
322 Rails::Rack::Metal.metal_paths += plugin_loader.engine_metal_paths
323
324 config.middleware.insert_before(
325 :"ActionDispatch::ParamsParser",
326 Rails::Rack::Metal, :if => Rails::Rack::Metal.metals.any?)
327 end
328 end
329
330 initializer :check_for_unbuilt_gems do
331 unbuilt_gems = config.gems.select {|gem| gem.frozen? && !gem.built? }
332 if unbuilt_gems.size > 0
333 # don't print if the gems:build rake tasks are being run
334 unless $gems_build_rake_task
335 abort <<-end_error
336 The following gems have native components that need to be built
337 #{unbuilt_gems.map { |gemm| "#{gemm.name} #{gemm.requirement}" } * "\n "}
338
339 You're running:
340 ruby #{Gem.ruby_version} at #{Gem.ruby}
341 rubygems #{Gem::RubyGemsVersion} at #{Gem.path * ', '}
342
343 Run `rake gems:build` to build the unbuilt gems.
344 end_error
345 end
346 end
347 end
348
349 initializer :load_gems do
350 unless $gems_rake_task
351 config.gems.each { |gem| gem.load }
352 end
353 end
354
355 # Loads all plugins in <tt>config.plugin_paths</tt>. <tt>plugin_paths</tt>
356 # defaults to <tt>vendor/plugins</tt> but may also be set to a list of
357 # paths, such as
bf9819f Have Rails.root be based off of config.ru
Carl Lerche authored
358 # config.plugin_paths = ["#{config.root}/lib/plugins", "#{config.root}/vendor/plugins"]
992c2db Finish porting over the initializers to the app object and fix all the t...
Carl Lerche authored
359 #
360 # In the default implementation, as each plugin discovered in <tt>plugin_paths</tt> is initialized:
361 # * its +lib+ directory, if present, is added to the load path (immediately after the applications lib directory)
362 # * <tt>init.rb</tt> is evaluated, if present
363 #
364 # After all plugins are loaded, duplicates are removed from the load path.
365 # If an array of plugin names is specified in config.plugins, only those plugins will be loaded
366 # and they plugins will be loaded in that order. Otherwise, plugins are loaded in alphabetical
367 # order.
368 #
369 # if config.plugins ends contains :all then the named plugins will be loaded in the given order and all other
370 # plugins will be loaded in alphabetical order
371 initializer :load_plugins do
372 plugin_loader.load_plugins
373 end
374
375 # TODO: Figure out if this needs to run a second time
376 # load_gems
377
378 initializer :check_gem_dependencies do
379 unloaded_gems = config.gems.reject { |g| g.loaded? }
380 if unloaded_gems.size > 0
381 configuration.gems_dependencies_loaded = false
382 # don't print if the gems rake tasks are being run
383 unless $gems_rake_task
384 abort <<-end_error
385 Missing these required gems:
386 #{unloaded_gems.map { |gemm| "#{gemm.name} #{gemm.requirement}" } * "\n "}
387
388 You're running:
389 ruby #{Gem.ruby_version} at #{Gem.ruby}
390 rubygems #{Gem::RubyGemsVersion} at #{Gem.path * ', '}
391
392 Run `rake gems:install` to install the missing gems.
393 end_error
394 end
395 else
396 configuration.gems_dependencies_loaded = true
397 end
398 end
399
400 # # bail out if gems are missing - note that check_gem_dependencies will have
401 # # already called abort() unless $gems_rake_task is set
402 # return unless gems_dependencies_loaded
403
404 initializer :load_application_initializers do
405 if config.gems_dependencies_loaded
bf9819f Have Rails.root be based off of config.ru
Carl Lerche authored
406 Dir["#{configuration.root}/config/initializers/**/*.rb"].sort.each do |initializer|
992c2db Finish porting over the initializers to the app object and fix all the t...
Carl Lerche authored
407 load(initializer)
408 end
409 end
410 end
411
412 # Fires the user-supplied after_initialize block (Configuration#after_initialize)
413 initializer :after_initialize do
414 if config.gems_dependencies_loaded
415 configuration.after_initialize_blocks.each do |block|
416 block.call
417 end
418 end
419 end
420
421 # # Setup database middleware after initializers have run
422 initializer :initialize_database_middleware do
423 if configuration.frameworks.include?(:active_record)
424 if configuration.frameworks.include?(:action_controller) && ActionController::Base.session_store &&
425 ActionController::Base.session_store.name == 'ActiveRecord::SessionStore'
426 configuration.middleware.insert_before :"ActiveRecord::SessionStore", ActiveRecord::ConnectionAdapters::ConnectionManagement
427 configuration.middleware.insert_before :"ActiveRecord::SessionStore", ActiveRecord::QueryCache
428 else
429 configuration.middleware.use ActiveRecord::ConnectionAdapters::ConnectionManagement
430 configuration.middleware.use ActiveRecord::QueryCache
431 end
432 end
433 end
434
435 # TODO: Make a DSL way to limit an initializer to a particular framework
436
437 # # Prepare dispatcher callbacks and run 'prepare' callbacks
438 initializer :prepare_dispatcher do
439 next unless configuration.frameworks.include?(:action_controller)
440 require 'rails/dispatcher' unless defined?(::Dispatcher)
441 Dispatcher.define_dispatcher_callbacks(configuration.cache_classes)
442 end
443
444 # Routing must be initialized after plugins to allow the former to extend the routes
445 # ---
446 # If Action Controller is not one of the loaded frameworks (Configuration#frameworks)
447 # this does nothing. Otherwise, it loads the routing definitions and sets up
448 # loading module used to lazily load controllers (Configuration#controller_paths).
449 initializer :initialize_routing do
450 next unless configuration.frameworks.include?(:action_controller)
451
452 ActionController::Routing.controller_paths += configuration.controller_paths
453 ActionController::Routing::Routes.add_configuration_file(configuration.routes_configuration_file)
454 ActionController::Routing::Routes.reload!
455 end
456 #
457 # # Observers are loaded after plugins in case Observers or observed models are modified by plugins.
458 initializer :load_observers do
459 if config.gems_dependencies_loaded && configuration.frameworks.include?(:active_record)
460 ActiveRecord::Base.instantiate_observers
461 end
462 end
463
464 # Eager load application classes
465 initializer :load_application_classes do
466 next if $rails_rake_task
467
468 if configuration.cache_classes
469 configuration.eager_load_paths.each do |load_path|
470 matcher = /\A#{Regexp.escape(load_path)}(.*)\.rb\Z/
471 Dir.glob("#{load_path}/**/*.rb").sort.each do |file|
472 require_dependency file.sub(matcher, '\1')
473 end
474 end
475 end
476 end
477
478 # Disable dependency loading during request cycle
479 initializer :disable_dependency_loading do
480 if configuration.cache_classes && !configuration.dependency_loading
481 ActiveSupport::Dependencies.unhook!
482 end
483 end
484
485 # Configure generators if they were already loaded
486 # ===
487 # TODO: Does this need to be an initializer here?
488 initializer :initialize_generators do
489 if defined?(Rails::Generators)
490 Rails::Generators.no_color! unless config.generators.colorize_logging
491 Rails::Generators.aliases.deep_merge! config.generators.aliases
492 Rails::Generators.options.deep_merge! config.generators.options
493 end
494 end
aeaabc6 José Valim Configure Orchestra on initialization.
josevalim authored
495
2d7abe2 José Valim Renamed Orchestra to Notifications once again [#3321 state:resolved]
josevalim authored
496 # For each framework, search for instrument file with Notifications hooks.
aeaabc6 José Valim Configure Orchestra on initialization.
josevalim authored
497 #
2d7abe2 José Valim Renamed Orchestra to Notifications once again [#3321 state:resolved]
josevalim authored
498 initializer :load_notifications_hooks do
aeaabc6 José Valim Configure Orchestra on initialization.
josevalim authored
499 config.frameworks.each do |framework|
500 begin
2d7abe2 José Valim Renamed Orchestra to Notifications once again [#3321 state:resolved]
josevalim authored
501 require "#{framework}/notifications"
aeaabc6 José Valim Configure Orchestra on initialization.
josevalim authored
502 rescue LoadError => e
503 end
504 end
505 end
accd9b4 Joshua Peek Restore "Start Rails::Application object
josh authored
506 end
507 end
Something went wrong with that request. Please try again.