How do you store custom constants in Rails 4?

匆匆过客 提交于 2019-12-18 19:33:35

问题


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/

and use it like

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

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


回答1:


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.

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

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

module Fooapp
end

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

require 'fooapp'

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

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


来源:https://stackoverflow.com/questions/20771822/how-do-you-store-custom-constants-in-rails-4

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