Skip to content
This repository has been archived by the owner on Aug 13, 2021. It is now read-only.

Commit

Permalink
Merge pull request #80 from bonobos/feature/ensure_default_exists_and…
Browse files Browse the repository at this point in the history
…_is_unique

Spree::Store now ensures that there always will be a default
  • Loading branch information
JDutil committed Feb 28, 2014
2 parents 9f8ade3 + b630f65 commit 06fb54c
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 8 deletions.
10 changes: 10 additions & 0 deletions app/models/spree/store.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ class Store < ActiveRecord::Base
has_and_belongs_to_many :promotion_rules, :class_name => 'Spree::Promotion::Rules::Store', :join_table => 'spree_promotion_rules_stores', :association_foreign_key => 'promotion_rule_id'

validates_presence_of :name, :code, :domains

before_create :ensure_default_exists_and_is_unique

scope :default, lambda { where(:default => true) }
scope :by_domain, lambda { |domain| where("domains like ?", "%#{domain}%") }
Expand All @@ -32,5 +34,13 @@ def self.current(domain = nil)
def self.first_found_default
@cached_default ||= Store.default.first
end

def ensure_default_exists_and_is_unique
if default and not Store.default.empty?
Store.update_all(default: false)
elsif Store.default.empty?
self.default = true
end
end
end
end
32 changes: 24 additions & 8 deletions spec/models/spree/store_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,32 @@

describe Spree::Store do

before(:each) do
@store = FactoryGirl.create(:store, :domains => "website1.com\nwww.subdomain.com")
@store2 = FactoryGirl.create(:store, :domains => 'freethewhales.com')
end
describe "by_domain" do
let!(:store) { FactoryGirl.create(:store, :domains => "website1.com\nwww.subdomain.com") }
let!(:store_2) { FactoryGirl.create(:store, :domains => 'freethewhales.com') }

it "should find stores by domain" do
by_domain = Spree::Store.by_domain('www.subdomain.com')
it "should find stores by domain" do
by_domain = Spree::Store.by_domain('www.subdomain.com')

by_domain.should include(@store)
by_domain.should_not include(@store2)
by_domain.should include(store)
by_domain.should_not include(store_2)
end
end

describe "default" do
let!(:store) { FactoryGirl.create(:store) }
let!(:store_2) { FactoryGirl.create(:store, default: true) }

it "should ensure there is a default if one doesn't exist yet" do
store.default.should be_true
end

it "should ensure there is only one default" do
[store, store_2].each(&:reload)

Spree::Store.default.count.should == 1
store_2.default.should be_true
store.default.should_not be_true
end
end
end

0 comments on commit 06fb54c

Please sign in to comment.