lib/csv_rails/array.rb in csv_rails-0.4.1 vs lib/csv_rails/array.rb in csv_rails-0.5.0

- old
+ new

@@ -5,23 +5,27 @@ base.send(:remove_method, :to_csv) base.send(:include, CsvRails::Array::InstanceMethods) end module InstanceMethods + # ==== Options + # * <tt>:fields</tt> - target field names + # * <tt>:header</tt> - header + # * <tt>:without_header</tt> - total_count + # * <tt>:encoding</tt> - encoding def to_csv(opts={}) - return "" if length < 1 - first = self.first - fields = opts.delete(:fields) || first.class.attribute_names + fields = opts[:fields] + header = if opts[:header] + opts.delete(:header) + elsif (klass = first.class).respond_to?(:csv_header) + klass.csv_header(fields) + else + fields + end csv = CSV.generate do |_csv| - unless opts[:without_header] - _csv << if first.class.respond_to?(:human_attribute_name) - fields.map{|f| first.class.human_attribute_name(f) } - else - fields - end - end + _csv << header unless opts[:without_header] each do |element| - _csv << element.to_csv_ary(fields, opts) + _csv << element.to_csv_ary(fields, opts) end end opts[:encoding] ? csv.encode(opts[:encoding]) : csv end end