Class: FileSplit::FileSplitter

Inherits:
Object
  • Object
show all
Defined in:
lib/file_split/file_splitter.rb

Overview

The Main File Splitter Class

Instance Method Summary collapse

Instance Method Details

#startObject

Process File Splitting

Example

>> FileSplitter.start
=> void


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
64
65
66
67
68
69
# File 'lib/file_split/file_splitter.rb', line 13

def start
  row_count = 0
  file_count = 1
  headers = []
  footers = []
  out = false
  reader = File.open config[:source], "r"
  reader.each_line { |line|

    break if config[:maxlines] > 0 && reader.lineno == config[:maxlines]

    if row_count == 0
      out = File.new(target_name(file_count), "w+")
      headers.each { |header| out.puts header }
    end

    if config[:header] > 0 && reader.lineno <= config[:header]
      headers.push line
    end

    out.puts line

    row_count += 1

    if config[:footer] > 0
      footers.unshift line
      footers.delete_at config[:footer] if footers.length == config[:footer]
    end

    if row_count == config[:lines]
      row_count = 0
      file_count += 1
      out.close
    end

  }
  reader.close

  if row_count <= footers.length
    File.delete target_name(file_count)
    file_count -= 1
    File.open(target_name(file_count), "a+") do |last_file|
      [row_count..footers.length].each do |i|
        last_file.puts footers[i]
      end
    end
  end

  if footers.length > 0
    (file_count-1).times do |file_no|
      out = File.open(target_name(file_no), "a+")
      footers.each { |footer| out.puts footer }
      out.close
    end
  end

end