3

So, I'm not having a problem so much as I am confused by two different conventions that I see used around the web for changing the Rails config files.

Specifically, I see these two statements used often:

config.autoload_paths << "#{Rails.root}/app/arbitrary"
config.autoload_paths += %W(#{config.root}/app/arbitrary)
config.autoload_paths += Dir["#{config.root}/app/arbitrary/**/"]

First, is there any difference n using the << operator vs the += operator? Second, is it considered a better practice to use Rails.root as opposed to config.root?

Can some of these conventions only be used in certain combinations? I just hate not knowing something so seemingly basic.

2 Answers 2

1

difference between << and +=

config.autoload_paths is an Array. For an Array object, << push ONE object to the array, while + joins two array to create a new array. So if you only have one object to be appended to the existing array, << is preferred for performance because no new object will be created. If you want to append another array to the existing array, you have to use +.

Yo know, a1 =+ a2 is equal to a1 = a1 + a2.

Rails.root v.s. config.root

Rails.root is just the root of Rails app. If config.root is used in a Rails app, it should be same as Rails.root. But it can also be used in Engines, where it will be the Engine's root. If config.root is used in a Rails app, you may not have to change it to use the app as an Engine.

0

<< adds a single value while += adds an array of values. The %w(...) notation is just a shortcut for an array of strings.

Check the source for the Rails.root method: https://github.com/rails/rails/blob/master/railties/lib/rails.rb#L83

so it uses config.root anyhow because

Rails.application.config == Rails.configuration

evaluates to true. This is also the object you get passed for the configure blocks in config/application.rb and config/environments/ files.

2
  • Your answer is basically as good, but I'm giving the check mark to the first responder. Also, his explanation of how config.root could affect Engines was good to know.
    – Bryce
    Nov 29, 2012 at 10:32
  • Please don't worry :) Thanks a lot for the consideration.
    – moritz
    Nov 29, 2012 at 13:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.