Provide searching by supplier or distributor via spree searcher class

This commit is contained in:
Rohan Mitchell
2012-06-20 17:44:58 +10:00
parent b0a8645738
commit 412eb4365e
4 changed files with 62 additions and 4 deletions

View File

@@ -5,4 +5,7 @@ Spree::Product.class_eval do
attr_accessible :supplier_id, :distributor_ids
validates_presence_of :distributors
scope :in_supplier, lambda { |supplier| where(:supplier_id => supplier) }
scope :in_distributor, lambda { |distributor| joins(:distributors).where('distributors.id = ?', distributor) }
end

View File

@@ -8,15 +8,15 @@
require 'spree/product_filters'
require 'open_food_web/searcher'
Spree.config do |config|
# Example:
# Uncomment to override the default site name.
# config.site_name = "Spree Demo Site"
config.site_name = "Open Food Web"
# config.shipping_instructions = true
config.checkout_zone = 'Australia'
config.address_requires_state = true
config.default_country_id = 12 # This should be Australia, see:spree/core/db/default/spree/countries.yml
config.searcher_class = OpenFoodWeb::Searcher
end

View File

@@ -0,0 +1,23 @@
require 'spree/core/search/base'
module OpenFoodWeb
class Searcher < Spree::Core::Search::Base
def get_base_scope
base_scope = super
base_scope = base_scope.in_supplier(supplier_id) if supplier_id
base_scope = base_scope.in_distributor(distributor_id) if distributor_id
base_scope
end
def prepare(params)
super(params)
@properties[:supplier_id] = params[:supplier_id]
@properties[:distributor_id] = params[:distributor_id]
end
end
end

View File

@@ -0,0 +1,32 @@
require 'spec_helper'
require 'open_food_web/searcher'
module OpenFoodWeb
describe Searcher do
it "searches by supplier" do
# Given products under two suppliers
s1 = create(:supplier)
s2 = create(:supplier)
p1 = create(:product, :supplier => s1)
p2 = create(:product, :supplier => s2)
# When we search for one supplier, we should see only products from that supplier
searcher = Searcher.new(:supplier_id => s1.id.to_s)
products = searcher.retrieve_products
products.should == [p1]
end
it "searches by distributor" do
# Given products under two distributors
d1 = create(:distributor)
d2 = create(:distributor)
p1 = create(:product, :distributors => [d1])
p2 = create(:product, :distributors => [d2])
# When we search for one distributor, we should see only products from that distributor
searcher = Searcher.new(:distributor_id => d1.id.to_s)
products = searcher.retrieve_products
products.should == [p1]
end
end
end