class Schemacop::V2::Caster
Constants
- DEFAULT_CASTERS
Public Class Methods
new(casts, data, target_type)
click to toggle source
# 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
Public Instance Methods
cast()
click to toggle source
# 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?()
click to toggle source
# File lib/schemacop/v2/caster.rb, line 40 def castable? !@caster.nil? end