Module: Valentine

Defined in:
lib/valentine.rb

Defined Under Namespace

Classes: ValentineError, ValentineNote

Constant Summary collapse

VERSION =
"0.3.0"
DEFAULT_MESSAGES =
{ 
      :proc => "Failed to pass validation test.",
      :array => "Collection failed to pass validation.",
      :true => "Required key missing.",
      :false => "Key forbidden in this context",
      :value => "Invalid value."
}

Class Method Summary collapse

Class Method Details

.doublecheck(value, rule, msg = true, at = nil, msgs = {}) ⇒ Object



76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/valentine.rb', line 76

def self::doublecheck(value, rule, msg=true, at=nil, msgs={})
  msgs.merge!(DEFAULT_MESSAGES)
  case rule
  when Hash then value.respond_to?(:[]) && self::validate(value, rule)
  when Proc
    begin
      r = rule.call(value)
      if r.is_a? Exception
        return r
      else
        Valentine::expectation r, msgs[:proc], msg, at
      end
    rescue Exception => e
      return e
    end
  when Array
    valid = true
    value.is_a?(Array) && rule.each_index do |i| 
      valid &&= self::doublecheck(value[i], rule[i])
    end
    self::expectation valid, msgs[:array], msg, at
  when true
   self::expectation !value.nil?, msgs[:true], msg, at
  when false
    self::expectation value.nil?, msgs[:false], msg, at
  when nil then true
  else 
    self::expectation rule === value, msgs[:value], msg, at
  end
end

.expectation(r, m = "", msg = true, at = nil) ⇒ Object



68
69
70
71
72
73
74
# File 'lib/valentine.rb', line 68

def self::expectation(r, m="", msg=true, at=nil) 
  if r
    true
  else
    msg ? ValentineError.new([at, m] * ': ') : false
  end
end

.judge(valentine) ⇒ Object



107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/valentine.rb', line 107

def self::judge(valentine)
  if valentine.is_a? ValentineNote
    self::judge(valentine.validate)
  else
    valentine.values.inject(true) do |s, v|
      case v
      when Hash then s && self::judge(v)
      when Exception then s && false
      else s && v
      end
    end
  end
end

.validate(defendant, rules = {}, report = true, msgs = {}) ⇒ Object

Module Utility Methods follow.



54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/valentine.rb', line 54

def self::validate(defendant, rules={}, report=true, msgs={})
  return defendant.validate if defendant.is_a? ValentineNote
  errors = {}
  rules.each do |a, rule|
    begin
      result = Valentine::doublecheck(defendant[a], rule, report, a, msgs)
      errors[a] = result
    rescue Exception => e
      errors[a] = e
    end
  end
  report ? errors : self::judge(errors)
end