Module: CMDx::Coercions::Hash
Overview
Coerces to Hash. ‘nil` becomes `{}`; strings are JSON-decoded (and must decode to a Hash); `#to_hash`/`#to_h` are used as fallbacks.
Instance Method Summary collapse
Instance Method Details
#call(value, options = EMPTY_HASH) ⇒ Hash, Coercions::Failure
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/cmdx/coercions/hash.rb', line 15 def call(value, = EMPTY_HASH) if value.nil? {} elsif value.is_a?(::Hash) value elsif value.is_a?(::String) result = JSON.parse(value) result.is_a?(::Hash) ? result : coercion_failure elsif value.respond_to?(:to_hash) value.to_hash elsif value.respond_to?(:to_h) value.to_h else coercion_failure end rescue ArgumentError, TypeError, JSON::ParserError coercion_failure end |