Johnny Wong Johnny Wong - 1 year ago 123
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
Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download