Merge pull request #39832 from p8/scaffold-generator-inflection-check

Raise if camelcase inflection impossible in generator
This commit is contained in:
Rafael França 2020-11-02 15:18:26 -05:00 committed by GitHub
commit 5f40eca4a5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 36 additions and 2 deletions

View File

@ -11,6 +11,11 @@ module Rails
[WARNING] Rails cannot recover singular form from its plural form '%s'.
Please setup custom inflection rules for this noun before running the generator in config/initializers/inflections.rb.
WARNING
INFLECTION_IMPOSSIBLE_ERROR_MESSAGE = <<~ERROR
Rails cannot recover the underscored form from its camelcase form '%s'.
Please use an underscored name instead, either '%s' or '%s'.
Or setup custom inflection rules for this noun before running the generator in config/initializers/inflections.rb.
ERROR
mattr_accessor :skip_warn
def self.included(base) #:nodoc:
@ -19,7 +24,7 @@ module Rails
def initialize(args, *_options)
super
if name == name.pluralize && name.singularize != name.pluralize && !options[:force_plural]
if plural_model_name?(name) && !options[:force_plural]
singular = name.singularize
unless ModelHelpers.skip_warn
say PLURAL_MODEL_NAME_WARN_MESSAGE % [name, singular]
@ -27,11 +32,30 @@ module Rails
name.replace singular
assign_names!(name)
end
if name.singularize != name.pluralize.singularize && ! ModelHelpers.skip_warn
if inflection_impossible?(name)
option1 = name.singularize.underscore
option2 = name.pluralize.underscore.singularize
raise Error, INFLECTION_IMPOSSIBLE_ERROR_MESSAGE % [name, option1, option2]
end
if irregular_model_name?(name) && ! ModelHelpers.skip_warn
say IRREGULAR_MODEL_NAME_WARN_MESSAGE % [name.pluralize]
end
ModelHelpers.skip_warn = true
end
private
def plural_model_name?(name)
name == name.pluralize && name.singularize != name.pluralize
end
def irregular_model_name?(name)
name.singularize != name.pluralize.singularize
end
def inflection_impossible?(name)
name != name.underscore &&
name.singularize.underscore != name.pluralize.underscore.singularize
end
end
end
end

View File

@ -115,6 +115,16 @@ class ModelGeneratorTest < Rails::Generators::TestCase
assert_no_match("[WARNING] Rails cannot recover singular form from its plural form", regular_content)
end
def test_impossible_inflection_rules_raises_an_error
content = capture(:stderr) { run_generator ["BFF"] }
message = <<~MESSAGE
Rails cannot recover the underscored form from its camelcase form 'BFF'.
Please use an underscored name instead, either 'bff' or 'bf_f'.
Or setup custom inflection rules for this noun before running the generator in config/initializers/inflections.rb.
MESSAGE
assert_match message, content
end
def test_model_with_underscored_parent_option
run_generator ["account", "--parent", "admin/account"]
assert_file "app/models/account.rb", /class Account < Admin::Account/