在 Ruby on Rails 应用程序中定义常量的最佳位置在哪里? [英] Where's the best place to define a constant in a Ruby on Rails application?

查看:16
本文介绍了在 Ruby on Rails 应用程序中定义常量的最佳位置在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Ruby on Rails 应用程序中,哪里是定义常量的最佳位置?

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.

推荐答案

Rails >= 3,应用程序本身就是一个模块(位于 config/application.rb 中).您可以将它们存储在应用程序模块中

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

然后使用 MyApplication::SUPER_SECRET_TOKEN 来引用常量.

Then use MyApplication::SUPER_SECRET_TOKEN to reference the constant.

导轨 >= 2.1 &&<3 你应该放置它们

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

  1. /config/initializers 当常量具有应用程序范围时
  2. 当常量引用特定的模型/控制器/帮助器时,您可以在类/模块本身内限定它
  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

<小时>

在 Rails 2.1 和 initializers 支持之前,程序员习惯于将应用程序常量放在 environment.rb 中.


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

这里有几个例子

# 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

这篇关于在 Ruby on Rails 应用程序中定义常量的最佳位置在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆