Class: RuboCop::Cop::Flexport::NewGlobalModel

Inherits:
RuboCop::Cop
  • Object
show all
Defined in:
lib/rubocop/cop/flexport/new_global_model.rb

Overview

This cop disallows adding new models to the ‘app/models` directory.

The goal is to encourage developers to put new models inside Rails Engines (or at least namespaces), where they can be more modularly isolated and ownership is clear.

Use RuboCop’s standard ‘Exclude` file list parameter to exclude existing global model files from counting as violations for this cop.

If you have a monorepo with multiple Rails services, you may wish to set GlobalModelsPath to something more specific than ‘app/models` so that it only matches the main monolith service and allows global models in other, smaller services. To do this, just set GlobalModelsPath to e.g. `flexport/app/models` in your `.rubocop.yml`.

Examples:

AllowNamespacedGlobalModels: true (default)

# When `AllowNamespacedGlobalModels` is true, the cop only forbids
# additions at the top-level directory.

# bad
# path: app/models/my_new_global_model.rb
class MyNewGlobalModel < ApplicationRecord
  # ...
end

# good
# path: app/models/my_namespace/my_new_global_model.rb
class MyNamespace::MyNewGlobalModel < ApplicationRecord
  # ...
end

# good
# path: engines/my_engine/app/models/my_engine/my_new_engine_model.rb
class MyEngine::MyNewEngineModel < ApplicationRecord
  # ...
end

AllowNamespacedGlobalModels: false

# When `AllowNamespacedGlobalModels` is false, the cop forbids all
# new models in this directory and its descendants.

# bad
# path: app/models/my_new_global_model.rb
class MyNewGlobalModel < ApplicationRecord
  # ...
end

# bad
# path: app/models/my_namespace/my_new_global_model.rb
class MyNamespace::MyNewGlobalModel < ApplicationRecord
  # ...
end

# good
# path: engines/my_engine/app/models/my_engine/my_new_engine_model.rb
class MyEngine::MyNewEngineModel < ApplicationRecord
  # ...
end

Constant Summary collapse

ALLOW_NAMESPACES_MSG =
'Do not add new top-level global models in `app/models`. ' \
'Prefer namespaced models like `app/models/foo/bar.rb` or ' \
'or models inside Rails Engines.'
DISALLOW_NAMESPACES_MSG =
'Do not add new global models in `app/models`. ' \
'Instead add new models to Rails Engines.'

Instance Method Summary collapse

Instance Method Details

#investigate(processed_source) ⇒ Object



74
75
76
77
78
79
80
81
# File 'lib/rubocop/cop/flexport/new_global_model.rb', line 74

def investigate(processed_source)
  return if processed_source.blank?

  path = processed_source.file_path
  return unless global_rails_model?(path)

  add_offense(processed_source.ast)
end