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

查看:63
本文介绍了在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 引用常量

Rails> = 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 支持之前,程序员习惯于将应用程序常量放置在环境中。 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天全站免登陆