如何在Rails 4中存储自定义常量? [英] How do you store custom constants in Rails 4?

查看:60
本文介绍了如何在Rails 4中存储自定义常量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对电子邮件,bitmessage等做了一些正则表达式,并将它们作为常量

I made some regular expressions for email, bitmessage etc. and put them as constants to

#config/initializers/regexps.rb
REGEXP_EMAIL = /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
REGEXP_BITMESSAGE = /\ABM-[a-zA-Z1-9&&[^OIl]]{32,34}\z/

并使用它

if @user.contact =~ REGEXP_EMAIL
elsif @user.contact =~ REGEXP_BITMESSAGE

这是一个好习惯?最好的存储方式是什么?

Is that's good practice? What's the best way to store them?

推荐答案

这很有意义,这是可能的方法之一。这种方法的唯一缺点是常量将污染全局名称空间。

It makes sense, that's one of the possible approaches. The only downside of this approach, is that the constants will pollute the global namespace.

我通常更喜欢的方法是在应用程序名称空间中定义它们。

The approach that I normally prefer is to define them inside the application namespace.

假设您的应用程序名为 Fooapp ,那么您已经有一个 Fooapp 由Rails定义的模块(请参见 config / application )。

Assuming your application is called Fooapp, then you already have a Fooapp module defined by Rails (see config/application).

我通常创建一个 fooapp.rb 文件位于 lib 内,如下所示

I normally create a fooapp.rb file inside lib like the following

module Fooapp
end

,然后将常量放入其中。此外,请确保在您的底部 application.rb 文件

and I drop the constants inside. Also make sure to require it at the bottom of you application.rb file

require 'fooapp'

在这种情况下,文件的延迟加载将无法进行,因为 Fooapp 模块已经定义。

Lazy-loading of the file will not work in this case, because the Fooapp module is already defined.

当常量的数量足够大时,可以将它们更多地放入一个单独的常量中。文件,例如 /lib/fooapp/constants.rb 。这最后一步只是将所有常量分组到一个简单位置的简单改进(尽管 Ruby 2.1 Frozen String字面量的改进可能会让我删除几个常量)。

When the number of constants become large enough, you can more them into a separate file, for example /lib/fooapp/constants.rb. This last step is just a trivial improvement to group all the constants into one simple place (I tend to use constants a lot to replace magic numbers or for optimization, despite Ruby 2.1 Frozen String literal improvements will probably let me remove several constants).

还有一件事情。就您而言,如果正则表达式特定于一个模型,则可以将其存储在模型本身中并创建模型方法

One more thing. In your case, if the regexp is specific to one model, you can store it inside the model itself and create a model method

class User

  REGEXP_EMAIL = /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
  REGEXP_BITMESSAGE = /\ABM-[123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ]{32,34}\z/

  def contact_is_email?
    contact =~ REGEXP_EMAIL
  end

end

这篇关于如何在Rails 4中存储自定义常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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