Sha256: 99d3367c0b810d0a2251e5939363a9feb5ecb5f464f63627f39fae877c7d2212

Contents?: true

Size: 1.29 KB

Versions: 1

Compression:

Stored size: 1.29 KB

Contents

module ValidatesFormattingOf
  module ModelAdditions

    # Using validates_formatting_of is as simple as using Rails' built-in
    # validation methods in models.
    #
    # class User < ActiveRecord::Base
    #   validates_formatting_of :email, :using => :email
    # end
    #
    # This call will ensure that the user-provided email is a valid email. This way,
    # you will not need to find or write your own regex to validate. All of that
    # logic is contained within `validates_formatting_of`
    def validates_formatting_of(attribute, opts={})
      regex_for_validation = opts[:regex] || validate_with(opts[:using])
      validation_message = opts[:message] || ValidationMessages.message(opts[:using])
      options = {
        :format => {
          :with => regex_for_validation,
          :message => validation_message,
        }
      }
      options.merge!(:allow_nil => opts[:allow_nil]) unless opts[:allow_nil].nil?
      options.merge!(:allow_blank => opts[:allow_blank]) unless opts[:allow_blank].nil?
      validates(attribute, options)
    end

  private

    def validate_with(method)
      # Actually retrieve the regex to check against
      formatting.send(method)
    end

    def formatting
      # Grab the validating methods
      @formatting ||= ValidatingMethods.new
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
validates_formatting_of-0.3.7 lib/validates_formatting_of/model_additions.rb