Skip to content

Commit b8d5279

Browse files
authored
Merge pull request rails#41475 from Yegorov/add-uncountable
Add `uncountable?` method to ActiveModel::Name
2 parents 50b5371 + 89db42b commit b8d5279

File tree

2 files changed

+11
-2
lines changed

2 files changed

+11
-2
lines changed

activemodel/lib/active_model/naming.rb

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,7 @@ def initialize(klass, namespace = nil, name = nil, locale = :en)
171171
@klass = klass
172172
@singular = _singularize(@name)
173173
@plural = ActiveSupport::Inflector.pluralize(@singular, locale)
174+
@uncountable = @plural == @singular
174175
@element = ActiveSupport::Inflector.underscore(ActiveSupport::Inflector.demodulize(@name))
175176
@human = ActiveSupport::Inflector.humanize(@element)
176177
@collection = ActiveSupport::Inflector.tableize(@name)
@@ -179,7 +180,7 @@ def initialize(klass, namespace = nil, name = nil, locale = :en)
179180

180181
@route_key = (namespace ? ActiveSupport::Inflector.pluralize(@param_key, locale) : @plural.dup)
181182
@singular_route_key = ActiveSupport::Inflector.singularize(@route_key, locale)
182-
@route_key << "_index" if @plural == @singular
183+
@route_key << "_index" if @uncountable
183184
end
184185

185186
# Transform the model name into a more human format, using I18n. By default,
@@ -207,6 +208,10 @@ def human(options = {})
207208
I18n.translate(defaults.shift, **options)
208209
end
209210

211+
def uncountable?
212+
@uncountable
213+
end
214+
210215
private
211216
def _singularize(string)
212217
ActiveSupport::Inflector.underscore(string).tr("/", "_")
@@ -280,7 +285,7 @@ def self.singular(record_or_class)
280285
# ActiveModel::Naming.uncountable?(Sheep) # => true
281286
# ActiveModel::Naming.uncountable?(Post) # => false
282287
def self.uncountable?(record_or_class)
283-
plural(record_or_class) == singular(record_or_class)
288+
model_name_from_record_or_class(record_or_class).uncountable?
284289
end
285290

286291
# Returns string to use while generating route names. It differs for

activemodel/test/cases/naming_test.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,10 @@ def test_param_key
4242
def test_i18n_key
4343
assert_equal :"post/track_back", @model_name.i18n_key
4444
end
45+
46+
def test_uncountable
47+
assert_equal false, @model_name.uncountable?
48+
end
4549
end
4650

4751
class NamingWithNamespacedModelInIsolatedNamespaceTest < ActiveModel::TestCase

0 commit comments

Comments
 (0)