Class: JsDuck::Util::IO

Inherits:
Object
  • Object
show all
Defined in:
lib/jsduck/util/io.rb

Overview

A helper to use instead the builtin IO class to read files in correct encoding.

By default in Ruby 1.9 the encoding is auto-detected, which can have surprising results. So in here we read in all files in UTF-8 (the default) or in some other encoding specified through –encoding option and convert it to UTF-8 internally.

We also allow for UTF-8 byte order mark.

Constant Summary collapse

@@encoding =
"BOM|UTF-8"

Class Method Summary collapse

Class Method Details

.configure(opts) ⇒ Object

Configures the encoding from command line options.



17
18
19
# File 'lib/jsduck/util/io.rb', line 17

def self.configure(opts)
  encoding = opts.encoding if opts.encoding
end

.encoding=(e) ⇒ Object

Sets the external encoding to be used for reading files. When it’s different from UTF-8, the input will be converted to UTF-8.



23
24
25
26
27
28
29
# File 'lib/jsduck/util/io.rb', line 23

def self.encoding=(e)
  if e =~ /^(BOM\|)?UTF-8$/i
    @@encoding = e
  else
    @@encoding = e+":UTF-8"
  end
end

.read(filename) ⇒ Object

Reads given filename into string



32
33
34
# File 'lib/jsduck/util/io.rb', line 32

def self.read(filename)
  File.open(filename, "r:"+@@encoding) {|f| self.strip_utf8_bom(f.read) }
end

.strip_utf8_bom(string) ⇒ Object

Takes care of removing UTF-8 byte order mark in Ruby <= 1.8 which doesn’t have built-in encodings support.



38
39
40
41
42
43
44
# File 'lib/jsduck/util/io.rb', line 38

def self.strip_utf8_bom(string)
  if "".respond_to?(:encoding)
    string
  else
    string.sub(/\A\xEF\xBB\xBF/, "")
  end
end