Skip to content

Instantly share code, notes, and snippets.

@tjstankus
Created November 5, 2009 15:13
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 tjstankus/227103 to your computer and use it in GitHub Desktop.
Save tjstankus/227103 to your computer and use it in GitHub Desktop.
require 'active_support/ordered_hash'
require 'active_support/core_ext/enumerable'
module Enumerable
def group_by_attribute(attr, options={:nils_first => true})
raise "attr parameter must by a symbol" unless attr.is_a?(Symbol)
h = group_by(&attr)
returning h2 = ActiveSupport::OrderedHash.new do
h2[nil] = h.delete(nil) if options[:nils_first] && h.has_key?(nil)
h2.merge!(h)
end
end unless [].respond_to?(:group_by_attribute)
end
class NewsItem < ActiveRecord::Base
# ... Lots of stuff omitted for brevity
def self.all_grouped_by_feed
self.all.group_by_attribute(:feed_id)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment