DEV Community

n350071đŸ‡ŻđŸ‡”
n350071đŸ‡ŻđŸ‡”

Posted on

a common validations concern in Rails

đŸ€” Situation

1. a common validations for multiple models

When you have some models that need to validate for e-mail, policy_agreement, user_name, tel_number, and so on, do you want to write almost the same things for many models?

2. the names of the same meaning column is different!

It's like this.

  • User#email
  • Company#mail_address

Is it possible to make them common?

🩄 We have a great tool ActiveSupport::Concern!

module CommonValidation
  extend ActiveSupport::Concern

  included do
    # This is for not the columns, but the screen items.
    attr_accessor :mail_address_confirmation
    attr_accessor :policy_agreement

    # This is for situation 1
    validates :name, length: { maximum: 16}
    validates :policy_agreement, acceptance: true, allow_nil: false, on: :with_policy_agreement

    # This is for situation 2
    # obj in the Proc.new is dinamically determine, it will be the very object of the validated model.
    [:email ,:mail_address].each do |column|
      validates column, format: { with: Regexp.new(Constants::EmailRegex) }, if: Proc.new { |obj| obj.respond_to?(column) }
    end
  end

end

🔗 Parent Note

Top comments (0)