Sha256: b6331b1f205d9ea43af7b9e8e0165bf4fc874c6b3f9ef56c295b1e5679ecd4dd

Contents?: true

Size: 1.33 KB

Versions: 2

Compression:

Stored size: 1.33 KB

Contents

require 'dry/types/builder'
require 'dry/types/result'
require 'dry/types/options'

module Dry
  module Types
    class Definition
      include Dry::Equalizer(:primitive, :options)
      include Options
      include Builder

      attr_reader :options

      attr_reader :primitive

      def self.[](primitive)
        if primitive == ::Array
          Types::Array
        elsif primitive == ::Hash
          Types::Hash
        else
          self
        end
      end

      def initialize(primitive, options = {})
        super
        @primitive = primitive
        freeze
      end

      def name
        primitive.name
      end

      def call(input)
        input
      end
      alias_method :[], :call

      def try(input, &block)
        if valid?(input)
          success(input)
        else
          failure = failure(input, "#{input.inspect} must be an instance of #{primitive}")
          block ? yield(failure) : failure
        end
      end

      def success(*args)
        result(Result::Success, *args)
      end

      def failure(*args)
        result(Result::Failure, *args)
      end

      def result(klass, *args)
        klass.new(*args)
      end

      def primitive?(value)
        value.is_a?(primitive)
      end
      alias_method :valid?, :primitive?
    end
  end
end

require 'dry/types/array'
require 'dry/types/hash'

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
dry-types-0.7.2 lib/dry/types/definition.rb
dry-types-0.7.1 lib/dry/types/definition.rb