Class: Errapi::ValidationContext

Inherits:
Object
  • Object
show all
Defined in:
lib/errapi/validation_context.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ ValidationContext

Returns a new instance of ValidationContext.



8
9
10
11
12
# File 'lib/errapi/validation_context.rb', line 8

def initialize options = {}
  @errors = []
  @data = OpenStruct.new options[:data] || {}
  @config = options[:config]
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



6
7
8
# File 'lib/errapi/validation_context.rb', line 6

def config
  @config
end

#dataObject (readonly)

Returns the value of attribute data.



4
5
6
# File 'lib/errapi/validation_context.rb', line 4

def data
  @data
end

#errorsObject (readonly)

Returns the value of attribute errors.



5
6
7
# File 'lib/errapi/validation_context.rb', line 5

def errors
  @errors
end

Instance Method Details

#add_error(options = {}) {|error| ... } ⇒ Object

Yields:

  • (error)


14
15
16
17
18
19
20
21
22
# File 'lib/errapi/validation_context.rb', line 14

def add_error options = {}, &block

  error = options.kind_of?(Errapi::ValidationError) ? options : @config.new_error(options)
  yield error if block_given?
  @config.build_error error, self

  @errors << error
  self
end

#clearObject



33
34
35
36
# File 'lib/errapi/validation_context.rb', line 33

def clear
  @errors.clear
  @data = OpenStruct.new
end

#errors?(criteria = {}, &block) ⇒ Boolean

Returns:

  • (Boolean)


24
25
26
27
# File 'lib/errapi/validation_context.rb', line 24

def errors? criteria = {}, &block
  return !@errors.empty? if criteria.empty? && !block
  block ? @errors.any?{ |err| err.matches?(criteria) && block.call(err) } : @errors.any?{ |err| err.matches?(criteria) }
end

#serializeObject

TODO: add custom serialization options



39
40
41
42
43
44
45
46
47
48
# File 'lib/errapi/validation_context.rb', line 39

def serialize
  # TODO: add hook for plugins to serialize context
  { errors: [] }.tap do |h|
    @errors.each do |error|
      serialized = {}
      @config.serialize_error error, serialized
      h[:errors] << serialized
    end
  end
end

#valid?Boolean

Returns:

  • (Boolean)


29
30
31
# File 'lib/errapi/validation_context.rb', line 29

def valid?
  !errors?
end