module EnumCSV

EnumCSV exposes a single method, csv, for easily creating CSV output/files from enumerable objects.

Public Class Methods

csv(enum, opts={}) { |line| ... } click to toggle source

Create CSV from the given Enumerable object. If a block is given, each item in the enumerable is yielded to the block, and the block should return an array of of items to use for the CSV line.

Options:

:headers

Should be an array of headers to use as the first line of the CSV output, or a comma-delimited string of headers.

:file

Output to the given file and return nil instead of returning a string with the CSV output.

all other options

Passed to CSV.open or CSV.generate

   # File lib/enum_csv.rb
19 def csv(enum, opts={})
20   headers = opts[:headers]
21   headers = headers.split(',') if headers.is_a?(String)
22   has_headers = headers.is_a?(Array) && !opts.has_key?(:write_headers)
23   has_file = opts[:file]
24 
25   if has_headers || has_file
26     opts = opts.dup
27     file = opts.delete(:file)
28 
29     if has_headers
30       opts[:write_headers] = true
31       opts[:headers] = headers
32     end
33   end
34 
35   csv_proc = proc do |csv|
36     enum.each do |line|
37       line = yield(line) if block_given?
38       csv << line
39     end
40   end
41 
42   if file
43     CSV.open(file, 'wb', **opts, &csv_proc)
44     nil
45   else
46     CSV.generate(**opts, &csv_proc)
47   end
48 end

Private Instance Methods

csv(enum, opts={}) { |line| ... } click to toggle source

Create CSV from the given Enumerable object. If a block is given, each item in the enumerable is yielded to the block, and the block should return an array of of items to use for the CSV line.

Options:

:headers

Should be an array of headers to use as the first line of the CSV output, or a comma-delimited string of headers.

:file

Output to the given file and return nil instead of returning a string with the CSV output.

all other options

Passed to CSV.open or CSV.generate

   # File lib/enum_csv.rb
19 def csv(enum, opts={})
20   headers = opts[:headers]
21   headers = headers.split(',') if headers.is_a?(String)
22   has_headers = headers.is_a?(Array) && !opts.has_key?(:write_headers)
23   has_file = opts[:file]
24 
25   if has_headers || has_file
26     opts = opts.dup
27     file = opts.delete(:file)
28 
29     if has_headers
30       opts[:write_headers] = true
31       opts[:headers] = headers
32     end
33   end
34 
35   csv_proc = proc do |csv|
36     enum.each do |line|
37       line = yield(line) if block_given?
38       csv << line
39     end
40   end
41 
42   if file
43     CSV.open(file, 'wb', **opts, &csv_proc)
44     nil
45   else
46     CSV.generate(**opts, &csv_proc)
47   end
48 end