Johnny Wong Johnny Wong - 7 months ago 42
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

file, with this content:

KB = 1000

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

MB = KB * KB

Is this possible?

gen gen

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'

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

Then in your class you can use your constant:

class Something
  include Constants
  MB = KB * KB

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