Created
April 28, 2013 18:16
-
-
Save pat/5477820 to your computer and use it in GitHub Desktop.
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
# 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