Class: RuboCop::Cop::SketchupSuggestions::FileEncoding

Inherits:
SketchUp::Cop show all
Defined in:
lib/rubocop/sketchup/cop/suggestions/file_encoding.rb

Overview

When using __FILE__ and __dir__, beware that Ruby doesn’t apply the correct encoding to the strings under Windows. When they contain non-english characters it will lead to exceptions being raised when the strings are used. Force encoding to work around this.

Examples:

Might fail

basename = File.basename(__FILE__, '.*')

Workaround

file = __FILE__.dup
file.force_encoding('UTF-8') if file.respond_to?(:force_encoding)
basename = File.basename(file, '.*')

Constant Summary collapse

MSG =
'Beware encoding bug with `__FILE__` and `__dir__`.'

Constants inherited from SketchUp::Cop

SketchUp::Cop::SKETCHUP_DEPARTMENT_SEVERITY

Constants included from SketchUp::Config

SketchUp::Config::DEFAULT_CONFIGURATION

Instance Method Summary collapse

Methods inherited from SketchUp::Cop

inherited, #relevant_file?

Instance Method Details

#magic_file?(node) ⇒ Boolean

Returns:

  • (Boolean)


30
31
32
33
34
# File 'lib/rubocop/sketchup/cop/suggestions/file_encoding.rb', line 30

def magic_file?(node)
  node.respond_to?(:str_type?) &&
    node.str_type? &&
    node.source_range.is?('__FILE__')
end

#magic_file_or_dir?(node) ⇒ Boolean

Returns:

  • (Boolean)


36
37
38
# File 'lib/rubocop/sketchup/cop/suggestions/file_encoding.rb', line 36

def magic_file_or_dir?(node)
  magic_file?(node) || magic_dir?(node)
end

#on_assign(node) ⇒ Object Also known as: on_lvasgn, on_masgn, on_casgn, on_ivasgn, on_cvasgn, on_gvasgn, on_or_asgn, on_and_asgn, on_op_asgn



52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/rubocop/sketchup/cop/suggestions/file_encoding.rb', line 52

def on_assign(node)
  lhs, value = *node
  return unless magic_file_or_dir?(value)
  # After assigning __FILE__ or __dir_ to a variable, check the parent
  # scope to whether .force_encoding is called on the variable.
  return if node.parent.nil?

  encoded = force_encoding(node.parent).to_a
  return if encoded.include?(lhs)

  add_offense(node)
end

#on_send(node) ⇒ Object



40
41
42
43
44
45
# File 'lib/rubocop/sketchup/cop/suggestions/file_encoding.rb', line 40

def on_send(node)
  return if file_loaded?(node)
  return if node.arguments.none?(&method(:magic_file_or_dir?))

  add_offense(node, location: :expression)
end