Module: DbAgile::IO::CSV
- Extended by:
- TypeSafe
- Defined in:
- lib/dbagile/io/csv.rb
Class Method Summary collapse
-
.build_csv_instance(io, options) ⇒ Object
Makes the CSV require, depending on Ruby version.
-
.from_csv(input, options = {}) ⇒ Object
If a block is given yields it with each tuple that can be loaded from the CSV input and returns nil.
-
.normalize_options(options) ⇒ Object
Normalizes CSV options from DBAgile options.
-
.to_csv(data, columns, buffer = "", options = {}) ⇒ ...
Outputs some data as a CSV string.
Methods included from TypeSafe
from_typesafe_relation, from_typesafe_tuple, from_typesafe_xxx, to_typesafe_relation, to_typesafe_tuple, with_type_safe_relation
Class Method Details
.build_csv_instance(io, options) ⇒ Object
Makes the CSV require, depending on Ruby version
22 23 24 25 26 27 28 29 30 31 32 33 34 |
# File 'lib/dbagile/io/csv.rb', line 22 def build_csv_instance(io, ) if RUBY_VERSION >= "1.9.0" require 'csv' = () = .dup.delete_if{|key,value| !::CSV::DEFAULT_OPTIONS.key?(key)} [::CSV.new(io, ), ] else require 'faster_csv' = () = .dup.delete_if{|key,value| !FasterCSV::DEFAULT_OPTIONS.key?(key)} [FasterCSV.new(io, ), ] end end |
.from_csv(input, options = {}) ⇒ Object
If a block is given yields it with each tuple that can be loaded from the CSV input and returns nil. Otherwise, reads the CSV input and returns an array of tuples.
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
# File 'lib/dbagile/io/csv.rb', line 70 def from_csv(input, = {}) # Creates a CSV inputer with options csv, = build_csv_instance(input, ) if ts = [:type_system] converter = lambda{|field| ts.parse_literal(field)} csv.header_convert(&converter) csv.convert(&converter) end # Load data now ts = [:type_system] if block_given? csv.each do |row| next if row.header_row? yield(row.to_hash) end else tuples = [] csv.each do |row| next if row.header_row? tuples << row.to_hash end tuples end end |
.normalize_options(options) ⇒ Object
Normalizes CSV options from DBAgile options
7 8 9 10 11 12 13 14 15 16 17 18 |
# File 'lib/dbagile/io/csv.rb', line 7 def () if [:type_system] [:headers] = true unless .key?(:headers) [:quote_char] = "'" unless .key?(:quote_char) [:force_quotes] = true unless .key?(:force_quotes) end if [:headers] [:write_headers] = true [:return_headers] = true end end |
.to_csv(data, columns, buffer = "", options = {}) ⇒ ...
Outputs some data as a CSV string.
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/dbagile/io/csv.rb', line 42 def to_csv(data, columns, buffer = "", = {}) # Creates a CSV outputter with options csv, = build_csv_instance(buffer, ) # Write header if required if [:headers] if ts = [:type_system] csv << columns.collect{|c| ts.to_literal(c)} else csv << columns end end # Write tuples now with_type_safe_relation(data, ) do |tuple| csv << columns.collect{|c| tuple[c]} end # Return buffer buffer end |