简体   繁体   中英

Ruby on Rails, load constants from YAML?

I'm interested in opinions / best practice on loading constants from a YAML from config/initializers. Currently these constants are loaded into a class variable where the service class inherits from self so that they can be accessed like so.

    ClassName.MY_CONSTANT 

    class ClassName
      class << self
        attr_accessor :MY_CONSTANT
      end
    end

The initialization looks like this.

    YADA YADA YAML LOADING
    ClassName.MY_CONSTANT = yaml_config[:my_constant] || 1800

My issue with this (one of my issues with this), is that this make rails fairly brittle. During development, if I touch anything in a controller, the libs are reloaded and so this CONSTANT becomes nil.

What's the best way to set a constant like this. It has to do with caching and so can never be nil?

It seems that you are describing a class level accessor, not a constant. I'm assuming that you wish to set the MY_CONSTANT once at boot/initialize time and the value is really a constant.

One approach is to use a global constant, and then set the class constant to the value of that global constant, eg :

# config/initializers/load_yaml_constant.rb

load_yaml_sometime_during_initialization
::CLASSNAME_MY_CONSTANT = yaml_config[:my_constant] || 1800

# my_class.rb
class MyClass
  MY_CONSTANT = ::CLASSNAME_MY_CONSTANT
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM