Extract out a DISPLAY_ON_OPTIONS constant in Spree::ShippingMethod instead of magic strings

This commit is contained in:
Cillian O'Ruanaidh
2022-06-08 20:00:04 +01:00
committed by Filipe
parent 37617f63ea
commit a5daee39e3
4 changed files with 28 additions and 7 deletions

View File

@@ -3,7 +3,10 @@
module Spree
class ShippingMethod < ApplicationRecord
include CalculatedAdjustments
DISPLAY = [:both, :front_end, :back_end].freeze
DISPLAY_ON_OPTIONS = {
both: "",
back_end: "back_end"
}.freeze
acts_as_paranoid
acts_as_taggable
@@ -27,6 +30,7 @@ module Spree
validates :name, presence: true
validate :distributor_validation
validate :at_least_one_shipping_category
validates :display_on, inclusion: { in: DISPLAY_ON_OPTIONS.values }, allow_nil: true
after_save :touch_distributors
@@ -101,12 +105,12 @@ module Spree
]
end
def self.on_backend_query
"#{table_name}.display_on != 'front_end' OR #{table_name}.display_on IS NULL"
def self.backend
where("spree_shipping_methods.display_on = ?", DISPLAY_ON_OPTIONS[:back_end])
end
def self.on_frontend_query
"#{table_name}.display_on != 'back_end' OR #{table_name}.display_on IS NULL"
def self.frontend
where("spree_shipping_methods.display_on IS NULL OR spree_shipping_methods.display_on = ''")
end
private

View File

@@ -8,7 +8,7 @@ module Spree
scope :frontend,
-> {
includes(:shipping_method).
where(ShippingMethod.on_frontend_query).
merge(ShippingMethod.frontend).
references(:shipping_method).
order("cost ASC")
}

View File

@@ -19,7 +19,7 @@
.alpha.four.columns
= f.label :display_on, t(:display)
.omega.twelve.columns
= select(:shipping_method, :display_on, [[t(".both"), nil], [t(".back_end"), "back_end"]], {}, {class: 'select2 fullwidth'})
= select(:shipping_method, :display_on, Spree::ShippingMethod::DISPLAY_ON_OPTIONS.map { |key, value| [t(".#{key}"), value] }, {}, {class: 'select2 fullwidth'})
= error_message_on :shipping_method, :display_on
.row

View File

@@ -143,6 +143,23 @@ module Spree
expect(shipping_method.errors[:name].first).to eq "can't be blank"
end
describe "#display_on" do
it "is valid when it's set to nil, an empty string or 'back_end'" do
shipping_method = build_stubbed(:shipping_method)
[nil, "", "back_end"].each do |display_on_option|
shipping_method.display_on = display_on_option
shipping_method.valid?
expect(shipping_method.errors[:display_on]).to be_empty
end
end
it "is not valid when it's set to an unknown value" do
shipping_method = build_stubbed(:shipping_method, display_on: "front_end")
expect(shipping_method).not_to be_valid
expect(shipping_method.errors[:display_on]).to eq ["is not included in the list"]
end
end
context "shipping category" do
it "validates presence of at least one" do
shipping_method = build_stubbed(