module Lipstick::AutoValidation::ClassMethods

Constants

VALIDATOR_TRANSLATORS

Public Class Methods

extended(base) click to toggle source
# File lib/lipstick/auto_validation.rb, line 6
def self.extended(base)
  return if base.respond_to?(:validators)

  raise('Lipstick::AutoValidation requires a class which responds' \
        ' to the `validators` method. For example, as provided by' \
        ' ActiveModel::Validations')
end

Public Instance Methods

lipstick_auto_validators() click to toggle source
# File lib/lipstick/auto_validation.rb, line 14
def lipstick_auto_validators
  validators.each_with_object({}) do |validator, map|
    validator.attributes.each do |attr|
      out = lipstick_validator(attr, validator)
      next if out.nil?

      map[attr.to_sym] ||= {}
      map[attr.to_sym].merge!(out)
    end
  end
end
lipstick_field_name(attr) click to toggle source
# File lib/lipstick/auto_validation.rb, line 26
def lipstick_field_name(attr)
  map = @lipstick_field_names || {}
  return map[attr] if map.key?(attr)

  attr.to_s.humanize(capitalize: false)
end

Private Instance Methods

lipstick_length_validator(_attr, validator, humanized) click to toggle source
# File lib/lipstick/auto_validation.rb, line 56
def lipstick_length_validator(_attr, validator, humanized)
  min = validator.options[:minimum]
  max = validator.options[:maximum]

  min_message = "Please enter a longer value for #{humanized} " \
                "(minimum #{min} characters)"
  max_message = "Please enter a shorter value for #{humanized} " \
                "(maximum #{max} characters)"

  {}.tap do |out|
    out[:minlength] = { param: min, message: min_message } if min
    out[:maxlength] = { param: max, message: max_message } if max
  end
end
lipstick_numericality_validator(_attr, _validator, humanized) click to toggle source
# File lib/lipstick/auto_validation.rb, line 71
def lipstick_numericality_validator(_attr, _validator, humanized)
  { digits: { message: "Please enter a numeric value for #{humanized}" } }
end
lipstick_presence_validator(_attr, _validator, humanized) click to toggle source
# File lib/lipstick/auto_validation.rb, line 52
def lipstick_presence_validator(_attr, _validator, humanized)
  { required: { message: "Please enter a value for #{humanized}" } }
end
lipstick_validator(attr, validator) click to toggle source
# File lib/lipstick/auto_validation.rb, line 43
def lipstick_validator(attr, validator)
  VALIDATOR_TRANSLATORS.each do |klass, sym|
    next unless validator.is_a?(klass)

    return send(sym, attr, validator, lipstick_field_name(attr.to_sym))
  end
  nil
end