Sha256: 893b4687e52fc3f71a9f453de94eff170851cdec6dfd18b1ce12327daad48d8b

Contents?: true

Size: 965 Bytes

Versions: 1

Compression:

Stored size: 965 Bytes

Contents

class PresenceAtLeastOneValidator < ActiveModel::EachValidator
  # Validates that AT LEAST ONE of the specified attributes are not blank (as defined by Object#blank?).
  #
  # ==== Examples
  #
  #    class Product < ActiveRecord::Base
  #       validates :name, :price, :presence_at_least_one => true
  #    end
  #
  #    >> product = Product.new
  #    >> product.valid?
  #    => false
  #    >> [product.errors[:name], :product.errors[:price]]
  #    => ['presence_at_least_one translate message error', 'presence_at_least_one translate message error']
  #
  #    >> product.name = 'Donate a Macbook to Tomas!'
  #    >> product.valid?
  #    => true
  #
  def validate(record)
    if all_specified_attributes_are_blank?(record)
      attributes.each { |attribute| record.errors.add(attribute, :presence_at_least_one) }
    end
  end

  def all_specified_attributes_are_blank?(record)
    attributes.all? { |attribute| record.send(attribute).blank? }
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
presence_at_least_one_validator-0.1.0 lib/presence_at_least_one_validator.rb