Where's the best place to define a constant in a Ruby on Rails application?

安稳与你 提交于 2019-12-28 08:07:20

问题


In a Ruby on Rails application, where is the best place to define a constant?

I have an array of constant data that I need available across all the controllers in my application.


回答1:


Rails >= 3, the application is itself a module (living in config/application.rb). You can store them in the application module

module MyApplication
  SUPER_SECRET_TOKEN = "123456"
end

Then use MyApplication::SUPER_SECRET_TOKEN to reference the constant.


Rails >= 2.1 && < 3 you should place them

  1. in /config/initializers when the constant has the applications scope
  2. when the constant refers to a specific model/controller/helper you can scope it within the class/module itself

Prior to Rails 2.1 and initializers support, programmers were used to place application constants in environment.rb.

Here's a few examples

# config/initializers/constants.rb
SUPER_SECRET_TOKEN = "123456"

# helpers/application_helper.rb
module ApplicationHelper
  THUMBNAIL_SIZE= "100x20"

  def thumbnail_tag(source, options = {})
    image_tag(source, options.merge(:size => THUMBNAIL_SIZE)
  end

end



回答2:


You can place them in config/environment.rb:

Rails::Initializer.run do |config|
    ...
    SITE_NAME = 'example.com'
end

If you have large amounts of global constants, this can be messy. Consider sourcing from a YAML file, or keeping the constants in the database.

EDIT:

weppos' answer is the better answer.

Keep your constants in a file in config/initializers/*.rb



来源:https://stackoverflow.com/questions/1107782/wheres-the-best-place-to-define-a-constant-in-a-ruby-on-rails-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!