class RuboCop::Cop::Performance::StringIdentifierArgument
respond_to?(“string_#{interpolation}”)
# good - using a symbol when string interpolation is involved causes a performance regression.
const_defined?(“#{module_path}::Base”)
const_source_location(“#{module_path}::Base”)
const_get(“#{module_path}::Base”)
# good - these methods don’t support namespaced symbols
instance_variable_get(:@ivar)
attr_accessor :do_something
send(:do_something)
# good
instance_variable_get(‘@ivar’)
attr_accessor ‘do_something’
send(‘do_something’)
# bad
@example
and the following examples are parts of it.
This cop targets methods that take identifier (e.g. method name) argument
It prevents the redundancy of the internal string-to-symbol conversion.
by symbol identifier argument.
Identifies places where string identifier argument can be replaced
def argument_replacement(node, value)
def argument_replacement(node, value) if node.str_type? value.to_sym.inspect else ":\"#{value.to_sym}\"" end end
def on_send(node)
def on_send(node) return if COMMAND_METHODS.include?(node.method_name) && node.receiver string_arguments(node).each do |string_argument| string_argument_value = string_argument.value next if string_argument_value.include?(' ') || string_argument_value.include?('::') register_offense(string_argument, string_argument_value) end end
def register_offense(argument, argument_value)
def register_offense(argument, argument_value) replacement = argument_replacement(argument, argument_value) message = format(MSG, symbol_arg: replacement, string_arg: argument.source) add_offense(argument, message: message) do |corrector| corrector.replace(argument, replacement) end end
def string_arguments(node)
def string_arguments(node) arguments = if node.method?(TWO_ARGUMENTS_METHOD) [node.first_argument, node.arguments[1]] elsif MULTIPLE_ARGUMENTS_METHODS.include?(node.method_name) node.arguments else [node.first_argument] end arguments.compact.filter(&:str_type?) end