Class: Rubocop::Cop::Style::MethodAndVariableSnakeCase
- Inherits:
-
Cop
- Object
- Cop
- Rubocop::Cop::Style::MethodAndVariableSnakeCase
show all
- Defined in:
- lib/rubocop/cop/style/method_and_variable_snake_case.rb
Overview
This cop makes sure that all methods and variables use
snake_case for their names. Some special arrangements have to be
made for operator methods.
Constant Summary
collapse
- MSG =
'Use snake_case for methods and variables.'
- SNAKE_CASE =
/^@?[\da-z_]+[!?=]?$/
- OPERATOR_METHODS =
%w(
| ^ & <=> == === =~ > >= < <= << >>
+ - * / % ** ~ +@ -@ [] []= ` ! != !~
).map(&:to_sym)
Instance Attribute Summary
Attributes inherited from Cop
#autocorrect, #corrections, #debug, #disabled_lines, #offences
Instance Method Summary
collapse
Methods inherited from Cop
#add_offence, all, #autocorrect_action, cop_name, cop_type, #do_autocorrect, #ignore_node, inherited, #initialize, lint?, #name, rails?, style?
Instance Method Details
#investigate(processed_source) ⇒ Object
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
# File 'lib/rubocop/cop/style/method_and_variable_snake_case.rb', line 19
def investigate(processed_source)
ast = processed_source.ast
return unless ast
on_node([:def, :defs, :lvasgn, :ivasgn, :send], ast) do |n|
name = case n.type
when :def
name_of_instance_method(n)
when :defs
name_of_singleton_method(n)
when :lvasgn, :ivasgn
name_of_variable(n)
when :send
name_of_setter(n)
end
next unless name
next if name =~ SNAKE_CASE || OPERATOR_METHODS.include?(name)
add_offence(:convention, n.location.expression, MSG)
end
end
|
#name_of_instance_method(def_node) ⇒ Object
41
42
43
|
# File 'lib/rubocop/cop/style/method_and_variable_snake_case.rb', line 41
def name_of_instance_method(def_node)
def_node.children.first
end
|
#name_of_setter(send_node) ⇒ Object
53
54
55
56
57
58
|
# File 'lib/rubocop/cop/style/method_and_variable_snake_case.rb', line 53
def name_of_setter(send_node)
receiver, method_name = *send_node
return nil unless receiver && receiver.type == :self
return nil unless method_name.to_s.end_with?('=')
method_name
end
|
#name_of_singleton_method(defs_node) ⇒ Object
45
46
47
|
# File 'lib/rubocop/cop/style/method_and_variable_snake_case.rb', line 45
def name_of_singleton_method(defs_node)
defs_node.children[1]
end
|
#name_of_variable(vasgn_node) ⇒ Object
49
50
51
|
# File 'lib/rubocop/cop/style/method_and_variable_snake_case.rb', line 49
def name_of_variable(vasgn_node)
vasgn_node.children.first
end
|