Class: Headache::Document

Inherits:
Fixy::Document
  • Object
show all
Defined in:
lib/headache/document.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(header = nil, control = nil, batches = []) ⇒ Document

Returns a new instance of Document.



7
8
9
10
11
12
# File 'lib/headache/document.rb', line 7

def initialize(header = nil, control = nil, batches = [])
  @header  = header
  @control = control
  @batches = batches
  [@header, @control].each { |r| r.try :document=, self }
end

Instance Attribute Details

#batchesObject (readonly)

Returns the value of attribute batches.



3
4
5
# File 'lib/headache/document.rb', line 3

def batches
  @batches
end

Instance Method Details

#<<(batch) ⇒ Object



29
30
31
32
# File 'lib/headache/document.rb', line 29

def <<(batch)
  add_batch batch
  self
end

#add_batch(batch) ⇒ Object



24
25
26
27
# File 'lib/headache/document.rb', line 24

def add_batch(batch)
  batch.document = self
  @batches << batch
end

#batchObject



19
20
21
22
# File 'lib/headache/document.rb', line 19

def batch
  fail Headache::AmbiguousBatch, 'multiple batches detected, be more explicit or use first_batch' if @batches.count > 1
  first_batch
end

#buildObject



66
67
68
69
70
71
72
73
74
75
# File 'lib/headache/document.rb', line 66

def build
  append_record header
  @batches.each do |batch|
    append_record batch.header
    batch.entries.each { |entry| append_record entry }
    append_record batch.control
  end
  append_record control
  overflow_lines_needed.times { append_record Record::Overflow.new }
end

#controlObject



42
43
44
# File 'lib/headache/document.rb', line 42

def control
  @control ||= Record::FileControl.new self
end

#entriesObject



34
35
36
# File 'lib/headache/document.rb', line 34

def entries
  @batches.map(&:entries).flatten
end

#first_batchObject



14
15
16
17
# File 'lib/headache/document.rb', line 14

def first_batch
  add_batch Batch.new(self) if @batches.empty?
  @batches.first
end

#headerObject



38
39
40
# File 'lib/headache/document.rb', line 38

def header
  @header ||= Record::FileHeader.new self
end

#linesObject



52
53
54
# File 'lib/headache/document.rb', line 52

def lines
  @content.split("\n").count
end

#overflow_lines_neededObject



56
57
58
# File 'lib/headache/document.rb', line 56

def overflow_lines_needed
  10 - lines % 10
end

#recordsObject



46
47
48
49
50
# File 'lib/headache/document.rb', line 46

def records
  ([header] << batches.map do |batch|
    [batch.header, batch.entries, batch.control]
  end << control).flatten
end

#to_hObject



60
61
62
63
64
# File 'lib/headache/document.rb', line 60

def to_h
  { file_header: @header.to_h,
    batches: @batches.map(&:to_h),
    file_control: @control.to_h }
end