Class: RuboCop::Cop::Netsoft::AuthHttpPositionalArguments

Inherits:
RuboCop::Cop
  • Object
show all
Extended by:
TargetRailsVersion
Defined in:
lib/netsoft/rubocop/cops/netsoft/auth_http_positional_arguments.rb

Overview

This cop is used to identify usages of http methods like ‘get`, `post`, `put`, `patch` without the usage of keyword arguments in your tests and change them to use keyword args. This cop only applies to Rails >= 5. If you are running Rails < 5 you should disable the Netsoft/HttpPositionalArguments cop or set your TargetRailsVersion in your .rubocop.yml file to 4.0, etc.

Examples:

# bad
get :new, { user_id: 1}

# good
get :new, params: { user_id: 1 }

Constant Summary collapse

MSG =
'Use keyword arguments instead of positional arguments for http call: `%<verb>s`.'
KEYWORD_ARGS =
i[method params session body flash xhr as headers env].freeze
HTTP_METHODS =
i[get post put patch delete head].freeze
HTTP_AUTH_METHODS =
i[get_with post_with put_with patch_with delete_with].freeze

Instance Method Summary collapse

Instance Method Details

#autocorrect(node) ⇒ Object

given a pre Rails 5 method: get :new, @user.id, {}

the result should look like:

get :new, params: { user_id: @user.id }, session: {}

the http_method is the method used to call the controller the controller node can be a symbol, method, object or string that represents the path/action on the Rails controller the data is the http parameters and environment sent in the Rails 5 http call

Returns:

  • lambda of auto correct procedure



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/netsoft/rubocop/cops/netsoft/auth_http_positional_arguments.rb', line 65

def autocorrect(node)
  has_auth = HTTP_AUTH_METHODS.include?(node.method_name.to_sym)
  if has_auth
    user, http_path, *data = *node.arguments
  else
    http_path, *data = *node.arguments
  end

  controller_action = http_path.source
  params = convert_hash_data(data.first, 'params')
  session = convert_hash_data(data.last, 'session') if data.size > 1
  # the range of the text to replace, which is the whole line
  code_to_replace = node.loc.expression
  # what to replace with
  format = parentheses_format(node)
  new_code = format % {name: node.method_name,
                    action: has_auth ? [user.source, controller_action].join(',') : controller_action,
                    params: params, session: session}
  ->(corrector) { corrector.replace(code_to_replace, new_code) }
end

#on_send(node) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/netsoft/rubocop/cops/netsoft/auth_http_positional_arguments.rb', line 39

def on_send(node)
  message = MSG % {verb: node.method_name}

  http_request?(node) do |data|
    return unless needs_conversion?(data)

    add_offense(node, location: :selector, message: message)
  end

  http_auth_request?(node) do |data|
    return unless auth_needs_conversion?(data)

    add_offense(node, location: :selector, message: message)
  end
end