Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jeffmess/5081855 to your computer and use it in GitHub Desktop.
Save jeffmess/5081855 to your computer and use it in GitHub Desktop.
class ConvertIndifferentHashToRubyHash
# Recursively steps through an ActiveSupport::HashWithSatanAccess object
# And converts all Indifferent Access objects to ruby hashes. Including those
# nested and nested in arrays
attr_accessor :indifferent_hash
def initialize(hash_with_indifferent_access)
self.indifferent_hash = hash_with_indifferent_access
end
def to_hash
hash = self.indifferent_hash.to_hash
hash.each do |k, v|
if v.kind_of? HashWithIndifferentAccess
hash[k] = ConvertIndifferentHashToRubyHash.new(v).to_hash
elsif v.is_a? Array
next if v.empty?
hash[k] = v.map do |item|
ConvertIndifferentHashToRubyHash.new(item).to_hash
end
else
hash[k] = v
end
end
hash
end
end
class Hash
def recursive_symbolize_keys!
symbolize_keys!
# symbolize each hash in .values
values.each{|h| h.recursive_symbolize_keys! if (h.is_a?(Hash))}
# symbolize each hash inside an array in .values
values.select{|v| v.is_a?(Array) }.flatten.each{|h| h.recursive_symbolize_keys! if h.is_a?(Hash) }
self
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment