Class: RuboCop::Cop::Guardrails::RestfulRoutes

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/guardrails/restful_routes.rb

Overview

Detects non-RESTful route definitions.

Routes should use ‘resources` and `resource` exclusively. When you need a custom action, extract a new resource rather than adding bare HTTP verb routes or `member`/`collection` blocks.

Examples:

# bad
get '/posts/:id/publish', to: 'posts#publish'

resources :posts do
  member do
    get :publish
  end
end

# good - extract a new resource
resources :posts do
  resource :publication, only: :create
end

Constant Summary collapse

MSG_VERB =
'Use `resources` or `resource` instead of bare HTTP verb routes.'
MSG_MEMBER =
'Use a new `resources` instead of `member` routes.'
MSG_COLLECTION =
'Use a new `resources` instead of `collection` routes.'
HTTP_VERBS =
%i[get post put patch delete match].to_set.freeze
RESTRICT_ON_SEND =
[*HTTP_VERBS, :member, :collection].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object Also known as: on_csend



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/rubocop/cop/guardrails/restful_routes.rb', line 40

def on_send(node)
  if inside_routes_draw?(node)
    if HTTP_VERBS.include?(node.method_name)
      add_offense(node.loc.selector, message: MSG_VERB) unless inside_member_or_collection?(node)
    elsif node.method?(:member)
      add_offense(node.loc.selector, message: MSG_MEMBER)
    elsif node.method?(:collection)
      add_offense(node.loc.selector, message: MSG_COLLECTION)
    end
  end
end

#route_draw_block?(node) ⇒ Object



36
37
38
# File 'lib/rubocop/cop/guardrails/restful_routes.rb', line 36

def_node_matcher :route_draw_block?, <<~PATTERN
  (block (send (send (send (const nil? :Rails) :application) :routes) :draw) ...)
PATTERN