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

Inherits:
RuboCop::Cop show all
Defined in:
lib/rubocop/cop/rails/match_route.rb

Overview

This cop 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.'
HTTP_METHODS =
%i[get post put patch delete].freeze

Instance Method Summary collapse

Instance Method Details

#autocorrect(node) ⇒ Object



50
51
52
53
54
55
56
57
58
# File 'lib/rubocop/cop/rails/match_route.rb', line 50

def autocorrect(node)
  match_method_call?(node) do |path_node, options_node|
    options_node = options_node.first

    lambda do |corrector|
      corrector.replace(node, replacement(path_node, options_node))
    end
  end
end

#on_send(node) ⇒ Object



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

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?
      message = format(MSG, http_method: 'get')
      add_offense(node, message: message)
    else
      via = extract_via(options_node)
      if via.size == 1 && http_method?(via.first)
        message = format(MSG, http_method: via.first)
        add_offense(node, message: message)
      end
    end
  end
end