Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic constant definition in Rails

I'm defining a constant in an initializer in Rails using the following syntax:

MyModule.const_set('MYCONSTANT','foobar')

It works, if I start a console and write

MyModule::MYCONSTANT 

I receive foobar as expected.

The problem is, when I try to call it in a Model the constant is not there.

Where should D dynamically define my constant that it can be available as well in my models?

If I statically define it in my lib/mymodule.rb it works but I would like to define some constants at runtime.

like image 214
VP. Avatar asked Nov 23 '10 12:11

VP.


1 Answers

if you want to keep config.cache_classes = false, you can put

MyModule.const_set('MYCONSTANT','foobar')

into following block in application.rb:

config.to_prepare do
MyModule.const_set('MYCONSTANT','foobar')
end
like image 83
Peter V. Avatar answered Sep 17 '22 13:09

Peter V.