class RuboCop::Cop::Naming::AccessorMethodName
Avoid prefixing accessor method names with ‘get_` or `set_`. Applies to both instance and class methods.
NOTE: Method names starting with ‘get_` or `set_` only register an offense when the methods match the expected arity for getters and setters respectively. Getters (`get_attribute`) must have no arguments to be registered, and setters (`set_attribute(value)`) must have exactly one.
@example
# bad def set_attribute(value) end # good def attribute=(value) end # bad def get_attribute end # good def attribute end # accepted, incorrect arity for getter def get_value(attr) end # accepted, incorrect arity for setter def set_value end
Constants
- MSG_READER
- MSG_WRITER
Public Instance Methods
Source
# File lib/rubocop/cop/naming/accessor_method_name.rb, line 42 def on_def(node) return unless proper_attribute_name?(node) return unless bad_reader_name?(node) || bad_writer_name?(node) message = message(node) add_offense(node.loc.name, message: message) end
Also aliased as: on_defs
Private Instance Methods
Source
# File lib/rubocop/cop/naming/accessor_method_name.rb, line 66 def bad_reader_name?(node) node.method_name.to_s.start_with?('get_') && !node.arguments? end
Source
# File lib/rubocop/cop/naming/accessor_method_name.rb, line 70 def bad_writer_name?(node) node.method_name.to_s.start_with?('set_') && node.arguments.one? && node.first_argument.arg_type? end
Source
# File lib/rubocop/cop/naming/accessor_method_name.rb, line 54 def message(node) if bad_reader_name?(node) MSG_READER elsif bad_writer_name?(node) MSG_WRITER end end
Source
# File lib/rubocop/cop/naming/accessor_method_name.rb, line 62 def proper_attribute_name?(node) !node.method_name.to_s.end_with?('!', '?', '=') end