Class: CsvRowModel::Export::File

Inherits:
Object
  • Object
show all
Defined in:
lib/csv_row_model/public/export/file.rb

Defined Under Namespace

Classes: Proxy

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(row_model_class, context = {}) ⇒ File


7
8
9
10
# File 'lib/csv_row_model/public/export/file.rb', line 7

def initialize(row_model_class, context={})
  @row_model_class = row_model_class
  @context = context.to_h.symbolize_keys
end

Instance Attribute Details

#contextObject (readonly)

Returns the value of attribute context


4
5
6
# File 'lib/csv_row_model/public/export/file.rb', line 4

def context
  @context
end

#csvObject (readonly)

Returns the value of attribute csv


4
5
6
# File 'lib/csv_row_model/public/export/file.rb', line 4

def csv
  @csv
end

#fileObject (readonly)

Returns the value of attribute file


4
5
6
# File 'lib/csv_row_model/public/export/file.rb', line 4

def file
  @file
end

#row_model_classObject (readonly)

Returns the value of attribute row_model_class


4
5
6
# File 'lib/csv_row_model/public/export/file.rb', line 4

def row_model_class
  @row_model_class
end

Instance Method Details

#append_model(source_model, context = {}) ⇒ CsvRowModel::Export Also known as: <<

Add a row_model to the


20
21
22
23
24
25
26
# File 'lib/csv_row_model/public/export/file.rb', line 20

def append_model(source_model, context={})
  row_model = row_model_class.new(source_model, context.reverse_merge(self.context))
  row_model.to_rows.each do |row|
    csv << row
  end
  row_model
end

#generate(with_headers: true) ⇒ Object

Open a block to generate a file


36
37
38
39
40
41
42
43
44
45
# File 'lib/csv_row_model/public/export/file.rb', line 36

def generate(with_headers: true)
  @file = Tempfile.new([row_model_class.name, ".csv"])
  CSV.open(file.path, "wb") do |csv|
    @csv = csv
    row_model_class.setup(csv, context, with_headers: with_headers)
    yield Proxy.new(self)
  end
ensure
  @csv = nil
end

#generated?Boolean


30
31
32
# File 'lib/csv_row_model/public/export/file.rb', line 30

def generated?
  !!file
end

#headersObject


12
13
14
# File 'lib/csv_row_model/public/export/file.rb', line 12

def headers
  row_model_class.headers(self.context)
end

#to_sObject


47
48
49
# File 'lib/csv_row_model/public/export/file.rb', line 47

def to_s
  file.read
end