File: json.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 (40 lines) | stat: -rw-r--r-- 802 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
# frozen_string_literal: true

require 'date'
require 'bigdecimal'
require 'bigdecimal/util'
require 'time'

module Dry
  module Types
    module Coercions
      # JSON-specific coercions
      #
      # @api public
      module JSON
        extend Coercions

        # @param [#to_d, Object] input
        #
        # @return [BigDecimal,nil]
        #
        # @raise CoercionError
        #
        # @api public
        def self.to_decimal(input, &block)
          if input.is_a?(::Float)
            input.to_d
          else
            BigDecimal(input)
          end
        rescue ArgumentError, TypeError
          if block_given?
            yield
          else
            raise CoercionError, "#{input} cannot be coerced to decimal"
          end
        end
      end
    end
  end
end