Module: Dry::Types::Coercions
- Includes:
- Core::Constants
- 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
Instance Method Summary collapse
- #to_date(input, &block) ⇒ Date, Object
- #to_date_time(input, &block) ⇒ DateTime, Object
- #to_symbol(input, &block) ⇒ Symbol, Object
- #to_time(input, &block) ⇒ Time, Object
Instance Method Details
#to_date(input, &block) ⇒ Date, Object
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
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
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
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 |