Class: RuboCop::Cop::Appdev::StringParamKeys

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

Overview

Requires ‘params.fetch(“string_key”)` in controllers. Flags three variants and autocorrects to the blessed form:

params[:foo]           -> params.fetch("foo")
params["foo"]          -> params.fetch("foo")
params.fetch(:foo)     -> params.fetch("foo")
params.fetch("foo")    # already correct

Reinforces two pedagogical points at once: string keys (so students see the hash underneath Rails’ ParameterSet), and ‘.fetch` (so missing keys raise instead of silently returning nil).

Autocorrects. The rewrite from ‘[]` to `.fetch` is behavior-changing when a key is legitimately missing, but author code should never be relying on nil-returning defaults — if it is, the lint catches it.

Constant Summary collapse

MSG_BRACKET_SYM =
"Use `params.fetch(\"%<key>s\")` instead of `params[:%<key>s]`."
MSG_BRACKET_STR =
"Use `params.fetch(\"%<key>s\")` instead of `params[\"%<key>s\"]`."
MSG_FETCH_SYM =
"Use a string key: `params.fetch(\"%<key>s\")`."
RESTRICT_ON_SEND =
[:[], :fetch].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/rubocop/cop/appdev/string_param_keys.rb', line 28

def on_send(node)
  return unless params_receiver?(node.receiver)
  return if node.arguments.empty?

  arg = node.arguments.first

  case node.method_name
  when :[]
    handle_bracket(node, arg)
  when :fetch
    handle_fetch(node, arg)
  end
end