Johnny Wong Johnny Wong - 3 months ago 23
Ruby Question

In Ruby on Rails, how to make global constants autoreloadable in development mode, without server restart?

E.g. Currently I put global constants in the

config/initializers/constants.rb
file, with this content:

KB = 1000


I want my app to immediately recognize
MB
when I add this line, without server restart:

MB = KB * KB


Is this possible?

gen gen
Answer

Initializers are designed to fire only once on the initialization of the app. If you want something reloadable, put it in a separate module inside lib folder. Here is a full topic about Autoloading and Reloading Constants:

  module Colors
    RED = '0xff0000'
  end

Note, you will also have to adjust your application.rb with

 config.autoload_paths << "#{Rails.root}/lib"

So, for your case it would be a file constants.rb inside lib:

module Constants
  KB = 1000
end

Then in your class you can use your constant:

class Something
  include Constants
  MB = KB * KB
end

Here MB will change if you change the value of KB on page reload, and it will not require a restart.