Module: SymmetricEncryption::Coerce
- Defined in:
- lib/symmetric_encryption/coerce.rb
Overview
For coercing data types to from strings
Constant Summary collapse
- TYPE_MAP =
{ string: String, integer: Integer, float: Float, decimal: BigDecimal, datetime: DateTime, time: Time, date: Date }.freeze
Class Method Summary collapse
-
.coerce(value, type, from_type = nil) ⇒ Object
Coerce given value into given type Does not coerce json or yaml values.
-
.coerce_from_string(value, type) ⇒ Object
Uses coercible gem to coerce values from strings into the target type Note: if the type is :string, then the value is returned as is, and the coercible gem is not used at all.
-
.coerce_to_string(value, type) ⇒ Object
Uses coercible gem to coerce values to strings from the specified type Note: if the type is :string, and value is not nil, then #to_s is called on the value and the coercible gem is not used at all.
-
.coercion_type(symbol, value) ⇒ Object
Returns the correct coercion type to use for the specified symbol and value.
Class Method Details
.coerce(value, type, from_type = nil) ⇒ Object
Coerce given value into given type Does not coerce json or yaml values
16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/symmetric_encryption/coerce.rb', line 16 def self.coerce(value, type, from_type = nil) return value if value.nil? || (value == "") from_type ||= value.class case type when :json value when :yaml value else coercer = Coercible::Coercer.new coercer[from_type].send("to_#{type}".to_sym, value) end end |
.coerce_from_string(value, type) ⇒ Object
Uses coercible gem to coerce values from strings into the target type Note: if the type is :string, then the value is returned as is, and the
coercible gem is not used at all.
34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/symmetric_encryption/coerce.rb', line 34 def self.coerce_from_string(value, type) return value if value.nil? || (value == "") case type when :string value when :json JSON.load(value) when :yaml YAML.load(value) else coerce(value, type, String) end end |
.coerce_to_string(value, type) ⇒ Object
Uses coercible gem to coerce values to strings from the specified type Note: if the type is :string, and value is not nil, then #to_s is called
on the value and the coercible gem is not used at all.
52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/symmetric_encryption/coerce.rb', line 52 def self.coerce_to_string(value, type) return value if value.nil? || (value == "") case type when :string value.to_s when :json value.to_json when :yaml value.to_yaml else coerce(value, :string, coercion_type(type, value)) end end |
.coercion_type(symbol, value) ⇒ Object
Returns the correct coercion type to use for the specified symbol and value
68 69 70 71 72 73 74 |
# File 'lib/symmetric_encryption/coerce.rb', line 68 def self.coercion_type(symbol, value) if symbol == :boolean value.class else TYPE_MAP[symbol] end end |