Sha256: a7f35b1e75e8f18e3ff39877f9e206814368bf31ee206f059adc23692a0c1a82

Contents?: true

Size: 1.31 KB

Versions: 32

Compression:

Stored size: 1.31 KB

Contents

module Schemacop::V2
  class Caster
    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

    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

    def castable?
      !@caster.nil?
    end

    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
  end
end

Version data entries

32 entries across 32 versions & 1 rubygems

Version Path
schemacop-3.0.29 lib/schemacop/v2/caster.rb
schemacop-3.0.28 lib/schemacop/v2/caster.rb
schemacop-3.0.27 lib/schemacop/v2/caster.rb
schemacop-3.0.26 lib/schemacop/v2/caster.rb
schemacop-3.0.25 lib/schemacop/v2/caster.rb
schemacop-3.0.24 lib/schemacop/v2/caster.rb
schemacop-3.0.23 lib/schemacop/v2/caster.rb
schemacop-3.0.22 lib/schemacop/v2/caster.rb
schemacop-3.0.21 lib/schemacop/v2/caster.rb
schemacop-3.0.20 lib/schemacop/v2/caster.rb
schemacop-3.0.19 lib/schemacop/v2/caster.rb
schemacop-3.0.18 lib/schemacop/v2/caster.rb
schemacop-3.0.17 lib/schemacop/v2/caster.rb
schemacop-3.0.16 lib/schemacop/v2/caster.rb
schemacop-3.0.15 lib/schemacop/v2/caster.rb
schemacop-3.0.14 lib/schemacop/v2/caster.rb
schemacop-3.0.13 lib/schemacop/v2/caster.rb
schemacop-3.0.12 lib/schemacop/v2/caster.rb
schemacop-3.0.11 lib/schemacop/v2/caster.rb
schemacop-3.0.10 lib/schemacop/v2/caster.rb