Module: LiveAST::Reader

Defined in:
lib/live_ast/reader.rb

Constant Summary collapse

UTF8_BOM =
/\A\xef\xbb\xbf/
MAGIC_COMMENT =
/\A(?:#!.*?\n)?\s*\#.*(?:en)?coding\s*[:=]\s*([^\s;]+)/

Class Method Summary collapse

Class Method Details

.read(file) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/live_ast/reader.rb', line 9

def self.read(file)
  contents = File.read(file, encoding: "BINARY")

  utf8 = contents.sub!(UTF8_BOM, "") ? "UTF-8" : nil

  # magic comment overrides BOM
  encoding = contents[MAGIC_COMMENT, 1] || utf8 || "US-ASCII"
  encoding = strip_special encoding
  begin
    Encoding.find encoding
  rescue ArgumentError
    raise ArgumentError, "unknown encoding name: #{encoding}"
  end

  contents.force_encoding encoding
end

.strip_special(encoding) ⇒ Object



26
27
28
29
30
31
32
# File 'lib/live_ast/reader.rb', line 26

def self.strip_special(encoding)
  if /\Autf8-mac\Z/i.match?(encoding)
    "UTF8-MAC"
  else
    encoding.sub(/-(unix|dos|mac)\Z/i, "")
  end
end