How do you store custom constants in Rails 4?

后端 未结 1 976
攒了一身酷
攒了一身酷 2021-01-04 10: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         


        
相关标签:
1条回答
  • 2021-01-04 11:03

    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
    
    0 讨论(0)
提交回复
热议问题