class RuboCop::Cop::Style::Encoding

Checks ensures source files have no utf-8 encoding comments. @example

# bad
# encoding: UTF-8
# coding: UTF-8
# -*- coding: UTF-8 -*-

Constants

ENCODING_PATTERN
MSG
SHEBANG

Public Instance Methods

on_new_investigation() click to toggle source
# File lib/rubocop/cop/style/encoding.rb, line 20
def on_new_investigation
  return if processed_source.buffer.source.empty?

  comments.each do |line_number, comment|
    next unless offense?(comment)

    register_offense(line_number, comment)
  end
end

Private Instance Methods

comments() click to toggle source
# File lib/rubocop/cop/style/encoding.rb, line 32
def comments
  processed_source.lines.each.with_index.with_object({}) do |(line, line_number), comments|
    next if line.start_with?(SHEBANG)

    comment = MagicComment.parse(line)
    return comments unless comment.valid?

    comments[line_number + 1] = comment
  end
end
offense?(comment) click to toggle source
# File lib/rubocop/cop/style/encoding.rb, line 43
def offense?(comment)
  comment.encoding_specified? && comment.encoding.casecmp('utf-8').zero?
end
register_offense(line_number, comment) click to toggle source
# File lib/rubocop/cop/style/encoding.rb, line 47
def register_offense(line_number, comment)
  range = processed_source.buffer.line_range(line_number)

  add_offense(range) do |corrector|
    text = comment.without(:encoding)

    if text.blank?
      corrector.remove(range_with_surrounding_space(range, side: :right))
    else
      corrector.replace(range, text)
    end
  end
end