From ef2c1b44b122759f294249d8a3128069f4249f25 Mon Sep 17 00:00:00 2001 From: John Hawthorn Date: Fri, 21 Jul 2017 15:37:05 -0700 Subject: [PATCH] Override model_name.human for PaymentMethod Recently we started using model_name.human instead of the raw class name when displaying the names of payment methods. Unfortunately, if there isn't an i18n key for that specific payment method, model_name.human will fall back to "Payment Method", which is not at all helpful in distinguishing it. This commit changes PaymentMethod.model_name to return a custom ActiveModel::Name subclass, which will use exact matches for translations but doesn't fall back to "Payment Method", and instead will use the "humanized" class name if there is no key. --- core/app/models/spree/payment_method.rb | 19 +++++++++++++++++++ core/spec/models/spree/payment_method_spec.rb | 16 ++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/core/app/models/spree/payment_method.rb b/core/app/models/spree/payment_method.rb index 5e4fc9a3730..aa03108087c 100644 --- a/core/app/models/spree/payment_method.rb +++ b/core/app/models/spree/payment_method.rb @@ -37,6 +37,21 @@ class PaymentMethod < Spree::Base include Spree::Preferences::StaticallyConfigurable + # Custom ModelName#human implementation to ensure we don't refer to + # subclasses as just "PaymentMethod" + class ModelName < ActiveModel::Name + # Similar to ActiveModel::Name#human, but skips lookup_ancestors + def human(options = {}) + defaults = [ + i18n_key, + options[:default], + @human + ].compact + options = { scope: [:activerecord, :models], count: 1, default: defaults }.merge!(options.except(:default)) + I18n.translate(defaults.shift, options) + end + end + class << self def providers Spree::Deprecation.warn 'Spree::PaymentMethod.providers is deprecated and will be deleted in Solidus 3.0. ' \ @@ -66,6 +81,10 @@ def available(display_on = nil, store: nil) end end + def model_name + ModelName.new(self, Spree) + end + def active? where(type: to_s, active: true).count > 0 end diff --git a/core/spec/models/spree/payment_method_spec.rb b/core/spec/models/spree/payment_method_spec.rb index 4b21d210697..c5d1eac1903 100644 --- a/core/spec/models/spree/payment_method_spec.rb +++ b/core/spec/models/spree/payment_method_spec.rb @@ -354,4 +354,20 @@ def gateway_class expect(payment_method.credit).to eq 'credit' end end + + describe 'model_name.human' do + context 'PaymentMethod itself' do + it "returns i18n value" do + expect(Spree::PaymentMethod.model_name.human).to eq('Payment Method') + end + end + + context 'A subclass with no i18n key' do + let!(:klass) { stub_const("MyGem::SomeClass", Class.new(described_class)) } + + it "returns default humanized value" do + expect(klass.model_name.human).to eq('Some class') + end + end + end end