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