Module: Csv2Psql::Convert
- Defined in:
- lib/csv2psql/convert/convert.rb
Overview
Csv2Psql convert module
Constant Summary collapse
- DEFAULT_OPTIONS =
{ delimiter: ',', header: true }
Class Method Summary collapse
Class Method Details
.convert(paths, opts = {}) ⇒ Object
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/csv2psql/convert/convert.rb', line 31 def convert(paths, opts = {}) paths = [paths] unless paths.is_a?(Array) paths.each do |path| puts "Converting #{path}" header = !opts[:header].nil? ? opts[:header] : DEFAULT_OPTIONS[:header] csv_opts = { col_sep: opts[:delimiter] || DEFAULT_OPTIONS[:delimiter], :headers => header } CSV.open(path, 'rt', csv_opts) do |csv| csv.each do |row| puts format_row(row) end end end end |
.format_row(row) ⇒ Object
19 20 21 22 23 24 25 26 27 28 29 |
# File 'lib/csv2psql/convert/convert.rb', line 19 def format_row(row) headers = row.headers.map do |h| h.downcase.gsub(/\./, '_') end values = row.headers.map do |h| "'#{row[h]}'" end "INSERT INTO aaa(#{headers.join(', ')}) VALUES(#{values.join(', ')});" end |
.sanitize_header(header) ⇒ Object
50 51 52 53 54 |
# File 'lib/csv2psql/convert/convert.rb', line 50 def sanitize_header(header) header.map do |h| h.downcase end end |