Class: Datacaster::Comparator

Inherits:
Base
  • Object
show all
Defined in:
lib/datacaster/comparator.rb

Instance Method Summary collapse

Methods included from Mixin

#&, #*, #call, #call_with_runtime, #cast_errors, #i18n_key, #i18n_map_keys, #i18n_scope, #i18n_vars, #then, #with_context, #with_object_context, #with_runtime, #|

Constructor Details

#initialize(value, error_key = nil) ⇒ Comparator

Returns a new instance of Comparator.



3
4
5
6
7
8
# File 'lib/datacaster/comparator.rb', line 3

def initialize(value, error_key = nil)
  @value = value

  @error_keys = ['.compare', 'datacaster.errors.compare']
  @error_keys.unshift(error_key) if error_key
end

Instance Method Details

#cast(object, runtime:) ⇒ Object



10
11
12
13
14
15
16
17
18
# File 'lib/datacaster/comparator.rb', line 10

def cast(object, runtime:)
  if @value == object
    Datacaster.ValidResult(object)
  else
    Datacaster.ErrorResult(
      I18nValues::Key.new(@error_keys, reference: @value.inspect, value: object)
    )
  end
end

#inspectObject



20
21
22
# File 'lib/datacaster/comparator.rb', line 20

def inspect
  "#<Datacaster::Comparator(#{@value.inspect})>"
end