Sha256: 6afff5e84b7f44feb5e9efbfd40b77d5653b09d0f5a8f6ee8027e771f36b38ad

Contents?: true

Size: 977 Bytes

Versions: 7

Compression:

Stored size: 977 Bytes

Contents

module Schemacop
  class Caster
    def initialize(casts, data, target_type)
      @casts = casts
      @data = data
      @target_type = target_type
      @caster = 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

    def castable?
      !@caster.nil?
    end

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

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
schemacop-2.4.7 lib/schemacop/caster.rb
schemacop-2.4.6 lib/schemacop/caster.rb
schemacop-2.4.5 lib/schemacop/caster.rb
schemacop-2.4.4 lib/schemacop/caster.rb
schemacop-2.4.3 lib/schemacop/caster.rb
schemacop-2.4.2 lib/schemacop/caster.rb
schemacop-2.4.1 lib/schemacop/caster.rb