Class: Schemacop::V2::Caster

Inherits:
Object
  • Object
show all
Defined in:
lib/schemacop/v2/caster.rb

Constant Summary collapse

DEFAULT_CASTERS =
{
  String  => {
    Integer => proc { |s| s.blank? ? nil : Integer(s, 10) },
    Float   => proc { |s| s.blank? ? nil : Float(s) }
  },
  Float   => {
    Integer => proc { |f| Integer(f) }
  },
  Integer => {
    Float => proc { |f| Float(f) }
  }
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(casts, data, target_type) ⇒ Caster

Returns a new instance of Caster.



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/schemacop/v2/caster.rb', line 16

def initialize(casts, data, target_type)
  @casts = casts
  @data = data
  @target_type = target_type
  @caster = nil
  @value = nil

  if casts.is_a?(Array)
    from_types = casts
  elsif casts.is_a?(Hash)
    from_types = casts.keys
  else
    fail Exceptions::InvalidSchemaError, 'Option `cast` must be either an array or a hash.'
  end

  return unless from_types.include?(data.class)

  if (casts.is_a?(Array) && casts.include?(data.class)) || casts[data.class] == :default
    @caster = DEFAULT_CASTERS[data.class][target_type]
  else
    @caster = casts[data.class]
  end
end

Instance Method Details

#castObject



44
45
46
47
48
49
50
51
# File 'lib/schemacop/v2/caster.rb', line 44

def cast
  fail 'Not castable.' unless castable?

  return @caster.call(@data)
rescue StandardError => e
  fail Exceptions::InvalidSchemaError,
       "Could not cast value #{@value.inspect} to #{@target_type}: #{e.message}."
end

#castable?Boolean

Returns:

  • (Boolean)


40
41
42
# File 'lib/schemacop/v2/caster.rb', line 40

def castable?
  !@caster.nil?
end