class WeakHeaders::BaseValidator

Public Class Methods

new(controller, key, options = {}, &block) click to toggle source
# File lib/weak_headers/base_validator.rb, line 3
def initialize(controller, key, options = {}, &block)
  @controller = controller
  @key        = key.to_s
  @options    = options
  @block      = block
end

Public Instance Methods

type() click to toggle source
# File lib/weak_headers/base_validator.rb, line 14
def type
  self.class.name.split('::').last.sub(/Validator\z/, '').underscore.to_sym
end
validate() click to toggle source
# File lib/weak_headers/base_validator.rb, line 10
def validate
  handle_failure unless valid?
end

Private Instance Methods

blank?() click to toggle source
# File lib/weak_headers/base_validator.rb, line 51
def blank?
  headers.nil? || headers[@key].blank?
end
error_message() click to toggle source
# File lib/weak_headers/base_validator.rb, line 82
def error_message
  "request.headers[#{@key.inspect}] must be a valid value"
end
exceptional?() click to toggle source
# File lib/weak_headers/base_validator.rb, line 67
def exceptional?
  case
  when @options[:only].try(:exclude?, value)
    true
  when @options[:except].try(:include?, value)
    true
  else
    false
  end
end
handle_failure() click to toggle source
# File lib/weak_headers/base_validator.rb, line 43
def handle_failure
  if has_handler?
    @controller.send(@options[:handler])
  else
    raise_error
  end
end
has_handler?() click to toggle source
# File lib/weak_headers/base_validator.rb, line 86
def has_handler?
  !!@options[:handler]
end
headers() click to toggle source
# File lib/weak_headers/base_validator.rb, line 35
def headers
  @controller.request.headers
end
optional?() click to toggle source
# File lib/weak_headers/base_validator.rb, line 63
def optional?
  type == :optional
end
present?() click to toggle source
# File lib/weak_headers/base_validator.rb, line 55
def present?
  !blank?
end
raise_error() click to toggle source
# File lib/weak_headers/base_validator.rb, line 78
def raise_error
  raise WeakHeaders::ValidationError, error_message
end
requires?() click to toggle source
# File lib/weak_headers/base_validator.rb, line 59
def requires?
  type == :requires
end
valid?() click to toggle source
# File lib/weak_headers/base_validator.rb, line 20
def valid?
  case
  when requires? && blank?
    false
  when present? && exceptional?
    false
  when requires? && @block && !@block.call(value)
    false
  when optional? && present? && @block && !@controller.instance_exec(value, &@block)
    false
  else
    true
  end
end
value() click to toggle source
# File lib/weak_headers/base_validator.rb, line 39
def value
  headers[@key]
end