Filter products by distributor

This commit is contained in:
Rohan Mitchell
2012-06-20 14:20:07 +10:00
parent 423ab26a1a
commit 1207062f7c
5 changed files with 72 additions and 0 deletions

View File

@@ -0,0 +1,8 @@
Spree::Taxon.class_eval do
# Indicate which filters should be used for this taxon
def applicable_filters
fs = []
fs << Spree::ProductFilters.distributor_filter if Spree::ProductFilters.respond_to? :distributor_filter
fs
end
end

View File

@@ -0,0 +1,28 @@
<% filters = @taxon ? @taxon.applicable_filters : [Spree::ProductFilters.distributor_filter] %>
<% unless filters.empty? %>
<%= form_tag '', :method => :get, :id => 'sidebar_products_search' do %>
<% params[:search] ||= {} %>
<%= hidden_field_tag 'per_page', params[:per_page] %>
<% filters.each do |filter| %>
<% labels = filter[:labels] || filter[:conds].map {|m,c| [m,m]} %>
<% next if labels.empty? %>
<div class="navigation" data-hook="navigation">
<span class="category"> <%= filter[:name] %> </span>
<ul class="filter_choices">
<% labels.each do |nm,val| %>
<% label = "#{filter[:name]}_#{nm}".gsub(/\s+/,'_') %>
<li class="nowrap">
<input type="checkbox"
id="<%= label %>"
name="search[<%= filter[:scope].to_s %>][]"
value="<%= val %>"
<%= params[:search][filter[:scope]] && params[:search][filter[:scope]].include?(val.to_s) ? "checked" : "" %> />
<label class="nowrap" for="<%= label %>"> <%= nm %> </label>
</li>
<% end %>
</ul>
</div>
<% end %>
<%= submit_tag t(:search), :name => nil %>
<% end %>
<% end %>

View File

@@ -5,6 +5,11 @@
#
# In order to initialize a setting do:
# config.setting_name = 'new value'
require 'spree/product_filters'
Spree.config do |config|
# Example:
# Uncomment to override the default site name.

View File

@@ -0,0 +1,21 @@
module Spree
module ProductFilters
if Spree::Distributor.table_exists?
Spree::Product.scope :distributor_any,
lambda {|*opts|
conds = opts.map {|o| ProductFilters.distributor_filter[:conds][o]}.reject {|c| c.nil?}
Spree::Product.joins(:distributors).conditions_any(conds)
}
def ProductFilters.distributor_filter
distributors = Spree::Distributor.all.map(&:name).compact.uniq
conds = Hash[*distributors.map { |d| [d, "#{Spree::Distributor.table_name}.name = '#{d}'"] }.flatten]
{ :name => "Distributor",
:scope => :distributor_any,
:conds => conds,
:labels => (distributors.sort).map { |k| [k, k] }
}
end
end
end
end

View File

@@ -0,0 +1,10 @@
require 'spec_helper'
describe Spree::ProductFilters do
context "distributor filter" do
it "provides filtering for all distributors" do
3.times { create(:distributor) }
Spree::ProductFilters.distributor_filter[:labels].should == Spree::Distributor.all.map { |d| [d.name, d.name] }
end
end
end