Sha256: 43af9fd1d0903a1f32a234c7ab9135928cbcc107cc8fe054a5c8fb757117dbac

Contents?: true

Size: 1.14 KB

Versions: 14

Compression:

Stored size: 1.14 KB

Contents

module Spree
  class Store < Spree::Base
    has_many :orders, class_name: "Spree::Order"

    with_options presence: true do
      validates :code, uniqueness: { allow_blank: true }
      validates :name, :url, :mail_from_address
    end

    before_save :ensure_default_exists_and_is_unique
    before_destroy :validate_not_default

    scope :by_url, lambda { |url| where("url like ?", "%#{url}%") }

    after_commit :clear_cache

    def self.current(domain = nil)
      current_store = domain ? Store.by_url(domain).first : nil
      current_store || Store.default
    end

    def self.default
      Rails.cache.fetch("default_store") do
        where(default: true).first_or_initialize
      end
    end

    private

    def ensure_default_exists_and_is_unique
      if default
        Store.where.not(id: id).update_all(default: false)
      elsif Store.where(default: true).count.zero?
        self.default = true
      end
    end

    def validate_not_default
      if default
        errors.add(:base, :cannot_destroy_default_store)
        throw(:abort)
      end
    end

    def clear_cache
      Rails.cache.delete("default_store")
    end
  end
end

Version data entries

14 entries across 14 versions & 2 rubygems

Version Path
goca-spree-core-3.1.14.rails.5.0.1 app/models/spree/store.rb
spree_core-3.2.9 app/models/spree/store.rb
spree_core-3.2.8 app/models/spree/store.rb
spree_core-3.2.7 app/models/spree/store.rb
spree_core-3.2.6 app/models/spree/store.rb
spree_core-3.2.5 app/models/spree/store.rb
spree_core-3.2.4 app/models/spree/store.rb
spree_core-3.2.3 app/models/spree/store.rb
spree_core-3.2.2 app/models/spree/store.rb
spree_core-3.2.1 app/models/spree/store.rb
spree_core-3.2.0 app/models/spree/store.rb
spree_core-3.2.0.rc3 app/models/spree/store.rb
spree_core-3.2.0.rc2 app/models/spree/store.rb
spree_core-3.2.0.rc1 app/models/spree/store.rb