File: lax.rb

package info (click to toggle)
ruby-dry-types 1.2.2-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 504 kB
  • sloc: ruby: 3,059; makefile: 4
file content (78 lines) | stat: -rw-r--r-- 1,682 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# frozen_string_literal: true

require 'dry/core/deprecations'
require 'dry/types/decorator'

module Dry
  module Types
    # Lax types rescue from type-related errors when constructors fail
    #
    # @api public
    class Lax
      include Type
      include Decorator
      include Builder
      include Printable
      include Dry::Equalizer(:type, inspect: false, immutable: true)

      undef :options, :constructor

      # @param [Object] input
      #
      # @return [Object]
      #
      # @api public
      def call(input)
        type.call_safe(input) { |output = input| output }
      end
      alias_method :[], :call
      alias_method :call_safe, :call
      alias_method :call_unsafe, :call

      # @param [Object] input
      # @param [#call,nil] block
      #
      # @yieldparam [Failure] failure
      # @yieldreturn [Result]
      #
      # @return [Result,Logic::Result]
      #
      # @api public
      def try(input, &block)
        type.try(input, &block)
      rescue CoercionError => e
        result = failure(input, e.message)
        block ? yield(result) : result
      end

      # @see Nominal#to_ast
      #
      # @api public
      def to_ast(meta: true)
        [:lax, type.to_ast(meta: meta)]
      end

      # @return [Lax]
      #
      # @api public
      def lax
        self
      end

      private

      # @param [Object, Dry::Types::Constructor] response
      #
      # @return [Boolean]
      #
      # @api private
      def decorate?(response)
        super || response.is_a?(type.constructor_type)
      end
    end

    extend ::Dry::Core::Deprecations[:'dry-types']
    Safe = Lax
    deprecate_constant(:Safe)
  end
end