What is the best way to refactor validation logic and regular expressions in rails?
Let's say you have several models that contain fields for address, postal code, province/country, phone number, etc.
These are rather common fields that have specific regular expression validations. If you put the same validations and regular expressions in each model, it is duplicated. Also, the tests are duplicated. This is a smell ;)
What is the best approach using ruby and rails to refa开发者_开发知识库ctor these types of things? A module?
In Java with Hibernate, we'd use a Component class to store the address, and then we'd put the validation logic there. Each model that wanted to use an address would simply contain one, and it will get all the address validation logic.
What is the approach to achieve the same thing in rails? Thanks!
Build custom validators for the various types of validations you need, then invoke them in your model classes.
For example:
class PostalCodeValidator < ActiveModel::EachValidator def validate_each(record, attr_name, value) unless value =~ /^\d{5}$/ record.errors[attr_name] << "must be a 5-digit postal code" end end
Now use that validation in each model class and for each attribute that is a postal code. For instance, if you Customer has an attribute postal_code:
class Customer < ActiveRecord::Base validates :postal_code, :postal_code => true end
There's more detail and lots of fancy options, so I suggest a Google search on rails custom validators.
精彩评论