Class: RuboCop::Cop::Chef::Style::AttributeKeys

Inherits:
RuboCop::Cop
  • Object
show all
Includes:
RuboCop::Cop::ConfigurableEnforcedStyle
Defined in:
lib/rubocop/cop/chef/style/attribute_keys.rb

Overview

Check which style of keys are used to access node attributes.

There are two supported styles: “symbols” and “strings”.

Examples:

when configuration is ‘EnforcedStyle: symbols`


### incorrect
node['foo']
node["foo"]

### correct
node[:foo]

when configuration is ‘EnforcedStyle: strings`


### incorrect
node[:foo]

### correct
node['foo']
node["foo"]

Constant Summary collapse

MSG =
'Use %s to access node attributes'
RESTRICT_ON_SEND =
[:[]].freeze

Instance Method Summary collapse

Instance Method Details

#autocorrect(node) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
# File 'lib/rubocop/cop/chef/style/attribute_keys.rb', line 80

def autocorrect(node)
  lambda do |corrector|
    key_string = node.children.first.to_s
    key_replacement = if style == :symbols
                        key_string.to_sym.inspect
                      else # strings
                        key_string.inspect
                      end
    corrector.replace(node, key_replacement)
  end
end

#on_node_attribute_access(node) ⇒ Object



70
71
72
73
74
75
76
77
78
# File 'lib/rubocop/cop/chef/style/attribute_keys.rb', line 70

def on_node_attribute_access(node)
  if node.str_type?
    style_detected(:strings)
    add_offense(node, message: MSG % style, severity: :refactor) if style == :symbols
  elsif node.sym_type?
    style_detected(:symbols)
    add_offense(node, message: MSG % style, severity: :refactor) if style == :strings
  end
end

#on_send(node) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/rubocop/cop/chef/style/attribute_keys.rb', line 57

def on_send(node)
  if node_attribute_access?(node) || node_level_attribute_access?(node)
    # node is first child for #[], need to look for the outermost parent too.
    outer_node = node
    while outer_node.parent && outer_node.parent.send_type? && outer_node.parent.children[1] == :[]
      on_node_attribute_access(outer_node.children[2])
      outer_node = outer_node.parent
    end
    # One last time for the outer-most access.
    on_node_attribute_access(outer_node.children[2])
  end
end