class Stockboy::Readers::Spreadsheet
Parse an Excel spreadsheet
Backed by Roo gem. See roo for other configuration options.
Public Class Methods
new(opts={}, &block)
click to toggle source
Initialize a new Spreadsheet
reader
@param [Hash] opts
Calls superclass method
Stockboy::Reader::new
# File lib/stockboy/readers/spreadsheet.rb, line 75 def initialize(opts={}, &block) super @format = opts[:format] || :xls @sheet = opts[:sheet] || :first @first_row = opts[:first_row] @last_row = opts[:last_row] @header_row = opts[:header_row] @headers = opts[:headers] @options = opts[:options] || {} DSL.new(self).instance_eval(&block) if block_given? end
Public Instance Methods
parse(content)
click to toggle source
# File lib/stockboy/readers/spreadsheet.rb, line 87 def parse(content) with_spreadsheet_tempfile(content) do |table| headers = table_headers(table) enum_data_rows(table).inject([]) do |rows, i| rows << Hash[headers.zip(table.row(i))] end end end
Private Instance Methods
enum_data_rows(table)
click to toggle source
# File lib/stockboy/readers/spreadsheet.rb, line 99 def enum_data_rows(table) first_table_row(table).upto last_table_row(table) end
first_table_row(table)
click to toggle source
# File lib/stockboy/readers/spreadsheet.rb, line 123 def first_table_row(table) return @first_row if @first_row if @headers table.first_row elsif @header_row @header_row + 1 else table.first_row + 1 end end
last_table_row(table)
click to toggle source
# File lib/stockboy/readers/spreadsheet.rb, line 135 def last_table_row(table) if @last_row.to_i < 0 table.last_row + @last_row + 1 elsif @last_row.to_i > 0 @last_row else table.last_row end end
sheet_number(table, id)
click to toggle source
# File lib/stockboy/readers/spreadsheet.rb, line 115 def sheet_number(table, id) case id when Symbol then table.sheets.public_send id when Integer then table.sheets[id-1] when String then id end end
table_header_row(table)
click to toggle source
# File lib/stockboy/readers/spreadsheet.rb, line 150 def table_header_row(table) [table.header_line, table.first_row].max end
table_headers(table)
click to toggle source
# File lib/stockboy/readers/spreadsheet.rb, line 145 def table_headers(table) return @headers if @headers table.row(table_header_row(table)).map { |h| h.to_s unless h.nil? } end
tmp_name()
click to toggle source
# File lib/stockboy/readers/spreadsheet.rb, line 154 def tmp_name ['stockboy', ".#{@format}"] end
with_spreadsheet_tempfile(content) { |table| ... }
click to toggle source
# File lib/stockboy/readers/spreadsheet.rb, line 103 def with_spreadsheet_tempfile(content) Tempfile.open(tmp_name, Stockboy.configuration.tmp_dir) do |file| file.binmode file.write content file.fsync table = Roo::Spreadsheet.open(file.path, @options) table.default_sheet = sheet_number(table, @sheet) table.header_line = @header_row if @header_row yield table end end