There are a couple of ways you could do this, I prefer to store global constants is under the initializer folder.
For example:
Create an initializer file as /config/initializers/my_constants.rb
class MyConstants
MAX_LENGTH = 100
##.. other constants
end
After this use it in your models as:
validates :email, length: { maximum: MyConstants::MAX_LENGTH }
Please note every time you update this initializer file with new global constants, you must restart with rails s
to reload the changes.
Say you have two models User
with attributes username
and email
and Campaign
with attributes name
and email
- This approach would be more useful, when you need somewhat same validation to attributes with same/ different names across different models i.e., in the above case you can apply same validation for both
User#email
andCampaign#email
. Also, you have the freedom to use same validations forUser#username
andCampaign#name
even though they are named differently. - Even in cases when you need one option (say
minimum
inlength
validation) to have same value BUT another option(saymaximum
inlength
validation) to have different values. Say in case ofUser#username
andCampaign#name
, you needminimum to be 2 characters
for both andmaximum
ofUser#username
to be30
andminimum
ofCampaign#name
to be50
then you can achieve that easily.
Like I said, you can achieve this in various ways. Another approach suggested by @CaptChrisD is also good for the case where you need exactly same validation and you don't plan on tweaking it in future anyhow.
In that case you can make use of ActiveSupport::Concern
You would need to place the module in app/models/concerns
directory and name the file as email_validation.rb
.
module EmailValidation
extend ActiveSupport::Concern
included do
validates :email, length: { minimum: 5, maximum: 100 }
end
end
After this you would need to include the module in the models where you need the same validation on email
field.
class MyModel < ActiveRecord::Base
include EmailValidation ## Add this
##..
end
This is an excellent read on Ruby Mixins & ActiveSupport::Concern for your reference.
You can also check out this SO Answer: Rails put validation in a module mixin?