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
# 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"

  contents.force_encoding(strip_special(encoding))
end

.strip_special(encoding) ⇒ Object



20
21
22
23
24
25
26
# File 'lib/live_ast/reader.rb', line 20

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