0

I want to inject a custom property (hash map) into my Rails.application.config. It seems that the way to do it is simply to assign a new variable in environment.rb:

Rails.application.config.feature_map = { :email => true }

I need to access this map through various places in my application, like the user model, controllers, and rake tasks.

Other gems, like devise, also need access to this. The problem is that adding it to environment.rb seems to be too early in the application life-cycle.

I have code in initializers/devise.rb like this:

if Rails.application.config.feature_map[:email] = true

The server complains that this field doesn't exist.

I also use it to add additional validation in my user model:

if Rails.application.config.feature_map.enabled?(:username)
validates_length_of :username, :in => 3..50

I also get a runtime error here about undefined feature Rails.application.config.feature_map

Where can I move this so that I can access it as early as in initializers and in my model class? I tried moving it into a new initializers/feature_map.rb file, but that didn't work either.

3 Answers 3

2

Put it in config/application.rb:

module MyRailsApp
  class Application < Rails::Application
    config.feature_map = ActiveSupport::OrderedOptions.new
    config.feature_map.email = true
  end
end

Anything you set in there will be default for all environments, but can be overridden per environment in config/environments/*.rb.

Sign up to request clarification or add additional context in comments.

1 Comment

Excellent, thanks. FeatureMap is a class in lib for me, so I have to use require "#{config.root}/lib/feature_map". It works great, thanks.
0

Gems like Figaro and .env will help you load up your config even before the loading of initializer.rb

Unless there is a strong reason that you wouldn't wanna use environment variables, I would recommend using either of those gems since they are the recommended way of adding your custom configs.

1 Comment

I prefer a simpler approach over adding more gems. Thanks though.
0

Edit: See Jimmy Cuadra's answer above, which I ended up going with.

I found an alternative solution: this answer to manipulate the order of initializers.

I can rename my initializer to 00_feature_map.rb and it loads first.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.