Module: Unicode::DisplayWidth

Defined in:
lib/unicode/display_width.rb

Constant Summary collapse

VERSION =
'0.2.0'
DATA_DIR =
File.join(File.dirname(__FILE__), '../../data/')
TABLE_FILE =
DATA_DIR + 'EastAsianWidth.index'
DATA_FILE =
DATA_DIR + 'EastAsianWidth.txt'

Class Method Summary collapse

Class Method Details

.build_tableObject

# # index



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/unicode/display_width.rb', line 33

def build_table
  data = File.open DATA_FILE
  data.rewind
  table = {}
  dir = File.dirname TABLE_FILE
  Dir.mkdir(dir) unless Dir.exists?(dir)
  data.each_line{ |line|
    line =~ /^(\S+?);(\S+)\s+#.*$/
    if $1 && $2
      cps, width = $1, $2
      if cps['..']
        range = Range.new *cps.split('..').map{ |cp| cp.to_i(16) }
        range.each{ |cp| table[ cp ] = width.to_sym }
      else
        table[ cps.to_i(16) ] = width.to_sym
      end
    end

  }
  File.open(TABLE_FILE, 'wb') { |f| Marshal.dump(table, f) }
end

.codepoint(n) ⇒ Object Also known as: width, of



23
24
25
26
# File 'lib/unicode/display_width.rb', line 23

def codepoint(n)
  n = n.to_s.unpack('U')[0] unless n.is_a? Integer
  table[n] or raise ArgumentError, 'codepoint not found'
end

.tableObject

# # lookup



15
16
17
18
19
20
21
# File 'lib/unicode/display_width.rb', line 15

def table
  if @table
    @table
  else
    @table = Marshal.load File.respond_to?(:binread) ? File.binread(TABLE_FILE) : File.read(TABLE_FILE)
  end
end