Using the Rails Application Configuration Variable in a Model

I defined user configuration options in my rails application (hash APP_CONFIG). OK, now how can I use these variables in my models? By directly calling APP_CONFIG ['variable'] in models, these are not rails! For example, I can use these models without the Rails framework. Then APP_CONFIG will not be defined.

ATM I use a model observer and assign global configuration variables with instance variables, for example:

def after_initialize model
  Mongoid.observers.disable :all do
    model.user_id = APP_CONFIG['user_id'])
    model.variable = User.find(model.user_id).variable
  end
end

But this solution looks like a monkey patch. Is there a better way?

Or should I keep it simple and can just define the APP_CONFIG hash in a new application (not a Rails application)?

+5
source share
3 answers

. , , :

class Something
  def initialize(config = APP_CONFIG)
    @config = config
  end
end

config , :

def something(config = APP_CONFIG)
  # do something
end

Ruby . / .

/ Rails:

def something(config = Rails.config)
  # do something
end
+2

/config/config.yml

defaults: &defaults
  user_id :100

development:
  <<: *defaults

test:
  <<: *defaults

production:
  <<: *defaults

/config/initializers/app_config.rb

APP_CONFIG = YAML.load_file("#{Rails.root}/config/config.yml")[Rails.env]

APP_CONFIG['user_id']

0

Use :before_createto localize the code in your model:

class MyModel < ActiveRecord::Base

  before_create :set_config

  private

  def set_config
    self.app_config = APP_CONFIG
  end
end

Or, alternatively, you can use ActiveSupport::Concern, which is a very clean way to create a module that could be used well in N models:

class MyModel < ActiveRecord::Base    
  include AppConfig     
end

module AppConfig
    extend ActiveSupport::Concern

    included do
       #...
    end

    module ClassMethods
       #...
    end

    def app_config
      APP_CONFIG
    end
end
0
source

All Articles