Class: RailsImporter::Base

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(filepath, options = {}) ⇒ Base

Returns a new instance of Base.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/rails_importer/base.rb', line 7

def initialize filepath, options={}
  if File.exists?(filepath)
    @filepath = filepath
  end

  @spreadsheet = nil

  @messages = []

  @rows = 0

  begin
    open_spreadsheet

    @rows = @spreadsheet.last_row
  rescue => e
    add_error message: e.message, backtrace: e.backtrace, row_index: nil, data: {}
  end

  # Custom behavior
end

Instance Attribute Details

#messagesObject (readonly)

Returns the value of attribute messages.



5
6
7
# File 'lib/rails_importer/base.rb', line 5

def messages
  @messages
end

Class Method Details

.keyObject

A unique key identifier for importer



30
31
32
# File 'lib/rails_importer/base.rb', line 30

def self.key
  self.to_s.gsub('Importer', '').demodulize.underscore
end

.sample_fileObject

The importer sample file



60
61
62
# File 'lib/rails_importer/base.rb', line 60

def self.sample_file
  Rails.root.join("lib/rails_importer/templates/#{key}.xlsx")
end

Instance Method Details

#load_data(row:) ⇒ Object

Load a file and the get data from each file row



55
56
57
# File 'lib/rails_importer/base.rb', line 55

def load_data(row:)
  raise "#{__FILE__}:#{__LINE__} You must define it"
end

#processObject

Load a file and the get data from each file row



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/rails_importer/base.rb', line 35

def process
  # Load each row element
  2.upto(@rows).each do |row_index|
    ActiveRecord::Base.transaction do
      begin
        load_data row: @spreadsheet.row(row_index)

      rescue => e
        add_error message: e.message, backtrace: e.backtrace, row_index: row_index, data: @spreadsheet.row(row_index)

        raise ActiveRecord::Rollback
      end
    end
  end
end