application.rb 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. require 'active_support/core_ext/hash/reverse_merge'
  2. require 'fileutils'
  3. require 'rails/plugin'
  4. require 'rails/engine'
  5. module Rails
  6. # In Rails 3.0, a Rails::Application object was introduced which is nothing more than
  7. # an Engine but with the responsibility of coordinating the whole boot process.
  8. #
  9. # == Initialization
  10. #
  11. # Rails::Application is responsible for executing all railties, engines and plugin
  12. # initializers. It also executes some bootstrap initializers (check
  13. # Rails::Application::Bootstrap) and finishing initializers, after all the others
  14. # are executed (check Rails::Application::Finisher).
  15. #
  16. # == Configuration
  17. #
  18. # Besides providing the same configuration as Rails::Engine and Rails::Railtie,
  19. # the application object has several specific configurations, for example
  20. # "allow_concurrency", "cache_classes", "consider_all_requests_local", "filter_parameters",
  21. # "logger", "reload_plugins" and so forth.
  22. #
  23. # Check Rails::Application::Configuration to see them all.
  24. #
  25. # == Routes
  26. #
  27. # The application object is also responsible for holding the routes and reloading routes
  28. # whenever the files change in development.
  29. #
  30. # == Middlewares
  31. #
  32. # The Application is also responsible for building the middleware stack.
  33. #
  34. # == Booting process
  35. #
  36. # The application is also responsible for setting up and executing the booting
  37. # process. From the moment you require "config/application.rb" in your app,
  38. # the booting process goes like this:
  39. #
  40. # 1) require "config/boot.rb" to setup load paths
  41. # 2) require railties and engines
  42. # 3) Define Rails.application as "class MyApp::Application < Rails::Application"
  43. # 4) Run config.before_configuration callbacks
  44. # 5) Load config/environments/ENV.rb
  45. # 6) Run config.before_initialize callbacks
  46. # 7) Run Railtie#initializer defined by railties, engines and application.
  47. # One by one, each engine sets up its load paths, routes and runs its config/initializers/* files.
  48. # 9) Custom Railtie#initializers added by railties, engines and applications are executed
  49. # 10) Build the middleware stack and run to_prepare callbacks
  50. # 11) Run config.before_eager_load and eager_load if cache classes is true
  51. # 12) Run config.after_initialize callbacks
  52. #
  53. class Application < Engine
  54. autoload :Bootstrap, 'rails/application/bootstrap'
  55. autoload :Configuration, 'rails/application/configuration'
  56. autoload :Finisher, 'rails/application/finisher'
  57. autoload :Railties, 'rails/application/railties'
  58. autoload :RoutesReloader, 'rails/application/routes_reloader'
  59. class << self
  60. def inherited(base)
  61. raise "You cannot have more than one Rails::Application" if Rails.application
  62. super
  63. Rails.application = base.instance
  64. Rails.application.add_lib_to_load_path!
  65. ActiveSupport.run_load_hooks(:before_configuration, base.instance)
  66. end
  67. end
  68. attr_accessor :assets, :sandbox
  69. alias_method :sandbox?, :sandbox
  70. attr_reader :reloaders
  71. delegate :default_url_options, :default_url_options=, :to => :routes
  72. def initialize
  73. super
  74. @initialized = false
  75. @reloaders = []
  76. end
  77. # This method is called just after an application inherits from Rails::Application,
  78. # allowing the developer to load classes in lib and use them during application
  79. # configuration.
  80. #
  81. # class MyApplication < Rails::Application
  82. # require "my_backend" # in lib/my_backend
  83. # config.i18n.backend = MyBackend
  84. # end
  85. #
  86. # Notice this method takes into consideration the default root path. So if you
  87. # are changing config.root inside your application definition or having a custom
  88. # Rails application, you will need to add lib to $LOAD_PATH on your own in case
  89. # you need to load files in lib/ during the application configuration as well.
  90. def add_lib_to_load_path! #:nodoc:
  91. path = config.root.join('lib').to_s
  92. $LOAD_PATH.unshift(path) if File.exists?(path)
  93. end
  94. def require_environment! #:nodoc:
  95. environment = paths["config/environment"].existent.first
  96. require environment if environment
  97. end
  98. # Reload application routes regardless if they changed or not.
  99. def reload_routes!
  100. routes_reloader.reload!
  101. end
  102. def routes_reloader #:nodoc:
  103. @routes_reloader ||= RoutesReloader.new
  104. end
  105. # Returns an array of file paths appended with a hash of directories-extensions
  106. # suitable for ActiveSupport::FileUpdateChecker API.
  107. def watchable_args
  108. files = []
  109. files.concat config.watchable_files
  110. dirs = {}
  111. dirs.merge! config.watchable_dirs
  112. ActiveSupport::Dependencies.autoload_paths.each do |path|
  113. dirs[path.to_s] = [:rb]
  114. end
  115. [files, dirs]
  116. end
  117. # Initialize the application passing the given group. By default, the
  118. # group is :default but sprockets precompilation passes group equals
  119. # to assets if initialize_on_precompile is false to avoid booting the
  120. # whole app.
  121. def initialize!(group=:default) #:nodoc:
  122. raise "Application has been already initialized." if @initialized
  123. run_initializers(group, self)
  124. @initialized = true
  125. self
  126. end
  127. # Load the application and its railties tasks and invoke the registered hooks.
  128. # Check <tt>Rails::Railtie.rake_tasks</tt> for more info.
  129. def load_tasks(app=self)
  130. initialize_tasks
  131. super
  132. self
  133. end
  134. # Load the application console and invoke the registered hooks.
  135. # Check <tt>Rails::Railtie.console</tt> for more info.
  136. def load_console(app=self)
  137. initialize_console
  138. super
  139. self
  140. end
  141. # Rails.application.env_config stores some of the Rails initial environment parameters.
  142. # Currently stores:
  143. #
  144. # * action_dispatch.parameter_filter" => config.filter_parameters,
  145. # * action_dispatch.secret_token" => config.secret_token,
  146. # * action_dispatch.show_exceptions" => config.action_dispatch.show_exceptions
  147. #
  148. # These parameters will be used by middlewares and engines to configure themselves.
  149. #
  150. def env_config
  151. @env_config ||= super.merge({
  152. "action_dispatch.parameter_filter" => config.filter_parameters,
  153. "action_dispatch.secret_token" => config.secret_token,
  154. "action_dispatch.show_exceptions" => config.action_dispatch.show_exceptions,
  155. "action_dispatch.show_detailed_exceptions" => config.consider_all_requests_local,
  156. "action_dispatch.logger" => Rails.logger,
  157. "action_dispatch.backtrace_cleaner" => Rails.backtrace_cleaner
  158. })
  159. end
  160. # Returns the ordered railties for this application considering railties_order.
  161. def ordered_railties #:nodoc:
  162. @ordered_railties ||= begin
  163. order = config.railties_order.map do |railtie|
  164. if railtie == :main_app
  165. self
  166. elsif railtie.respond_to?(:instance)
  167. railtie.instance
  168. else
  169. railtie
  170. end
  171. end
  172. all = (railties.all - order)
  173. all.push(self) unless (all + order).include?(self)
  174. order.push(:all) unless order.include?(:all)
  175. index = order.index(:all)
  176. order[index] = all
  177. order.reverse.flatten
  178. end
  179. end
  180. def initializers #:nodoc:
  181. Bootstrap.initializers_for(self) +
  182. super +
  183. Finisher.initializers_for(self)
  184. end
  185. def config #:nodoc:
  186. @config ||= Application::Configuration.new(find_root_with_flag("config.ru", Dir.pwd))
  187. end
  188. def to_app
  189. self
  190. end
  191. def helpers_paths #:nodoc:
  192. config.helpers_paths
  193. end
  194. def call(env)
  195. env["ORIGINAL_FULLPATH"] = build_original_fullpath(env)
  196. super(env)
  197. end
  198. protected
  199. alias :build_middleware_stack :app
  200. def reload_dependencies?
  201. config.reload_classes_only_on_change != true || reloaders.map(&:updated?).any?
  202. end
  203. def default_middleware_stack
  204. ActionDispatch::MiddlewareStack.new.tap do |middleware|
  205. if rack_cache = config.action_controller.perform_caching && config.action_dispatch.rack_cache
  206. require "action_dispatch/http/rack_cache"
  207. middleware.use ::Rack::Cache, rack_cache
  208. end
  209. if config.force_ssl
  210. require "rack/ssl"
  211. middleware.use ::Rack::SSL, config.ssl_options
  212. end
  213. if config.serve_static_assets
  214. middleware.use ::ActionDispatch::Static, paths["public"].first, config.static_cache_control
  215. end
  216. middleware.use ::Rack::Lock unless config.allow_concurrency
  217. middleware.use ::Rack::Runtime
  218. middleware.use ::Rack::MethodOverride
  219. middleware.use ::ActionDispatch::RequestId
  220. middleware.use ::Rails::Rack::Logger, config.log_tags # must come after Rack::MethodOverride to properly log overridden methods
  221. middleware.use ::ActionDispatch::ShowExceptions, config.exceptions_app || ActionDispatch::PublicExceptions.new(Rails.public_path)
  222. middleware.use ::ActionDispatch::DebugExceptions
  223. middleware.use ::ActionDispatch::RemoteIp, config.action_dispatch.ip_spoofing_check, config.action_dispatch.trusted_proxies
  224. if config.action_dispatch.x_sendfile_header.present?
  225. middleware.use ::Rack::Sendfile, config.action_dispatch.x_sendfile_header
  226. end
  227. unless config.cache_classes
  228. app = self
  229. middleware.use ::ActionDispatch::Reloader, lambda { app.reload_dependencies? }
  230. end
  231. middleware.use ::ActionDispatch::Callbacks
  232. middleware.use ::ActionDispatch::Cookies
  233. if config.session_store
  234. if config.force_ssl && !config.session_options.key?(:secure)
  235. config.session_options[:secure] = true
  236. end
  237. middleware.use config.session_store, config.session_options
  238. middleware.use ::ActionDispatch::Flash
  239. end
  240. middleware.use ::ActionDispatch::ParamsParser
  241. middleware.use ::ActionDispatch::Head
  242. middleware.use ::Rack::ConditionalGet
  243. middleware.use ::Rack::ETag, "no-cache"
  244. if config.action_dispatch.best_standards_support
  245. middleware.use ::ActionDispatch::BestStandardsSupport, config.action_dispatch.best_standards_support
  246. end
  247. end
  248. end
  249. def initialize_tasks #:nodoc:
  250. self.class.rake_tasks do
  251. require "rails/tasks"
  252. task :environment do
  253. $rails_rake_task = true
  254. require_environment!
  255. end
  256. end
  257. end
  258. def initialize_console #:nodoc:
  259. require "pp"
  260. require "rails/console/app"
  261. require "rails/console/helpers"
  262. end
  263. def build_original_fullpath(env)
  264. path_info = env["PATH_INFO"]
  265. query_string = env["QUERY_STRING"]
  266. script_name = env["SCRIPT_NAME"]
  267. if query_string.present?
  268. "#{script_name}#{path_info}?#{query_string}"
  269. else
  270. "#{script_name}#{path_info}"
  271. end
  272. end
  273. end
  274. end