Class: TalltyImportExport::Excel

Inherits:
Object
  • Object
show all
Defined in:
lib/tallty_import_export/excel.rb

Defined Under Namespace

Classes: Pagination, Rows

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(uid = SecureRandom.hex(8)) ⇒ Excel

Returns a new instance of Excel.



8
9
10
11
# File 'lib/tallty_import_export/excel.rb', line 8

def initialize uid = SecureRandom.hex(8)
  @uid = uid
  @cache = ::Redis::HashKey.new(@uid, expiration: 60 * 60 * 1, marshal: true)
end

Instance Attribute Details

#cacheObject (readonly)

Returns the value of attribute cache.



6
7
8
# File 'lib/tallty_import_export/excel.rb', line 6

def cache
  @cache
end

#uidObject (readonly)

Returns the value of attribute uid.



6
7
8
# File 'lib/tallty_import_export/excel.rb', line 6

def uid
  @uid
end

Instance Method Details

#dataObject



45
46
47
# File 'lib/tallty_import_export/excel.rb', line 45

def data
  cache.all
end

#load(file, **opts) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/tallty_import_export/excel.rb', line 13

def load file, **opts
  opts = opts.with_indifferent_access

  file_path = file.is_a?(String) ? file : file.path
  book = ::Roo::Spreadsheet.open(file_path, extension: File.extname(file_path) == '.xls' ? :xls : :xlsx)

  read_title_from_row = opts[:read_title_from_row] || 1
  read_data_from_row = opts[:read_data_from_row] || 2
  titles = book.row(read_title_from_row)
  rows = []

  read_data_from_row.upto(book.last_row) do |i|
    row = book.row(i)[0 .. titles.count]
    out = {}
    titles.each_with_index do |title, index|
      out[title] = row[index]
    end
    rows << out
  end
  cache['uid'] = uid
  cache['rows'] = rows
  cache['titles'] = titles
end

#records_pagination(page: 1, per_page: 15) ⇒ Object



49
50
51
# File 'lib/tallty_import_export/excel.rb', line 49

def records_pagination page: 1, per_page: 15
  Pagination.new(rows, page: page, per_page: per_page)
end

#rowsObject



37
38
39
# File 'lib/tallty_import_export/excel.rb', line 37

def rows
  Rows.new(cache['rows'])
end

#titlesObject



41
42
43
# File 'lib/tallty_import_export/excel.rb', line 41

def titles
  cache['titles']
end