2014-04-30 17:34:37 +00:00
|
|
|
require 'hashie/extensions/stringify_keys'
|
|
|
|
require 'hashie/extensions/pretty_inspect'
|
2010-08-26 10:43:05 +00:00
|
|
|
|
2009-09-06 04:27:54 +00:00
|
|
|
module Hashie
|
|
|
|
# A Hashie Hash is simply a Hash that has convenience
|
|
|
|
# functions baked in such as stringify_keys that may
|
|
|
|
# not be available in all libraries.
|
2012-02-08 20:53:20 +00:00
|
|
|
class Hash < ::Hash
|
2014-04-30 17:34:37 +00:00
|
|
|
include Hashie::Extensions::PrettyInspect
|
|
|
|
include Hashie::Extensions::StringifyKeys
|
|
|
|
|
|
|
|
# Convert this hash into a Mash
|
|
|
|
def to_mash
|
|
|
|
::Hashie::Mash.new(self)
|
|
|
|
end
|
2010-06-15 06:16:25 +00:00
|
|
|
|
2014-02-12 18:13:23 +00:00
|
|
|
# Converts a mash back to a hash (with stringified or symbolized keys)
|
2014-03-31 00:44:13 +00:00
|
|
|
def to_hash(options = {})
|
2010-06-15 06:16:25 +00:00
|
|
|
out = {}
|
2018-02-03 16:23:14 +00:00
|
|
|
each_key do |k|
|
2018-09-30 19:07:18 +00:00
|
|
|
assignment_key =
|
|
|
|
if options[:stringify_keys]
|
|
|
|
k.to_s
|
2020-05-05 01:15:32 +00:00
|
|
|
elsif options[:symbolize_keys] && k.respond_to?(:to_sym)
|
|
|
|
k.to_sym
|
2018-09-30 19:07:18 +00:00
|
|
|
else
|
|
|
|
k
|
|
|
|
end
|
2012-03-05 21:53:34 +00:00
|
|
|
if self[k].is_a?(Array)
|
2014-02-12 18:13:23 +00:00
|
|
|
out[assignment_key] ||= []
|
2012-03-05 21:53:34 +00:00
|
|
|
self[k].each do |array_object|
|
2018-09-30 19:07:18 +00:00
|
|
|
out[assignment_key] << maybe_convert_to_hash(array_object, options)
|
2012-03-05 21:53:34 +00:00
|
|
|
end
|
|
|
|
else
|
2018-09-30 19:07:18 +00:00
|
|
|
out[assignment_key] = maybe_convert_to_hash(self[k], options)
|
2012-03-05 21:53:34 +00:00
|
|
|
end
|
2010-06-15 06:16:25 +00:00
|
|
|
end
|
|
|
|
out
|
|
|
|
end
|
|
|
|
|
2014-04-11 21:38:26 +00:00
|
|
|
# The C generator for the json gem doesn't like mashies
|
2010-06-15 06:23:20 +00:00
|
|
|
def to_json(*args)
|
|
|
|
to_hash.to_json(*args)
|
2010-06-15 06:16:25 +00:00
|
|
|
end
|
2014-04-11 21:53:16 +00:00
|
|
|
|
2014-04-11 21:38:26 +00:00
|
|
|
private
|
2014-04-11 21:53:16 +00:00
|
|
|
|
2018-09-30 19:07:18 +00:00
|
|
|
def maybe_convert_to_hash(object, options)
|
|
|
|
return object unless object.is_a?(Hash) || object.respond_to?(:to_hash)
|
|
|
|
|
|
|
|
flexibly_convert_to_hash(object, options)
|
|
|
|
end
|
|
|
|
|
2014-04-11 21:38:26 +00:00
|
|
|
def flexibly_convert_to_hash(object, options = {})
|
2018-02-03 16:23:14 +00:00
|
|
|
if object.method(:to_hash).arity.zero?
|
2014-04-11 21:38:26 +00:00
|
|
|
object.to_hash
|
|
|
|
else
|
|
|
|
object.to_hash(options)
|
|
|
|
end
|
|
|
|
end
|
2009-09-06 04:27:54 +00:00
|
|
|
end
|
2010-06-15 06:16:25 +00:00
|
|
|
end
|