module Hashie::Extensions::Coercion::ClassMethods

def coerce_key(*attrs)

Other tags:
    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 = {})

Other tags:
    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)

if one exists.
Returns the specific key coercion for the specified key,
def key_coercion(key)
  key_coercions[key.to_sym]
end

def key_coercions

Returns a hash of any existing key coercions.
def key_coercions
  @key_coercions || {}
end

def lenient_value_coercions

Return all value coercions that have the :strict rule as false.
def lenient_value_coercions
  @value_coercions || {}
end

def strict_value_coercions

Return all value coercions that have the :strict rule as true.
def strict_value_coercions
  @strict_value_coercions || {}
end

def value_coercion(value)

Fetch the value coercion, if any, for the specified object.
def value_coercion(value)
  from = value.class
  strict_value_coercions[from] || lenient_value_coercions[from]
end