Class: Rubocop::Cop::Style::MethodAndVariableSnakeCase
- Inherits:
-
Cop
- Object
- Parser::Rewriter
- 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, #debug, #disabled_lines, #offences
Instance Method Summary
collapse
Methods inherited from Cop
#add_offence, #autocorrect_action, cop_name, cop_type, #do_autocorrect, #ignore_node, inherited, #initialize, lint?, #name, rails?, style?
Instance Method Details
#inspect(source_buffer, source, tokens, node, comments) ⇒ Object
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
# File 'lib/rubocop/cop/style/method_and_variable_snake_case.rb', line 19
def inspect(source_buffer, source, tokens, node, )
return unless node
on_node([:def, :defs, :lvasgn, :ivasgn, :send], node) 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
40
41
42
|
# File 'lib/rubocop/cop/style/method_and_variable_snake_case.rb', line 40
def name_of_instance_method(def_node)
def_node.children.first
end
|
#name_of_setter(send_node) ⇒ Object
52
53
54
55
56
57
|
# File 'lib/rubocop/cop/style/method_and_variable_snake_case.rb', line 52
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
44
45
46
|
# File 'lib/rubocop/cop/style/method_and_variable_snake_case.rb', line 44
def name_of_singleton_method(defs_node)
defs_node.children[1]
end
|
#name_of_variable(vasgn_node) ⇒ Object
48
49
50
|
# File 'lib/rubocop/cop/style/method_and_variable_snake_case.rb', line 48
def name_of_variable(vasgn_node)
vasgn_node.children.first
end
|