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



8
9
10
11
12
13
14
15
16
17
# File 'lib/live_ast/reader.rb', line 8

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



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

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