0Day Forums
Dynamic constant definition in Rails - Printable Version

+- 0Day Forums (https://zeroday.vip)
+-- Forum: Coding (https://zeroday.vip/Forum-Coding)
+--- Forum: Ruby (https://zeroday.vip/Forum-Ruby)
+--- Thread: Dynamic constant definition in Rails (/Thread-Dynamic-constant-definition-in-Rails)



Dynamic constant definition in Rails - ellanellard793 - 07-19-2023

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.


RE: Dynamic constant definition in Rails - albertype689 - 07-19-2023

I've stumbled on this as I was trying to do "dynamic constants".

My goal is to be able to use a specific database entry as a constant. (Once inserted, the line will never change on a specific instance but ids can be different on different instances).

I came up with a solution that could apply to this case depending on why you're trying to have dynamic constants. Here's an example in my usecase but it's fairly easy to replace the attribute definition by something else.

<!-- language: rails -->

class MyModel < ActiveRecord::Base
def self.MY_CONST
@my_const ||= MyModel.find_by(code: 'my_const_code')
end
end

And here's how i tested it:

require 'test_helper'

class MyModelTest < ActiveSupport::TestCase
test "mymodel constant defined" do
assert_equal MyModel.find_by(code: 'my_const_code'), MyModel.MY_CONST
end
end



RE: Dynamic constant definition in Rails - odaliscpi - 07-19-2023

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



RE: Dynamic constant definition in Rails - helm785662 - 07-19-2023

Maybe autoloading in development mode is the problem?

Your model class is recreated for every request, so you would need to create the constant again and again.

The problem would just disappear in production mode. You may turn off the autoloading in development mode, but this will force you to restart the server after every change in your code.

See config/environments/development.rb: `config.cache_classes = false` (change to true).