Skip to content

Instantly share code, notes, and snippets.

@pat
Created April 28, 2013 18:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pat/5477820 to your computer and use it in GitHub Desktop.
Save pat/5477820 to your computer and use it in GitHub Desktop.
# Converts facets with foreign keys to their corresponding objects.
# Usage:
#
# Each article belongs to a user, and has a facet for the user_id attribute.
#
# facets = Article.facets
# FacetExpander.expand facets, :user
#
# facets[:users] has facets for each user object, and original user_id facet is
# still available as well.
#
class FacetExpander
def self.expand(facets, reference)
new(facets, reference).expand
end
def initialize(facets, reference)
@facets, @reference = facets, reference
end
def expand
facets[expanded_key] = {}
facets[id_key].each do |id, count|
object = collection.detect { |instance| instance.id == id }
next if object.nil?
facets[expanded_key][object] = count
end
end
private
attr_reader :facets, :reference
def collection
@collection ||= klass.where id: facets[id_key].keys
end
def expanded_key
reference.to_s.pluralize.to_sym
end
def id_key
"#{reference}_id".to_sym
end
def klass
@klass ||= reference.to_s.camelize.constantize
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment