Module: Varify::Base

Defined in:
lib/varify/base.rb

Constant Summary collapse

RULES =
{
  required: Varify::Rules::RequiredRule,
  is_a:     Varify::Rules::IsARule,
  one_of:   Varify::Rules::OneOfRule,
  between:  Varify::Rules::BetweenRule
}

Class Method Summary collapse

Class Method Details

.callback {|| ... } ⇒ Object

Sets the callback for when a validation fails

Parameters:

  • &block (Proc)

    the callback to run when validation fails

Yield Parameters:



20
21
22
# File 'lib/varify/base.rb', line 20

def self.callback(&block)
  @callback = block
end

.fail(options = {}) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Used by the varify method to send error messages to the callback

Parameters:

  • options (Hash) (defaults to: {})

    the information to post for the error

Options Hash (options):

  • :message (String)

    the user readable message

  • :key (Symbol)

    the key of the value to get from the Hashh

  • :rule (Symbol)

    the Rule ID from RULES



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/varify/base.rb', line 30

def self.fail(options={})
  message = options.is_a?(String) ? options : options[:message]
  raise "Fail (fail) requires a string message or hash with :message" unless message
  raise "Key (:key) is required in calling fail" unless options[:key]
  raise "Rule (:rule) is required in calling fail" unless options[:rule]

  error = {
    message: message,
    key:     options[:key],
    rule:    options[:rule]
  }

  if @callback
    @callback.call(error)
  else
    raise ArgumentError, message
  end
end

.varify(param_key, params = {}, options = {}, &block) ⇒ Object

Processes the input parameter

Parameters:

  • Varify::Base.callback (Symbol)

    the key to identify the value out of the hash

  • params (Hash) (defaults to: {})

    the hash of keys

  • options (Hash) (defaults to: {})

    set of rules to test

  • &block (Proc)

    optional block to use as a validator



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/varify/base.rb', line 54

def self.varify(param_key, params={}, options={},&block)
  value    = params[param_key] || options[:default]
  name     = params[:name] || param_key.to_s.split('_').map{|e| e.capitalize}.join(' ')
  required = options[:required]
  rules    = {}

  rules_to_process = options.dup
  rules_to_process.delete(:default)
  rules_to_process.delete(:name)

  if value || required
    rules_to_process.each do |rule_key,rule_value|
      rule_class = RULES[rule_key]
      raise "Rule ':#{rule_key}' is not defined" unless rule_class
      rules[rule_key] = rule_class.new(param_key,name,value,rule_value)
    end

    rules.each do |rule_key,rule|
      fail(message: rule.error_message, key: param_key, rule:rule_key) unless rule.valid?
    end
  end

  value
end