Skip to content

Instantly share code, notes, and snippets.

@codesnik
Created January 19, 2016 05:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codesnik/00dbfdcfe5792f565a01 to your computer and use it in GitHub Desktop.
Save codesnik/00dbfdcfe5792f565a01 to your computer and use it in GitHub Desktop.
regrouping activerecord's group of group of groups
module Regroup
module_function
# Makes a tree out of a flat hashes with array keys.
# Useful for transformation of things like
# relation.group(:a).group(:b).group(:c).count
# to a hash of hash of hahes of any depth.
# Safe for usage with plain hashes, too.
#
# > rs = Payment.group(:date).group(:currency).sum
# => {[Tue, 19 Jan 2016, "EUR"] => 100,
# [Tue, 19 Jan 2016, "USD"] => 20,
# [Wen, 20 Jan 2016, "EUR"] => 6,
# }
#
# > regroup(rs)
# => {
# Tue, 19 Jan 2016 => {
# "EUR" => 100,
# "USD" => 20
# },
# Wen, 20 Jan 2016 => {
# "EUR" => 6
# }
# }
def regroup(hash)
tree = {}
hash.each do |(*heads, tail), value|
heads.inject(tree) { |subtree, key|
subtree[key] ||= {}
}[tail] = value
end
tree
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment