1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

add locale argument to ActiveModel::Name initialize

This commit is contained in:
Lukáš Pokorný 2020-12-29 10:39:35 +01:00
parent 96446a9708
commit d20caa6df1
No known key found for this signature in database
GPG key ID: C770FCFED0C306C2
2 changed files with 23 additions and 4 deletions

View file

@ -153,6 +153,7 @@ module ActiveModel
# Returns a new ActiveModel::Name instance. By default, the +namespace+
# and +name+ option will take the namespace and name of the given class
# respectively.
# Use +locale+ argument for singularize and pluralize model name.
#
# module Foo
# class Bar
@ -161,7 +162,7 @@ module ActiveModel
#
# ActiveModel::Name.new(Foo::Bar).to_s
# # => "Foo::Bar"
def initialize(klass, namespace = nil, name = nil)
def initialize(klass, namespace = nil, name = nil, locale = :en)
@name = name || klass.name
raise ArgumentError, "Class name cannot be blank. You need to supply a name argument when anonymous class given" if @name.blank?
@ -169,15 +170,15 @@ module ActiveModel
@unnamespaced = @name.delete_prefix("#{namespace.name}::") if namespace
@klass = klass
@singular = _singularize(@name)
@plural = ActiveSupport::Inflector.pluralize(@singular)
@plural = ActiveSupport::Inflector.pluralize(@singular, locale)
@element = ActiveSupport::Inflector.underscore(ActiveSupport::Inflector.demodulize(@name))
@human = ActiveSupport::Inflector.humanize(@element)
@collection = ActiveSupport::Inflector.tableize(@name)
@param_key = (namespace ? _singularize(@unnamespaced) : @singular)
@i18n_key = @name.underscore.to_sym
@route_key = (namespace ? ActiveSupport::Inflector.pluralize(@param_key) : @plural.dup)
@singular_route_key = ActiveSupport::Inflector.singularize(@route_key)
@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
end

View file

@ -158,6 +158,24 @@ class NamingWithSuppliedModelNameTest < ActiveModel::TestCase
end
end
class NamingWithSuppliedLocaleTest < ActiveModel::TestCase
def setup
ActiveSupport::Inflector.inflections(:cs) do |inflect|
inflect.plural(/(e)l$/i, '\1lé')
end
@model_name = ActiveModel::Name.new(Blog::Post, nil, "Uzivatel", :cs)
end
def test_singular
assert_equal "uzivatel", @model_name.singular
end
def test_plural
assert_equal "uzivatelé", @model_name.plural
end
end
class NamingUsingRelativeModelNameTest < ActiveModel::TestCase
def setup
@model_name = Blog::Post.model_name