Class: SimpleCsv::Writer

Inherits:
Base
  • Object
show all
Defined in:
lib/simple_csv/writer.rb

Constant Summary

Constants inherited from Base

Base::COMMON_DELIMITERS

Instance Attribute Summary

Attributes inherited from Base

#index

Instance Method Summary collapse

Constructor Details

#initialize(path, **opts, &block) ⇒ Writer

Returns a new instance of Writer.



3
4
5
6
7
8
9
10
11
12
13
# File 'lib/simple_csv/writer.rb', line 3

def initialize(path, **opts, &block)
  @caller_self = eval 'self', block.binding

  settings.apply({force_row_completion: true}, opts)
  CSV.open(File.expand_path(path), 'w', settings.for_csv) do |csv|
    @csv = csv
    @last_row = {}
    @current_row = {}
    instance_exec(self, &block)
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(mtd, *args, &block) ⇒ Object (private)



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/simple_csv/writer.rb', line 23

def method_missing(mtd, *args, &block)
  SimpleCsv.csv_manually_set_headers! unless @headers_written

  current_val = @current_row[mtd] if @current_row.key?(mtd)
  current_val = @last_row[mtd] if @last_row.key?(mtd)

  return current_val if args.empty? && current_val

  unless headers.include?(mtd.to_s) || @col_map.key?(mtd.to_s)
    return @caller_self.send mtd, *args, &block
  end

  if settings.force_row_completion && @current_row.key?(mtd) && args.any?
    SimpleCsv.row_not_complete!(mtd, args.first)
  end

  current_val = @current_row[mtd] = args.first || current_val

  return current_val unless @current_row.size == headers.size

  @last_row = @current_row
  @csv << @current_row.values
  @current_row = {}
  current_val
end

Instance Method Details

#headers(*args) ⇒ Object



15
16
17
18
19
# File 'lib/simple_csv/writer.rb', line 15

def headers(*args)
  super
  (@csv << @headers) && @headers_written = true if !@headers_written && @csv
  @headers
end