4

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

10
  • you can use it in model PROCEDURES_CONFIG = YAML.load_file("#{::Rails.root}/config/assessment_procedures.yml") instead of initializers Commented Sep 3, 2014 at 10:00
  • @RajarshiDas I know, but it's a bad practice to keep constants in model Commented Sep 3, 2014 at 10:02
  • I defined constants in an initializer in a rails 3.2 project with syntax MENU_CONFIG = Rails.root.join("config", "menu.yml").open { |file| YAML::load(file) } and its working quite well. Commented Sep 3, 2014 at 10:03
  • stackoverflow.com/questions/8026344/… Commented Sep 3, 2014 at 10:05
  • 1
    replace PROCEDURES_CONFIG['self_estimation_weight'] on ::PROCEDURES_CONFIG['self_estimation_weight'] Commented Sep 3, 2014 at 10:06

1 Answer 1

2

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

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

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.