Class: SimpleReport::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/simple_report/base.rb

Instance Method Summary collapse

Constructor Details

#initializeBase

Returns a new instance of Base.



3
4
5
# File 'lib/simple_report/base.rb', line 3

def initialize
  @sheets = []
end

Instance Method Details

#add_format(name, format) ⇒ Object



7
8
9
10
# File 'lib/simple_report/base.rb', line 7

def add_format(name, format)
  @formats ||= {}
  @formats[name] = format
end

#add_formatsObject



55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/simple_report/base.rb', line 55

def add_formats
  money = @workbook.add_format
  money.set_num_format('$0.00')
  add_format :money, money

  heading = @workbook.add_format
  heading.set_bold
  add_format :heading, heading

  percent = @workbook.add_format
  percent.set_num_format('0.0%')
  add_format :percent, percent
end

#add_sheet(name, data) {|sheet| ... } ⇒ Object

Yields:

  • (sheet)


19
20
21
22
23
24
# File 'lib/simple_report/base.rb', line 19

def add_sheet(name, data)
  sheet = Sheet.new(name, data)
  yield sheet
  @sheets ||= []
  @sheets << sheet
end

#build_reportObject

Raises:

  • (NotImplementedError)


69
70
71
# File 'lib/simple_report/base.rb', line 69

def build_report
  raise NotImplementedError.new('<report>#build_report not implemented')
end

#find_format(format) ⇒ Object



51
52
53
# File 'lib/simple_report/base.rb', line 51

def find_format(format)
  @formats[format]
end

#generate_reportObject



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/simple_report/base.rb', line 26

def generate_report
  @file = Tempfile.new('simple_report')
  @workbook = WriteXLSX.new(@file.path)
  add_formats
  @sheets.each do |sheet|
    output_sheet = @workbook.add_worksheet(sheet.name)
    sheet.fields.each_with_index do |f, index|
      output_sheet.set_column(index, index, f.width)
      output_sheet.write(0, index, f.name, @formats[:heading])
    end
    sheet.collection.each_with_index do |ic, record_num|
      sheet.fields.each_with_index do |field, column|
        if field.field
          value = ic.send(field.field)
        elsif field.value
          value = field.value
        elsif field.block
          value = field.block.call(ic, record_num + 2)
        end
        output_sheet.write(record_num + 1, column, value, find_format(field.format))
      end
    end
  end
end

#to_xlsx(*params) ⇒ Object



12
13
14
15
16
17
# File 'lib/simple_report/base.rb', line 12

def to_xlsx(*params)
  build_report(*params)
  generate_report
  @workbook.close
  File.read @file.path
end