Class: VFCSV::Generator

Inherits:
Object
  • Object
show all
Defined in:
lib/vfcsv.rb

Overview

Generator for building CSV strings

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(str, options) ⇒ Generator

Returns a new instance of Generator.



442
443
444
445
446
447
448
449
# File 'lib/vfcsv.rb', line 442

def initialize(str, options)
  @output = str.dup
  @col_sep = options[:col_sep] || ","
  @quote_char = options[:quote_char] || '"'
  @row_sep = options[:row_sep] == :auto ? "\n" : (options[:row_sep] || "\n")
  @force_quotes = options[:force_quotes] || false
  @quote_empty = options.fetch(:quote_empty, true)
end

Class Method Details

.generate_line(row, **options) ⇒ Object



468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
# File 'lib/vfcsv.rb', line 468

def self.generate_line(row, **options)
  col_sep = options[:col_sep] || ","
  quote_char = options[:quote_char] || '"'
  row_sep = options[:row_sep]
  row_sep = "\n" if row_sep.nil? || row_sep == :auto
  force_quotes = options[:force_quotes] || false
  quote_empty = options.fetch(:quote_empty, true)

  fields = row.map do |field|
    field_str = field.to_s
    if force_quotes || needs_quoting?(field_str, col_sep, quote_char) || (quote_empty && field_str.empty?)
      quote_field(field_str, quote_char)
    else
      field_str
    end
  end

  fields.join(col_sep) + row_sep
end

.needs_quoting?(str, col_sep, quote_char) ⇒ Boolean

Returns:

  • (Boolean)


488
489
490
# File 'lib/vfcsv.rb', line 488

def self.needs_quoting?(str, col_sep, quote_char)
  str.include?(col_sep) || str.include?(quote_char) || str.include?("\n") || str.include?("\r")
end

.quote_field(str, quote_char) ⇒ Object



492
493
494
495
# File 'lib/vfcsv.rb', line 492

def self.quote_field(str, quote_char)
  escaped = str.gsub(quote_char, quote_char + quote_char)
  "#{quote_char}#{escaped}#{quote_char}"
end

Instance Method Details

#<<(row) ⇒ Object Also known as: add_row, puts



451
452
453
454
455
456
457
458
459
460
# File 'lib/vfcsv.rb', line 451

def <<(row)
  @output << self.class.generate_line(row,
    col_sep: @col_sep,
    quote_char: @quote_char,
    row_sep: @row_sep,
    force_quotes: @force_quotes,
    quote_empty: @quote_empty
  )
  self
end

#to_sObject



464
465
466
# File 'lib/vfcsv.rb', line 464

def to_s
  @output
end