Module: UsefulRenderers::CsvRenderable
- Defined in:
- lib/useful_renderers/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
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/useful_renderers/csv_renderable.rb', line 12 def to_csv( = {}) klass = first.class return '' if empty? return join(',') unless klass.respond_to? :column_names columns = klass.column_names if [:only] columns = [] [:only].each do |method| columns << method.to_s if first.respond_to?(method) end end columns -= [:except].map(&:to_s) if [:except] columns += [:add_methods].map(&:to_s) if [:add_methods] headers = columns.dup headers.map!{|col| klass.human_attribute_name col } if [:translate] = { encoding: 'utf-8', headers: headers, write_headers: true } CSV.generate() do |row| self.each do |obj| row << columns.map { |c| obj.send(c) } end end end |