Class: ToXls::Writer

Inherits:
Object
  • Object
show all
Defined in:
lib/to_xls/writer.rb

Instance Method Summary collapse

Constructor Details

#initialize(array, options = {}) ⇒ Writer

Returns a new instance of Writer.



8
9
10
11
12
13
# File 'lib/to_xls/writer.rb', line 8

def initialize(array, options = {})
  @array = array
  @options = options
  @cell_format = create_format :cell_format
  @header_format = create_format :header_format
end

Instance Method Details

#can_get_columns_from_first_element?Boolean

Returns:

  • (Boolean)


60
61
62
63
64
65
# File 'lib/to_xls/writer.rb', line 60

def can_get_columns_from_first_element?
  @array.first &&
  @array.first.respond_to?(:attributes) &&
  @array.first.attributes.respond_to?(:keys) &&
  @array.first.attributes.keys.is_a?(Array)
end

#columnsObject

Raises:

  • (ArgumentError)


53
54
55
56
57
58
# File 'lib/to_xls/writer.rb', line 53

def columns
  return  @columns if @columns
  @columns = @options[:columns]
  raise ArgumentError.new(":columns (#{columns}) must be an array or nil") unless (@columns.nil? || @columns.is_a?(Array))
  @columns ||=  can_get_columns_from_first_element? ? get_columns_from_first_element : []
end

#get_columns_from_first_elementObject



67
68
69
# File 'lib/to_xls/writer.rb', line 67

def get_columns_from_first_element
  @array.first.attributes.keys.sort_by {|sym| sym.to_s}.collect.to_a
end

#headersObject

Raises:

  • (ArgumentError)


71
72
73
74
75
76
# File 'lib/to_xls/writer.rb', line 71

def headers
  return  @headers if @headers
  @headers = @options[:headers] || columns
  raise ArgumentError, ":headers (#{@headers.inspect}) must be an array" unless @headers.is_a? Array
  @headers
end

#headers_should_be_included?Boolean

Returns:

  • (Boolean)


78
79
80
# File 'lib/to_xls/writer.rb', line 78

def headers_should_be_included?
  @options[:headers] != false
end

#write_book(book) ⇒ Object



27
28
29
30
31
32
# File 'lib/to_xls/writer.rb', line 27

def write_book(book)
  sheet = book.create_worksheet
  sheet.name = @options[:name] || 'Sheet 1'
  write_sheet(sheet)
  return book
end

#write_io(io) ⇒ Object



21
22
23
24
25
# File 'lib/to_xls/writer.rb', line 21

def write_io(io)
  book = Spreadsheet::Workbook.new
  write_book(book)
  book.write(io)
end

#write_sheet(sheet) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/to_xls/writer.rb', line 34

def write_sheet(sheet)
  if columns.any?
    row_index = 0

    if headers_should_be_included?
      apply_format_to_row(sheet.row(0), @header_format)
      fill_row(sheet.row(0), headers)
      row_index = 1
    end

    @array.each do |model|
      row = sheet.row(row_index)
      apply_format_to_row(row, @cell_format)
      fill_row(row, columns, model)
      row_index += 1
    end
  end
end

#write_string(string = '') ⇒ Object



15
16
17
18
19
# File 'lib/to_xls/writer.rb', line 15

def write_string(string = '')
  io = StringIO.new(string)
  write_io(io)
  io.string
end