Pavel
Pavel

Reputation: 1974

Rails: constant in initializer

I want to keep constants in initializer and use it in model like:

model:

class AssessmentProcedure < ActiveRecord::Base

  def default_values
    self.self_estimation_weight ||= PROCEDURES_CONFIG['self_estimation_weight']
    self.parent_estimation_weight ||= PROCEDURES_CONFIG['parent_estimation_weight']
  end

end

config/initializers/constants.rb

PROCEDURES_CONFIG = YAML.load_file("#{::Rails.root}/config/assessment_procedures.yml")

The problem is when I use it I get an exception:

NameError: uninitialized constant AssessmentProcedure::PROCEDURES_CONFIG

What did I miss? Thanks

Upvotes: 4

Views: 2821

Answers (1)

dre-hh
dre-hh

Reputation: 8044

try

self.self_estimation_weight ||= ::PROCEDURES_CONFIG['self_estimation_weight']

it will unscope the constant and use the global namespace

In Rail 4.2 there is a much cleaner way

# config/environments/production.rb
config.x.procedures_config.self_estimation_weight = 4711

See http://edgeguides.rubyonrails.org/4_2_release_notes.html about custom configuration options

Upvotes: 2

Related Questions