Rails: constant in initializer

I want to store constants in an initializer and use it in a model, for example:

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 I am using it. I am getting an exception:

NameError: uninitialized constant AssessmentProcedure::PROCEDURES_CONFIG

      

What did I miss? Thanks to

+3


source to share


1 answer


try it

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

      

it will zero out the constant and use the global namespace



There is a much cleaner way in Rail 4.2

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

      

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

0


source







All Articles