Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 723 Vote(s) - 3.52 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dynamic constant definition in Rails

#1
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.
Reply

#2
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
Reply

#3
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
Reply

#4
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).
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through