Class: Csvbuilder::Export::File

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

Defined Under Namespace

Classes: FileProxy

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of File.

Parameters:

  • export_model (Export)

    export model class



9
10
11
12
# File 'lib/csvbuilder/exporter/public/export/file.rb', line 9

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.



6
7
8
# File 'lib/csvbuilder/exporter/public/export/file.rb', line 6

def context
  @context
end

#csvObject (readonly)

Returns the value of attribute csv.



6
7
8
# File 'lib/csvbuilder/exporter/public/export/file.rb', line 6

def csv
  @csv
end

#fileObject (readonly)

Returns the value of attribute file.



6
7
8
# File 'lib/csvbuilder/exporter/public/export/file.rb', line 6

def file
  @file
end

#row_model_classObject (readonly)

Returns the value of attribute row_model_class.



6
7
8
# File 'lib/csvbuilder/exporter/public/export/file.rb', line 6

def row_model_class
  @row_model_class
end

Instance Method Details

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

Add a row_model to the

Parameters:

  • []

    source_model the source model of the export row model

  • context (Hash) (defaults to: {})

    the extra context given to the instance of the row model

Returns:



22
23
24
25
26
27
28
# File 'lib/csvbuilder/exporter/public/export/file.rb', line 22

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

Parameters:

  • with_headers (Boolean) (defaults to: true)

    adds the header to the file if true



38
39
40
41
42
43
44
45
46
47
# File 'lib/csvbuilder/exporter/public/export/file.rb', line 38

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 FileProxy.new(self)
  end
ensure
  @csv = nil
end

#generated?Boolean

Returns true, if a csv file is generated.

Returns:

  • (Boolean)

    true, if a csv file is generated



32
33
34
# File 'lib/csvbuilder/exporter/public/export/file.rb', line 32

def generated?
  !!file
end

#headersObject



14
15
16
# File 'lib/csvbuilder/exporter/public/export/file.rb', line 14

def headers
  row_model_class.headers(context)
end

#to_sObject



49
50
51
# File 'lib/csvbuilder/exporter/public/export/file.rb', line 49

def to_s
  file.read
end