Class: Bmg::Writer::Csv

Inherits:
Object
  • Object
show all
Includes:
Bmg::Writer
Defined in:
lib/bmg/writer/csv.rb

Constant Summary collapse

DEFAULT_OPTIONS =
{
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(csv_options, output_preferences = nil) ⇒ Csv

Returns a new instance of Csv.



9
10
11
12
# File 'lib/bmg/writer/csv.rb', line 9

def initialize(csv_options, output_preferences = nil)
  @csv_options = DEFAULT_OPTIONS.merge(csv_options)
  @output_preferences = OutputPreferences.dress(output_preferences)
end

Instance Attribute Details

#csv_optionsObject (readonly)

Returns the value of attribute csv_options.



13
14
15
# File 'lib/bmg/writer/csv.rb', line 13

def csv_options
  @csv_options
end

#output_preferencesObject (readonly)

Returns the value of attribute output_preferences.



13
14
15
# File 'lib/bmg/writer/csv.rb', line 13

def output_preferences
  @output_preferences
end

Instance Method Details

#call(relation, string_or_io = nil) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/bmg/writer/csv.rb', line 15

def call(relation, string_or_io = nil)
  require 'csv'
  string_or_io, to_s = string_or_io.nil? ? [StringIO.new, true] : [string_or_io, false]
  headers, csv = infer_headers(relation.type), nil
  previous = nil
  each_tuple(relation) do |tuple,i|
    if csv.nil?
      headers = infer_headers(tuple) if headers.nil?
      csv_opts = csv_options.merge(headers: headers)
      csv = CSV.new(string_or_io, **csv_opts)
    end
    previous, tuple = output_preferences.erase_redundance_in_group(previous, tuple)
    csv << headers.map{|h| tuple[h] }
  end
  to_s ? string_or_io.string : string_or_io
end