Class: SunatBooks::Csv::Base

Inherits:
Object
  • Object
show all
Includes:
SunatBooks::CommonUtils
Defined in:
lib/sunat_books/csv/base.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from SunatBooks::CommonUtils

#available_value?

Constructor Details

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

Returns a new instance of Base.



14
15
16
17
18
19
20
21
22
23
# File 'lib/sunat_books/csv/base.rb', line 14

def initialize(tickets, options = {})
  # options
  # - layout => Array of strings used to get data for csv
  # - filename
  raise SunatBooks::Csv::OptionError, "Layout option is required" if options[:layout].nil?

  filename = options[:filename] || "#{tmp_path}book.csv"
  fields = options[:layout]
  get_file(filename, fields, tickets)
end

Instance Attribute Details

#fileObject

Returns the value of attribute file.



12
13
14
# File 'lib/sunat_books/csv/base.rb', line 12

def file
  @file
end

Instance Method Details

#append_data(tickets, filename, fields) ⇒ Object



44
45
46
47
48
49
50
51
52
# File 'lib/sunat_books/csv/base.rb', line 44

def append_data(tickets, filename, fields)
  tickets&.each do |ticket|
    data = []
    fields&.each do |field|
      data << available_value?(ticket, field)
    end
    append_to_csv(filename, data, "a+")
  end
end

#append_headers(filename, fields) ⇒ Object



40
41
42
# File 'lib/sunat_books/csv/base.rb', line 40

def append_headers(filename, fields)
  append_to_csv(filename, fields, "w+")
end

#append_to_csv(filename, data, mode) ⇒ Object



54
55
56
57
58
59
60
# File 'lib/sunat_books/csv/base.rb', line 54

def append_to_csv(filename, data, mode)
  return if data.nil?

  CSV.open(filename, mode) do |csv|
    csv << data
  end
end

#get_file(filename, fields, tickets) ⇒ Object



25
26
27
28
29
30
31
# File 'lib/sunat_books/csv/base.rb', line 25

def get_file(filename, fields, tickets)
  send("file=", filename)
  File.exist?(filename) ? File.delete(filename) : nil
  FileUtils.touch(filename)
  append_headers(filename, fields)
  append_data(tickets, filename, fields)
end

#tmp_pathObject



33
34
35
36
37
38
# File 'lib/sunat_books/csv/base.rb', line 33

def tmp_path
  dir = File.dirname(__FILE__)
  tmp_path = "#{dir}/tmp/"
  Dir.mkdir(tmp_path) unless Dir.exist?(tmp_path)
  tmp_path
end