Created
January 19, 2013 03:13
-
-
Save robertsosinski/4570537 to your computer and use it in GitHub Desktop.
Sequel model plugin that makes faceting easy.
This file contains 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
ProductType.facet(:name).all | |
[{:name=>"Direct Receiver", :count=>9}, | |
{:name=>"Input System", :count=>6}, | |
{:name=>"Performance Compressor", :count=>6}, | |
{:name=>"Air Controller", :count=>5}, | |
{:name=>"Audible Mount", :count=>5}, | |
{:name=>"Auto Amplifier", :count=>5}, | |
{:name=>"Digital Component", :count=>5}, | |
{:name=>"Direct Transmitter", :count=>5}, | |
{:name=>"Gel Receiver", :count=>5}... | |
ProductType.facet { unnest(:tags).as(:name) }.all | |
[{:name=>"party", :count=>53}, | |
{:name=>"seitan", :count=>53}, | |
{:name=>"squid", :count=>53}, | |
{:name=>"McSweeney's", :count=>52}, | |
{:name=>"tattooed", :count=>52}, | |
{:name=>"art", :count=>50}, | |
{:name=>"skateboard", :count=>50}, | |
{:name=>"lo-fi", :count=>49}, | |
{:name=>"butcher", :count=>48}... | |
This file contains 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 Sequel | |
module Plugins | |
module Facetable | |
module DatasetMethods | |
def facet(column = nil, &block) | |
table = self.model.table_name | |
case | |
when block_given? | |
selector = block | |
when column.present? | |
selector = proc { column.qualify(table).as(:name) } | |
else | |
raise ArgumentError.new('You must pass either a column name or a selector block.') | |
end | |
DB.dataset.with(:facets, | |
self.select(&selector). | |
select_append { count(:id.qualify(table)).as(:count) }. | |
group(1) | |
). | |
from(:facets). | |
order(:count.desc, :name.asc) | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Remember, that the column you facet by has to either be named, or be aliased to "name".