Reputation: 2872
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.
Upvotes: 3
Views: 70
Reputation: 25757
<<
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.
Upvotes: 0
Reputation: 5294
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.
Upvotes: 1