diff options
author | Bob Van Landuyt <bob@vanlanduyt.co> | 2018-08-16 15:15:54 +0300 |
---|---|---|
committer | Bob Van Landuyt <bob@vanlanduyt.co> | 2018-08-25 19:43:21 +0300 |
commit | 08c0a1b8527287457cb8db5f41c368af192c606b (patch) | |
tree | 2534ee8c44c34213d4d82cb8aad0d61fa326b78f /rubocop/cop/ruby_interpolation_in_translation.rb | |
parent | 842377ab3c5b80a3758ad8c36dc3358bd265bc10 (diff) |
Reject ruby interpolation in externalized strings
When using ruby interpolation in externalized strings, they can't be
detected. Which means they will never be presented to be translated.
To mix variables into translations we need to use `sprintf`
instead.
Instead of:
_("Hello #{subject}")
Use:
_("Hello %{subject}) % { subject: 'world' }
Diffstat (limited to 'rubocop/cop/ruby_interpolation_in_translation.rb')
-rw-r--r-- | rubocop/cop/ruby_interpolation_in_translation.rb | 29 |
1 files changed, 29 insertions, 0 deletions
diff --git a/rubocop/cop/ruby_interpolation_in_translation.rb b/rubocop/cop/ruby_interpolation_in_translation.rb new file mode 100644 index 00000000000..b9411fcfd6c --- /dev/null +++ b/rubocop/cop/ruby_interpolation_in_translation.rb @@ -0,0 +1,29 @@ +# frozen_string_literal: true + +module RuboCop + module Cop + class RubyInterpolationInTranslation < RuboCop::Cop::Cop + MSG = "Don't use ruby interpolation \#{} inside translated strings, instead use \%{}" + + TRANSLATION_METHODS = ':_ :s_ :N_ :n_' + RUBY_INTERPOLATION_REGEX = /.*\#\{.*\}/ + + def_node_matcher :translation_method?, <<~PATTERN + (send nil? {#{TRANSLATION_METHODS}} $dstr ...) + PATTERN + + def_node_matcher :plural_translation_method?, <<~PATTERN + (send nil? :n_ str $dstr ...) + PATTERN + + def on_send(node) + interpolation = translation_method?(node) || plural_translation_method?(node) + return unless interpolation + + interpolation.descendants.each do |possible_violation| + add_offense(possible_violation, message: MSG) if possible_violation.type != :str + end + end + end + end +end |