Module: Dry::Types::Coercions

Includes:
Core::Constants
Included in:
JSON, Params
Defined in:
lib/dry/types/coercions.rb,
lib/dry/types/coercions/json.rb,
lib/dry/types/coercions/params.rb

Overview

Common coercion functions used by the built-in Params and JSON types

Defined Under Namespace

Modules: JSON, Params

Instance Method Summary collapse

Instance Method Details

#to_date(input, &block) ⇒ Date, Object

Parameters:

  • input (#to_str, Object)

Returns:

  • (Date, Object)

See Also:

  • Date.parse


18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/dry/types/coercions.rb', line 18

def to_date(input, &block)
  if input.respond_to?(:to_str)
    begin
      ::Date.parse(input)
    rescue ArgumentError, RangeError => e
      CoercionError.handle(e, &block)
    end
  elsif input.is_a?(::Date)
    input
  elsif block_given?
    yield
  else
    raise CoercionError, "#{input.inspect} is not a string"
  end
end

#to_date_time(input, &block) ⇒ DateTime, Object

Parameters:

  • input (#to_str, Object)

Returns:

  • (DateTime, Object)

See Also:

  • DateTime.parse


41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/dry/types/coercions.rb', line 41

def to_date_time(input, &block)
  if input.respond_to?(:to_str)
    begin
      ::DateTime.parse(input)
    rescue ArgumentError => e
      CoercionError.handle(e, &block)
    end
  elsif input.is_a?(::DateTime)
    input
  elsif block_given?
    yield
  else
    raise CoercionError, "#{input.inspect} is not a string"
  end
end

#to_symbol(input, &block) ⇒ Symbol, Object

Parameters:

  • input (#to_sym, Object)

Returns:

  • (Symbol, Object)

Raises:

  • CoercionError



87
88
89
90
91
# File 'lib/dry/types/coercions.rb', line 87

def to_symbol(input, &block)
  input.to_sym
rescue NoMethodError => e
  CoercionError.handle(e, &block)
end

#to_time(input, &block) ⇒ Time, Object

Parameters:

  • input (#to_str, Object)

Returns:

  • (Time, Object)

See Also:

  • Time.parse


64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/dry/types/coercions.rb', line 64

def to_time(input, &block)
  if input.respond_to?(:to_str)
    begin
      ::Time.parse(input)
    rescue ArgumentError => e
      CoercionError.handle(e, &block)
    end
  elsif input.is_a?(::Time)
    input
  elsif block_given?
    yield
  else
    raise CoercionError, "#{input.inspect} is not a string"
  end
end