Sha256: 5935414eab6b1832b4bba73926120c2206cb6f991f5d522a4ca19529624ded65

Contents?: true

Size: 1.42 KB

Versions: 3

Compression:

Stored size: 1.42 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`
    # 
    # You can also pass conditions and options for Rails to use
    # * :if
    # * :unless
    # * :allow_nil
    # * :allow_blank
    # * :on
    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,
        }
      }
      %w(allow_nil allow_blank if unless on).each do |opt|
        options.merge!(opt.to_sym => opts[opt.to_sym]) if opts[opt.to_sym].present?
      end
      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

3 entries across 3 versions & 1 rubygems

Version Path
validates_formatting_of-0.5.0 lib/validates_formatting_of/model_additions.rb
validates_formatting_of-0.4.1 lib/validates_formatting_of/model_additions.rb
validates_formatting_of-0.4.0 lib/validates_formatting_of/model_additions.rb