Sha256: b9249788f5f42c1bbc3bc905004a256ff80cb34e5eb9f4175e4187cf6496834e

Contents?: true

Size: 1.33 KB

Versions: 3

Compression:

Stored size: 1.33 KB

Contents

require 'bigdecimal'
require 'bigdecimal/util'

module Dry
  module Types
    module Coercions
      module Form
        TRUE_VALUES = %w[1 on On ON t true True TRUE  y yes Yes YES].freeze
        FALSE_VALUES = %w[0 off Off OFF f false False FALSE n no No NO].freeze
        BOOLEAN_MAP = ::Hash[TRUE_VALUES.product([true]) + FALSE_VALUES.product([false])].freeze

        extend Coercions

        def self.to_true(input)
          BOOLEAN_MAP.fetch(input, input)
        end

        def self.to_false(input)
          BOOLEAN_MAP.fetch(input, input)
        end

        def self.to_int(input)
          if empty_str?(input)
            nil
          else
            Integer(input)
          end
        rescue ArgumentError, TypeError
          input
        end

        def self.to_float(input)
          if empty_str?(input)
            nil
          else
            Float(input)
          end
        rescue ArgumentError, TypeError
          input
        end

        def self.to_decimal(input)
          result = to_float(input)

          if result.instance_of?(Float)
            input.to_d
          else
            result
          end
        end

        def self.to_ary(input)
          empty_str?(input) ? [] : input
        end

        def self.to_hash(input)
          empty_str?(input) ? {} : input
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
dry-types-0.8.1 lib/dry/types/coercions/form.rb
dry-types-0.8.0 lib/dry/types/coercions/form.rb
dry-types-0.7.2 lib/dry/types/coercions/form.rb