Module: DataShift::ColumnPacker

Extended by:
Delimiters
Includes:
Delimiters
Included in:
CSV, CsvExporter, ExcelExporter
Defined in:
lib/datashift/column_packer.rb

Instance Attribute Summary

Attributes included from Delimiters

#attribute_list_end, #attribute_list_start, #csv_delimiter, #key_value_sep, #text_delim

Instance Method Summary collapse

Methods included from Delimiters

column_delim, column_delim=, eol, multi_assoc_delim, multi_assoc_delim=, multi_facet_delim, multi_value_delim, multi_value_delim=, name_value_delim, name_value_delim=, setmulti_facet_delim

Instance Method Details

#escape_for_csv(value) ⇒ Object

Ensure a value is written to CSV correctly TODO: - better ways ?? - see transcoding and String#encode



27
28
29
30
31
32
33
# File 'lib/datashift/column_packer.rb', line 27

def escape_for_csv(value)
  return nil if value.blank?
  text = value.to_s.gsub(text_delim, escape_text_delim).gsub("\n", '\\n')

  text = "#{text_delim}#{text}#{text_delim}" if(text.include?(csv_delimiter) && text.present?)
  text
end

#escape_text_delimObject

Return opposite of text delim - “hello, ‘barry’” => ‘“hello, ”barry“”’



19
20
21
22
# File 'lib/datashift/column_packer.rb', line 19

def escape_text_delim
  return '"' if text_delim == "\'"
  "\'"
end

#record_to_column(record, json = false) ⇒ Object

Convert an AR instance to a single column

e.g User  :  ":name = > 'tom', :role => 'developer'"

OPTIONS

json:         Export association data in single column in JSON format


42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/datashift/column_packer.rb', line 42

def record_to_column(record, json = false)

  return '' if record.nil? || (record.respond_to?(:each) && record.empty?)

  return record.to_json if json # packs associations into single column

  data = []

  if record.respond_to?(:each)
    return '' if record.empty?

    record.each { |r| data << record_to_column(r, json) }

    data.join(multi_assoc_delim).to_s
  else
    record.serializable_hash.each do |name, value|
      text = value.to_s.gsub(text_delim, escape_text_delim)
      data << "#{name}:#{key_value_sep}#{text}"
    end

    "#{attribute_list_start}#{data.join(multi_value_delim)}#{attribute_list_end}"
  end

end

#record_to_csv(record, options = {}) ⇒ Object

Convert an AR instance to a set of CSV columns



68
69
70
71
72
73
74
# File 'lib/datashift/column_packer.rb', line 68

def record_to_csv(record, options = {})
  csv_data = record.serializable_hash.values.collect { |value| escape_for_csv(value) }

  [*options[:methods]].each { |x| csv_data << escape_for_csv(record.send(x)) if record.respond_to?(x) } if options[:methods]

  csv_data.join( csv_delimiter )
end