]> git.openstreetmap.org Git - rails.git/blob - .rubocop/specific_action_names.rb
Merge remote-tracking branch 'upstream/pull/5533'
[rails.git] / .rubocop / specific_action_names.rb
1 # frozen_string_literal: true
2
3 module RuboCop
4   module Cop
5     module Rails
6       # Use only specific action names.
7       #
8       # It is good practice to separate controller classes rather than adding more actions as needed.
9       # By default, the 7 CRUD action names are specified that are generated by the Rails scaffold.
10       #
11       # @example
12       #   # bad
13       #   class UsersController < ApplicationController
14       #     def articles
15       #     end
16       #   end
17       #
18       #   # good
19       #   class UserArticlesController < ApplicationController
20       #     def index
21       #     end
22       #   end
23       class SpecificActionNames < Base
24         include VisibilityHelp
25
26         MSG = "Use only specific action names."
27
28         # @param node [RuboCop::AST::DefNode]
29         # @return [void]
30         def on_def(node)
31           return unless bad?(node)
32
33           add_offense(
34             node.location.name,
35             :message => format(
36               "Use only specific action names (%<action_names>s).",
37               :action_names => configured_action_names.join(", ")
38             )
39           )
40         end
41
42         private
43
44         # @param node [RuboCop::AST::DefNode]
45         # @return [Boolean]
46         def action?(node)
47           node_visibility(node) == :public
48         end
49
50         # @param node [RuboCop::AST::DefNode]
51         # @return [Boolean]
52         def bad?(node)
53           action?(node) && !configured_action_name?(node)
54         end
55
56         # @param node [RuboCop::AST::DefNode]
57         # @return [Boolean]
58         def configured_action_name?(node)
59           configured_action_names.include?(node.method_name.to_s)
60         end
61
62         # @return [Array<String>]
63         def configured_action_names
64           cop_config["ActionNames"]
65         end
66       end
67     end
68   end
69 end