Class: SpreadsheetGoodies::Row

Inherits:
Array
  • Object
show all
Defined in:
lib/spreadsheet_goodies/row.rb

Overview

Override Array#[] and Array#[]= to allow indexing by the column title. E.g.: row[‘Employee name’]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(header_row, sheet_row_number, parent_worksheet, *args) ⇒ Row

Returns a new instance of Row.



8
9
10
11
12
13
# File 'lib/spreadsheet_goodies/row.rb', line 8

def initialize(header_row, sheet_row_number, parent_worksheet, *args)
  @header_row = header_row
  @row_number = sheet_row_number
  @parent_worksheet = parent_worksheet
  super(args)
end

Instance Attribute Details

#header_rowObject (readonly)

Returns the value of attribute header_row.



6
7
8
# File 'lib/spreadsheet_goodies/row.rb', line 6

def header_row
  @header_row
end

#parent_worksheetObject (readonly)

Returns the value of attribute parent_worksheet.



6
7
8
# File 'lib/spreadsheet_goodies/row.rb', line 6

def parent_worksheet
  @parent_worksheet
end

#row_numberObject (readonly)

Returns the value of attribute row_number.



6
7
8
# File 'lib/spreadsheet_goodies/row.rb', line 6

def row_number
  @row_number
end

Instance Method Details

#[](locator) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
# File 'lib/spreadsheet_goodies/row.rb', line 15

def [](locator)
  if locator.is_a?(String)
    if column_index = @header_row.find_index(locator)
      super(column_index) # queries local cache only
    else
      raise "Column with title '#{locator}' does not exist in header row"
    end
  else
    super(locator) # queries local cache only
  end
end

#[]=(locator, value) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/spreadsheet_goodies/row.rb', line 27

def []=(locator, value)
  if locator.is_a?(String)
    column_index = @header_row.find_index(locator)
    if column_index.nil?
      raise "Column with title '#{locator}' does not exist in header row"
    end
  else
    column_index = locator
  end

  # propagates change to real worksheet
  @parent_worksheet.write_to_cell(@row_number, column_index+1, value)

  # updates local cache
  super(column_index, value)
end