Class: Jsapi::Model::Errors

Inherits:
ActiveModel::Errors
  • Object
show all
Defined in:
lib/jsapi/model/errors.rb

Instance Method Summary collapse

Constructor Details

#initialize(base = nil) ⇒ Errors

Returns a new instance of Errors.



6
7
8
9
10
# File 'lib/jsapi/model/errors.rb', line 6

def initialize(base = nil)
  @base = base
  @path = []
  super
end

Instance Method Details

#add(attribute, type = :invalid, **options) ⇒ Object

Overrides ActiveModel::Errors#add to wrap errors related to nested models.



14
15
16
17
18
# File 'lib/jsapi/model/errors.rb', line 14

def add(attribute, type = :invalid, **options)
  type = type.call(@base, options) if type.respond_to?(:call)

  errors << wrap(Error.new(@base, attribute.to_sym, type, **options))
end

#import(error, options = {}) ⇒ Object

Overrides ActiveModel::Errors#import to wrap errors related to nested models.



22
23
24
25
26
27
28
29
# File 'lib/jsapi/model/errors.rb', line 22

def import(error, options = {})
  if (options = options.slice(:attribute, :type)).any?
    attribute = (options[:attribute] || error.attribute).to_sym
    type = options[:type] || error.raw_type
    error = Error.new(error.base, attribute, type, **error.options)
  end
  errors << wrap(error)
end

#nested(attribute, &block) ⇒ Object

Calls the block in context of attribute.



32
33
34
35
36
37
# File 'lib/jsapi/model/errors.rb', line 32

def nested(attribute, &block)
  @path.push(attribute.to_sym)
  block&.call
ensure
  @path.pop
end