Class: VFCSV::Generator
- Inherits:
-
Object
- Object
- VFCSV::Generator
- Defined in:
- lib/vfcsv.rb
Overview
Generator for building CSV strings
Class Method Summary collapse
- .generate_line(row, **options) ⇒ Object
- .needs_quoting?(str, col_sep, quote_char) ⇒ Boolean
- .quote_field(str, quote_char) ⇒ Object
Instance Method Summary collapse
- #<<(row) ⇒ Object (also: #add_row, #puts)
-
#initialize(str, options) ⇒ Generator
constructor
A new instance of Generator.
- #to_s ⇒ Object
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, ) @output = str.dup @col_sep = [:col_sep] || "," @quote_char = [:quote_char] || '"' @row_sep = [:row_sep] == :auto ? "\n" : ([:row_sep] || "\n") @force_quotes = [:force_quotes] || false @quote_empty = .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, **) col_sep = [:col_sep] || "," quote_char = [:quote_char] || '"' row_sep = [:row_sep] row_sep = "\n" if row_sep.nil? || row_sep == :auto force_quotes = [:force_quotes] || false quote_empty = .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
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_s ⇒ Object
464 465 466 |
# File 'lib/vfcsv.rb', line 464 def to_s @output end |