Merge pull request #41475 from Yegorov/add-uncountable

Add `uncountable?` method to ActiveModel::Name
This commit is contained in:
Rafael França 2021-02-18 16:02:34 -05:00 committed by GitHub
commit b8d5279f17
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 11 additions and 2 deletions

View File

@ -171,6 +171,7 @@ module ActiveModel
@klass = klass
@singular = _singularize(@name)
@plural = ActiveSupport::Inflector.pluralize(@singular, locale)
@uncountable = @plural == @singular
@element = ActiveSupport::Inflector.underscore(ActiveSupport::Inflector.demodulize(@name))
@human = ActiveSupport::Inflector.humanize(@element)
@collection = ActiveSupport::Inflector.tableize(@name)
@ -179,7 +180,7 @@ module ActiveModel
@route_key = (namespace ? ActiveSupport::Inflector.pluralize(@param_key, locale) : @plural.dup)
@singular_route_key = ActiveSupport::Inflector.singularize(@route_key, locale)
@route_key << "_index" if @plural == @singular
@route_key << "_index" if @uncountable
end
# Transform the model name into a more human format, using I18n. By default,
@ -207,6 +208,10 @@ module ActiveModel
I18n.translate(defaults.shift, **options)
end
def uncountable?
@uncountable
end
private
def _singularize(string)
ActiveSupport::Inflector.underscore(string).tr("/", "_")
@ -280,7 +285,7 @@ module ActiveModel
# ActiveModel::Naming.uncountable?(Sheep) # => true
# ActiveModel::Naming.uncountable?(Post) # => false
def self.uncountable?(record_or_class)
plural(record_or_class) == singular(record_or_class)
model_name_from_record_or_class(record_or_class).uncountable?
end
# Returns string to use while generating route names. It differs for

View File

@ -42,6 +42,10 @@ class NamingTest < ActiveModel::TestCase
def test_i18n_key
assert_equal :"post/track_back", @model_name.i18n_key
end
def test_uncountable
assert_equal false, @model_name.uncountable?
end
end
class NamingWithNamespacedModelInIsolatedNamespaceTest < ActiveModel::TestCase