简体   繁体   中英

explanation of application.rb file in Rails App

I'm trying to get a deeper understanding of how a rails app initializes. I'm looking over the config/application.rb file and I'm confused by these three lines:

require_relative 'boot'

require 'rails/all'

Bundler.require(*Rails.groups)

From what I can tell all three of these lines are loading the gems used by the Rails Application. boot.rb appears to load all the gems as does Bundler.require(*Rails.groups) . Why is it necessary to have all three lines of code?

Mostly correct, and you can verify what is "needed" by disabling one line at a time in a working Rails app.

  • require_relative 'boot' : Application still runs.
  • require 'rails/all' : Method not found error for a gem not listed in my Gemfile (one of Rails' built-ins (require 'rails/all')
  • Bundler.require(*Rails.groups) : Method not found for gem from Gemfile.

So, the second and third are independent and essential. boot.rb's call to bundler/setup cannot stand in for either of the other two, because its function is actually to clean the load path by making sure that only Gemfile gems are included, and everything else is removed. See the last line of the Bundler setup source . So, while the app runs, it could be running with access to other gems that you did not intend to include, and give you a false sense that the app is working when it could fail for another user who only installed the Gemfile dependencies .

So you may get away with only the second and third in the short term, but would definitely want all three on anything that someone else may someday have to execute. The overhead is minimal so I would not remove any of these.

require_relative 'boot'

Sets up Bundler and load paths for gems

require 'rails/all'

This loads the rails gems. It can be replaced in order to explicitly require only the rails gems that you need (ie require "action_mailer/railtie "

Bundler.require(*Rails.groups)

This requires gems listed in your Gemfile by default. If you remove this line, you would have to require each gem by hand.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM