Class: RuboCop::Cop::Rails::MatchRoute

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/rails/match_route.rb

Overview

Identifies places where defining routes with ‘match` can be replaced with a specific HTTP method.

Don’t use ‘match` to define any routes unless there is a need to map multiple request types among [:get, :post, :patch, :put, :delete] to a single action using the `:via` option.

Examples:

# bad
match ':controller/:action/:id'
match 'photos/:id', to: 'photos#show', via: :get

# good
get ':controller/:action/:id'
get 'photos/:id', to: 'photos#show'
match 'photos/:id', to: 'photos#show', via: [:get, :post]
match 'photos/:id', to: 'photos#show', via: :all

Constant Summary collapse

MSG =
'Use `%<http_method>s` instead of `match` to define a route.'
RESTRICT_ON_SEND =
%i[match].freeze
HTTP_METHODS =
%i[get post put patch delete].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/rubocop/cop/rails/match_route.rb', line 34

def on_send(node)
  match_method_call?(node) do |path_node, options_node|
    return unless within_routes?(node)

    options_node = path_node.hash_type? ? path_node : options_node.first

    if options_node.nil?
      register_offense(node, 'get')
    else
      via = extract_via(options_node)
      return unless via.size == 1 && http_method?(via.first)

      register_offense(node, via.first)
    end
  end
end