module Hashie::Extensions::Coercion::InstanceMethods

@example Add coercing instance writers through the extension

class Record < Hash
  include Hashie::Extensions::Coercion
  coerce_key :count, Integer
end
record = Record.new
record[:count] = '3'
record[:count] # => 3

Public Instance Methods

convert_value(val, duping = false) click to toggle source

Ensures that values are coerced before Mash's own recursive Hash-to-Mash conversion has a chance to run, since by that point the value would already be an instance of `self.class` rather than a plain Hash, and value coercion would never trigger. See github.com/hashie/hashie/issues/265.

@example Convert values by their source type

class Record < Hash
  include Hashie::Extensions::Coercion
  coerce_value String, Integer
end
Record.new.convert_value('3') # => 3
Record.new.convert_value(false) # => false
Calls superclass method
# File lib/hashie/extensions/coercion.rb, line 103
def convert_value(val, duping = false)
  into = self.class.value_coercion(val)
  return self.class.fetch_coercion(into).call(val) if into

  defined?(super) ? super : val
end
custom_writer(key, value, _convert = true) click to toggle source

@example Route a custom write through coercion

class Record < Hash
  include Hashie::Extensions::Coercion
  coerce_key :count, Integer
end
record = Record.new
record.custom_writer(:count, '3')
record[:count] # => 3
# File lib/hashie/extensions/coercion.rb, line 86
def custom_writer(key, value, _convert = true)
  self[key] = value
end
replace(other_hash) click to toggle source

@example Remove old keys and coerce incoming values

class Record < Hash
  include Hashie::Extensions::Coercion
  coerce_key :count, Integer
end
record = Record[:old, true]
record.replace(count: '3')
record # => { count: 3 }
# File lib/hashie/extensions/coercion.rb, line 118
def replace(other_hash)
  (keys - other_hash.keys).each { |key| delete(key) }
  other_hash.each { |key, value| self[key] = value }
  self
end
set_value_with_coercion(key, value) click to toggle source

@example Write a coerced value

class Record < Hash
  include Hashie::Extensions::Coercion
  coerce_key :count, Integer
end
record = Record.new
record.set_value_with_coercion(:count, '3')
record[:count] # => 3
# File lib/hashie/extensions/coercion.rb, line 64
def set_value_with_coercion(key, value)
  into = self.class.key_coercion(key) || self.class.value_coercion(value)

  unless value.nil? || into.nil?
    begin
      value = self.class.fetch_coercion(into).call(value)
    rescue NoMethodError, TypeError, ArgumentError => e
      raise CoercionError.new(key, value, into, e.message)
    end
  end

  set_value_without_coercion(key, value)
end