Ruby on Rails: Where to define global constants?

前端 未结 12 1765
我在风中等你
我在风中等你 2020-11-28 00:44

I\'m just getting started with my first Ruby on Rails webapp. I\'ve got a bunch of different models, views, controllers, and so on.

I\'m wanting to find a good plac

12条回答
  •  再見小時候
    2020-11-28 01:33

    As of Rails 4.2, you can use the config.x property:

    # config/application.rb (or config/custom.rb if you prefer)
    config.x.colours.options = %w[white blue black red green]
    config.x.colours.default = 'white'
    

    Which will be available as:

    Rails.configuration.x.colours.options
    # => ["white", "blue", "black", "red", "green"]
    Rails.configuration.x.colours.default
    # => "white"
    

    Another method of loading custom config:

    # config/colours.yml
    default: &default
      options:
        - white
        - blue
        - black
        - red
        - green
      default: white
    development:
      *default
    production:
      *default
    
    # config/application.rb
    config.colours = config_for(:colours)
    
    Rails.configuration.colours
    # => {"options"=>["white", "blue", "black", "red", "green"], "default"=>"white"}
    Rails.configuration.colours['default']
    # => "white"
    

    In Rails 5 & 6, you can use the configuration object directly for custom configuration, in addition to config.x. However, it can only be used for non-nested configuration:

    # config/application.rb
    config.colours = %w[white blue black red green]
    

    It will be available as:

    Rails.configuration.colours
    # => ["white", "blue", "black", "red", "green"]
    

提交回复
热议问题