Class: RuboCop::Cop::Cobra::ViewComponentFilePlacement

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

Overview

This cop disallows adding global view_components to the ‘app/components` directory.

The goal is to encourage developers to put new view_components inside the correct namespace, where they can be more modularly isolated and ownership is clear.

The correct namespace is ‘app/components/my_component/resource/view_component.rb. Similar to how `app/views` templates are nested in a directory named after the controller’s resource.

Examples:

# bad
# path: components/my_component/app/components/foo_component.rb
class FooComponent < ::ViewComponent::Base
  # ...
end

# bad
# path: components/my_component/app/components/my_component/foo_component.rb
module MyComponent
  class FooComponent < MyComponent::ApplicationComponent
    # ...
  end
end

# acceptable
# path: components/my_component/app/components/my_component/application_component.rb
module MyComponent
  class ApplicationComponent < ::ViewComponent::Base
      # ...
    end
  end
end

# good
# path: components/my_component/app/components/my_component/resource/foo_component.rb
module MyComponent
  module Resource
    class FooComponent < MyComponent::ApplicationComponent
      # ...
    end
  end
end

Constant Summary collapse

FILE_PLACEMENT_MSG =
"Nest ViewComponent definitions in the parent component and resource namespace. " \
"For example: `%<correct_path>s`"

Instance Method Summary collapse

Instance Method Details

#investigate(processed_source) ⇒ Object



53
54
55
56
57
58
59
60
# File 'lib/rubocop/cop/cobra/view_component_file_placement.rb', line 53

def investigate(processed_source)
  return if processed_source.blank?
  return unless path_contains_matcher?
  return if namespaced_correctly?

  add_offense(processed_source.ast,
              message: format(FILE_PLACEMENT_MSG, correct_path: correct_path))
end