Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you store custom constants in Rails 4?

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?

like image 970
br. Avatar asked Dec 25 '13 10:12

br.


People also ask

How to define constant in Rails?

A constant is a type of variable which always starts with a capital letter. They can only be defined outside of methods, unless you use metaprogramming. Constants are used for values that aren't supposed to change, but Ruby doesn't prevent you from changing them.

How do you find the constants in Ruby?

Ruby Constants Constants begin with an uppercase letter. Constants defined within a class or module can be accessed from within that class or module, and those defined outside a class or module can be accessed globally. Constants may not be defined within methods.


1 Answers

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
like image 161
Simone Carletti Avatar answered Sep 19 '22 06:09

Simone Carletti