Skip to content

Commit

Permalink
Override model_name.human for PaymentMethod
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
jhawthorn committed Jul 25, 2017
1 parent 275d31c commit db402d8
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
19 changes: 19 additions & 0 deletions core/app/models/spree/payment_method.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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. ' \
Expand Down Expand Up @@ -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
Expand Down
16 changes: 16 additions & 0 deletions core/spec/models/spree/payment_method_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit db402d8

Please sign in to comment.