Created
January 19, 2016 05:09
-
-
Save codesnik/00dbfdcfe5792f565a01 to your computer and use it in GitHub Desktop.
regrouping activerecord's group of group of groups
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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