Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails convention confusion for altering config files

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.

like image 997
Bryce Avatar asked Feb 01 '26 09:02

Bryce


1 Answers

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.

like image 198
Yanhao Avatar answered Feb 03 '26 01:02

Yanhao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!