class RuboCop::Cop::Style::FormatString

This cop enforces the use of a single string formatting utility. Valid options include Kernel#format, Kernel#sprintf and String#%.

The detection of String#% cannot be implemented in a reliable manner for all cases, so only two scenarios are considered - if the first argument is a string literal and if the second argument is an array literal.

Public Instance Methods

on_send(node) click to toggle source
# File lib/rubocop/cop/style/format_string.rb, line 16
def on_send(node)
  add_offense(node, :selector) if offending_node?(node)
end

Private Instance Methods

format?(node) click to toggle source
# File lib/rubocop/cop/style/format_string.rb, line 43
def format?(node)
  format_method?(:format, node)
end
format_method?(name, node) click to toggle source
# File lib/rubocop/cop/style/format_string.rb, line 33
def format_method?(name, node)
  receiver, method_name, *args = *node

  # commands have no explicit receiver
  return false unless !receiver && method_name == name

  # we do an argument count check to reduce false positives
  args.size >= 2
end
message(node) click to toggle source
# File lib/rubocop/cop/style/format_string.rb, line 59
def message(node)
  _receiver_node, method_name, *_arg_nodes = *node

  preferred =
    if style == :percent
      'String#%'
    else
      style
    end

  method_name = 'String#%' if method_name == :%

  "Favor `#{preferred}` over `#{method_name}`."
end
offending_node?(node) click to toggle source
# File lib/rubocop/cop/style/format_string.rb, line 22
def offending_node?(node)
  case style
  when :format
    sprintf?(node) || percent?(node)
  when :sprintf
    format?(node) || percent?(node)
  when :percent
    format?(node) || sprintf?(node)
  end
end
percent?(node) click to toggle source
# File lib/rubocop/cop/style/format_string.rb, line 51
def percent?(node)
  receiver_node, method_name, *arg_nodes = *node

  method_name == :% &&
    ([:str, :dstr].include?(receiver_node.type) ||
     arg_nodes[0].type == :array)
end
sprintf?(node) click to toggle source
# File lib/rubocop/cop/style/format_string.rb, line 47
def sprintf?(node)
  format_method?(:sprintf, node)
end