Class: Zugzwang::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/zugzwang/connection/populate.rb,
lib/zugzwang/connection/connection.rb

Instance Method Summary collapse

Constructor Details

#initialize(database_path, adapter) ⇒ Connection

Returns a new instance of Connection.



6
7
8
9
10
11
12
# File 'lib/zugzwang/connection/connection.rb', line 6

def initialize(database_path, adapter)
    @database_path = database_path
    @adapter = adapter
    case adapter
    when :sqlite then @database = Sequel.sqlite("#{database_path}.sqlite3")
    end
end

Instance Method Details

#populate(items) ⇒ Object



8
9
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
62
63
# File 'lib/zugzwang/connection/populate.rb', line 8

def populate(items)
    return unless create()

    files = items.map{|i|File.file?(i) ? Dir[i] : Dir["#{i}/**/*.pgn"]}.flatten
    puts if files.map{|f|File.file? f}.any?{|f|f==true}

    files.each do |f|
        record = {}
        prev = ''

        # Progress bar
        lines = `sed -n '=' #{f} | wc -l`.to_i
        puts "\e[90mProcessing file:\e[0m \e[1m#{f}\e[0m"
        progress_bar = ProgressBar.create(
            :title => 'Progress',
            total: lines,
            progress_mark: "\e[1;35m#{?#}\e[0m",
            remainder_mark: ?.,
            format: "%t: %p%% (Line: %c/%C) %B"
        )

        # Processing file
        File.open(f,'r').each do |line|
            if prev =~ /\A\[.*\Z/ && line =~ /\A[\n\r].*\Z/
                @database[:games].insert(**record)
                record = {}
                prev = line
                progress_bar.increment
                next
            end
            if line =~ /\A([\n\r]|[0-9]).*\Z/
                prev = line
                progress_bar.increment
                next
            end
            subbed = line.gsub(%r{[\r\n\[\]\"]},'')
            field, value = subbed.split(' ', 2)
            field = field.to_sym
            if FIELDS[field]
                record[field] = case FIELDS[field][:type]
                when :string  then value
                when :integer then value.to_i
                when :date    then Date.parse(value)
                when :time    then value
                end
            end
            prev = line
            progress_bar.increment
        end
    end

    case @adapter
    when :sqlite
        puts "\n\e[92mComplete\e[0m: Populated #{@adapter} database at \e[1m#{@database_path}.sqlite3\e[0m."
    end
end