From e28ee7020136331b9e2bcb6b7b1d2a9b926ec3b9 Mon Sep 17 00:00:00 2001 From: Daniele Palombo Date: Wed, 20 Dec 2017 12:03:14 +0100 Subject: [PATCH] Fix match method Match cannot call for_address(address).first because for_address does not return the zone members in order zip_code, state, country. --- app/models/solidus_zip_zones/zone_decorator.rb | 15 ++++++++++++++- .../solidus_zip_zones/zone_decorator_spec.rb | 11 +++++++++-- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/app/models/solidus_zip_zones/zone_decorator.rb b/app/models/solidus_zip_zones/zone_decorator.rb index ae6fab8..913e6ce 100644 --- a/app/models/solidus_zip_zones/zone_decorator.rb +++ b/app/models/solidus_zip_zones/zone_decorator.rb @@ -57,7 +57,20 @@ def with_shared_members(zone) def match(address) Spree::Deprecation.warn("Spree::Zone.match is deprecated. Please use Spree::Zone.for_address instead.", caller) - for_address(address).first + # This code can't be replaced with for_address because for_address + # does not sort the member in order zip_code, state, country + return unless address && (matches = + for_address(address). + order(:zone_members_count, :created_at, :id). + references(:zones)) + + ['zip_code', 'state', 'country'].each do |zone_kind| + if match = matches.detect { |zone| zone_kind == zone.kind } + return match + end + end + + matches.first end end diff --git a/spec/models/solidus_zip_zones/zone_decorator_spec.rb b/spec/models/solidus_zip_zones/zone_decorator_spec.rb index 62e4fb6..1a123f5 100644 --- a/spec/models/solidus_zip_zones/zone_decorator_spec.rb +++ b/spec/models/solidus_zip_zones/zone_decorator_spec.rb @@ -130,9 +130,16 @@ end context "when there are three qualified zones with different member types" do - let!(:zip_zone) { create(:zone, name: 'ZipZone', zipcodes: '12345,12346') } - + let!(:zip_zone) { create(:zone, zip_codes: zip_codes) } let(:state_zone) { create(:zone, name: 'StateZone') } + + let(:zip_codes) do + [ + create(:zip_code, state_code: "AL", name: '12345'), + create(:zip_code, state_code: "AL", name: '12346') + ] + end + let(:address) do create(:address, country: country,