module Hashie::Extensions::Coercion::ClassMethods
def coerce_key(*attrs)
- Example: Coerce a "user" subhash into a User object -
Parameters:
-
into
(Class
) -- the class into which you want the key(s) coerced. -
key
(Object
) -- the key or array of keys you would like to be coerced.
def coerce_key(*attrs) @key_coercions ||= {} into = attrs.pop attrs.each { |key| @key_coercions[key] = into } end
def coerce_value(from, into, options = {})
- Example: Coerce all hashes into this special type of hash -
Options Hash:
(**options)
-
:strict
(Boolean
) -- whether use exact source class only or include ancestors
Parameters:
-
into
(Class
) -- the class into which you would like the value coerced. -
from
(Class
) -- the type you would like coerced.
def coerce_value(from, into, options = {}) options = {:strict => true}.merge(options) if options[:strict] (@strict_value_coercions ||= {})[from] = into else while from.superclass && from.superclass != Object (@lenient_value_coercions ||= {})[from] = into from = from.superclass end end end
def key_coercion(key)
Returns the specific key coercion for the specified key,
def key_coercion(key) key_coercions[key] end
def key_coercions
def key_coercions @key_coercions || {} end
def lenient_value_coercions; @value_coercions || {} end
def lenient_value_coercions; @value_coercions || {} end
def strict_value_coercions; @strict_value_coercions || {} end
def strict_value_coercions; @strict_value_coercions || {} end
def value_coercion(value)
def value_coercion(value) from = value.class strict_value_coercions[from] || lenient_value_coercions[from] end