Class: Alphabet::Reader

Inherits:
Object
  • Object
show all
Defined in:
lib/alphabets/reader.rb

Overview

todo/check: rename to CharReader or something - why? why not?

Class Method Summary collapse

Class Method Details

.parse(txt) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/alphabets/reader.rb', line 10

def self.parse( txt )
  h = {}  ## char(acter) table mappings

  lineno = 0
  txt.each_line do |line|
    lineno += 1
    line = line.strip

    next if line.empty?
    next if line.start_with?( '#' )   ## skip comments too

    ## strip inline (until end-of-line) comments too
    ##  e.g  ţ  t  ## U+0163
    ##   =>  ţ  t
    line = line.sub( /#.*/, '' ).strip
    ## pp line

    values = line.split( /[ \t]+/ )
    ## pp values

    ## check - must be a even - a multiple of two
    if values.size % 2 != 0
      puts "** !!! ERROR !!! - [line:#{lineno}] missing mapping pair - mappings must be even (a multiple of two):"
      pp values
      exit 1
    end

    # add mappings in pairs
    values.each_slice(2) do |slice|
      ## pp slice
      key   = slice[0]
      value = slice[1]

      ## check - key must be a single-character/letter in unicode
      if key.size != 1
        puts "** !!! ERROR !!! - [line:#{lineno}] mapping character must be a single-character, size is #{key.size}"
        pp slice
        exit 1
      end

      ## check - check for duplicates
      if h[ key ]
        puts "** !!! ERROR !!! - [line:#{lineno}] duplicate mapping character; key already present"
        pp slice
        exit 1
      else
        h[ key ] = value
      end
    end
  end
  h
end

.read(path) ⇒ Object

use - rename to read_file or from_file etc. - why? why not?



5
6
7
8
# File 'lib/alphabets/reader.rb', line 5

def self.read( path )   ## use - rename to read_file or from_file etc. - why? why not?
  txt = File.open( path, 'r:utf-8' ).read
  parse( txt )
end