Class: RuboCop::Cop::I18n::GetText::DecorateStringFormattingUsingPercent

Inherits:
Cop
  • Object
show all
Defined in:
lib/rubocop/cop/i18n/gettext/decorate_string_formatting_using_percent.rb

Overview

When using a decorated string to support I18N, any strings inside the decoration should not contain sprintf style formatting as this makes it hard to translate the string. This cop checks the decorators listed in GetText.supported_decorators and checks for each of the formats in SUPPORTED_FORMATS. NOTE: this cop does not check for all possible sprintf formats.

Examples:


# bad

_("result is %s" % ["value"])
n_("a string" + "a string with a %-3.1f" % [size])
N_("a string" + "a string with a %04d" % [size])

# good

_("result is %{detail}" % {detail: message})

Constant Summary collapse

SUPPORTED_FORMATS =
%w[b B d i o u x X e E f g G a A c p s].freeze

Instance Method Summary collapse

Methods inherited from Cop

#highlights, #messages

Instance Method Details

#on_send(node) ⇒ Object



27
28
29
30
31
32
33
34
35
# File 'lib/rubocop/cop/i18n/gettext/decorate_string_formatting_using_percent.rb', line 27

def on_send(node)
  decorator_name = node.loc.selector.source
  return unless GetText.supported_decorator?(decorator_name)
  _, method_name, *arg_nodes = *node
  if !arg_nodes.empty? && contains_string_with_percent_format?(arg_nodes)
    message_section = arg_nodes[0]
    add_offense(message_section, :expression, "'#{method_name}' function, message string should not contain sprintf style formatting (ie %s)")
  end
end