Skip to content

Instantly share code, notes, and snippets.

@robertsosinski
Created January 19, 2013 03:13
Show Gist options
  • Save robertsosinski/4570537 to your computer and use it in GitHub Desktop.
Save robertsosinski/4570537 to your computer and use it in GitHub Desktop.
Sequel model plugin that makes faceting easy.
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}...
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
@robertsosinski
Copy link
Author

Remember, that the column you facet by has to either be named, or be aliased to "name".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment