Class: CSVDoc
- Inherits:
-
Object
- Object
- CSVDoc
- Defined in:
- lib/csvgen.rb
Overview
CSV document class. Extend this class to add custom behavior, such as special quoting rules.
Instance Attribute Summary collapse
-
#newline ⇒ Object
Returns the value of attribute newline.
-
#quote ⇒ Object
Returns the value of attribute quote.
-
#sep ⇒ Object
Returns the value of attribute sep.
Instance Method Summary collapse
-
#enquote(val) ⇒ Object
Return quoted CSV value string for val.
-
#initialize ⇒ CSVDoc
constructor
A new instance of CSVDoc.
-
#needs_quote(val) ⇒ Object
Override this method if you need to implement special quoting rules.
-
#row(len_or_headers) {|r| ... } ⇒ Object
Append a row to the document, using the given fixed length, or array of headers.
- #to_s ⇒ Object
Constructor Details
#initialize ⇒ CSVDoc
Returns a new instance of CSVDoc.
17 18 19 20 21 22 |
# File 'lib/csvgen.rb', line 17 def initialize() @rows = [] self.newline = "\n" self.sep = "," self.quote = '"' end |
Instance Attribute Details
#newline ⇒ Object
Returns the value of attribute newline.
13 14 15 |
# File 'lib/csvgen.rb', line 13 def newline @newline end |
#quote ⇒ Object
Returns the value of attribute quote.
15 16 17 |
# File 'lib/csvgen.rb', line 15 def quote @quote end |
#sep ⇒ Object
Returns the value of attribute sep.
14 15 16 |
# File 'lib/csvgen.rb', line 14 def sep @sep end |
Instance Method Details
#enquote(val) ⇒ Object
Return quoted CSV value string for val.
46 47 48 49 50 51 52 53 |
# File 'lib/csvgen.rb', line 46 def enquote(val) val_s = val.to_s if needs_quote(val_s) then quote + val_s.gsub(quote, quote * 2) + quote else val_s end end |
#needs_quote(val) ⇒ Object
Override this method if you need to implement special quoting rules. By default it only quotes data which contains the quote character itself.
41 42 43 |
# File 'lib/csvgen.rb', line 41 def needs_quote(val) val.include?(quote) || val.include?(sep) end |
#row(len_or_headers) {|r| ... } ⇒ Object
Append a row to the document, using the given fixed length, or array of headers. Expects a block, which will be passed the new (empty) row object.
27 28 29 30 31 32 |
# File 'lib/csvgen.rb', line 27 def row(len_or_headers) r = CSVRow.new(self, len_or_headers) yield(r) @rows.push(r) self end |
#to_s ⇒ Object
34 35 36 |
# File 'lib/csvgen.rb', line 34 def to_s @rows.collect { |r| r.to_s }.join(@newline) end |