Module: RenderCsv::CsvRenderable
- Defined in:
- lib/render_csv/csv_renderable.rb
Instance Method Summary collapse
-
#to_csv(options = {}) ⇒ Object
Converts an array to CSV formatted string Options include: :only => [:col1, :col2] # Specify which columns to include :except => [:col1, :col2] # Specify which columns to exclude :add_methods => [:method1, :method2] # Include addtional methods that aren’t columns.
Instance Method Details
#to_csv(options = {}) ⇒ Object
Converts an array to CSV formatted string Options include: :only => [:col1, :col2] # Specify which columns to include :except => [:col1, :col2] # Specify which columns to exclude :add_methods => [:method1, :method2] # Include addtional methods that aren’t columns
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
# File 'lib/render_csv/csv_renderable.rb', line 10 def to_csv( = {}) return '' if empty? return join(',') unless first.class.respond_to? :column_names columns = first.class.column_names columns &= [:only].map(&:to_s) if [:only] columns -= [:except].map(&:to_s) if [:except] columns += [:add_methods].map(&:to_s) if [:add_methods] CSV.generate(encoding: 'utf-8') do |row| row << columns self.each do |obj| row << columns.map { |c| obj.send(c) } end end end |