Sha256: bd76fc47e04552b7cc71f7bbe1aaf5e0ee22880e31e641e57e10e2c7fc6463d0

Contents?: true

Size: 1.68 KB

Versions: 6

Compression:

Stored size: 1.68 KB

Contents

# frozen_string_literal: true

# rubocop:disable Style/AsciiComments

module RuboCop
  module Cop
    module Style
      # This cop checks for non-ascii (non-English) characters
      # in comments. You could set an array of allowed non-ascii chars in
      # `AllowedChars` attribute (copyright notice "©" by default).
      #
      # @example
      #   # bad
      #   # Translates from English to 日本語。
      #
      #   # good
      #   # Translates from English to Japanese
      class AsciiComments < Base
        include RangeHelp

        MSG = 'Use only ascii symbols in comments.'

        def on_new_investigation
          processed_source.comments.each do |comment|
            next if comment.text.ascii_only?
            next if only_allowed_non_ascii_chars?(comment.text)

            add_offense(first_offense_range(comment))
          end
        end

        private

        def first_offense_range(comment)
          expression    = comment.loc.expression
          first_offense = first_non_ascii_chars(comment.text)

          start_position = expression.begin_pos +
                           comment.text.index(first_offense)
          end_position   = start_position + first_offense.length

          range_between(start_position, end_position)
        end

        def first_non_ascii_chars(string)
          string.match(/[^[:ascii:]]+/).to_s
        end

        def only_allowed_non_ascii_chars?(string)
          non_ascii = string.scan(/[^[:ascii:]]/)
          (non_ascii - allowed_non_ascii_chars).empty?
        end

        def allowed_non_ascii_chars
          cop_config['AllowedChars'] || []
        end
      end
    end
  end
end
# rubocop:enable Style/AsciiComments

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
rubocop-1.12.1 lib/rubocop/cop/style/ascii_comments.rb
rubocop-1.12.0 lib/rubocop/cop/style/ascii_comments.rb
rubocop-1.11.0 lib/rubocop/cop/style/ascii_comments.rb
rubocop-1.10.0 lib/rubocop/cop/style/ascii_comments.rb
rubocop-1.9.1 lib/rubocop/cop/style/ascii_comments.rb
rubocop-1.9.0 lib/rubocop/cop/style/ascii_comments.rb