Class: Validation::Validator

Inherits:
Object
  • Object
show all
Includes:
Rules
Defined in:
lib/validation/validator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Rules

#validates_confirmation_of, #validates_format_of, #validates_greather_or_equal_then, #validates_greather_then, #validates_length_of_within, #validates_less_or_equal_then, #validates_less_then, #validates_numericality_of, #validates_presence_of

Constructor Details

#initializeValidator

Returns a new instance of Validator.



7
8
9
10
# File 'lib/validation/validator.rb', line 7

def initialize
  @rules = []
  @errors = {}
end

Instance Attribute Details

#errorsObject (readonly)

Returns the value of attribute errors.



5
6
7
# File 'lib/validation/validator.rb', line 5

def errors
  @errors
end

Instance Method Details

#valid?Boolean

Returns:

  • (Boolean)


25
26
27
# File 'lib/validation/validator.rb', line 25

def valid?
  @errors.empty?
end

#validate(data) ⇒ Object



16
17
18
19
20
21
22
23
# File 'lib/validation/validator.rb', line 16

def validate data
  @errors = {}
  @rules.each do |rule|
    next if @errors[rule[:message].field]
    @errors[rule[:message].field] = rule[:message] unless rule[:callback].call(data)
  end
  valid?
end

#validates(field, callback, message) ⇒ Object



12
13
14
# File 'lib/validation/validator.rb', line 12

def validates(field, callback, message)
  @rules << {:callback => callback, :message => Error.new(field, message)}
end