Sha256: 248b1f1b3cc18a29cd0dfa842b85c0b7595700b77aa4a2e4875bd0c3eb73e6c5

Contents?: true

Size: 1.26 KB

Versions: 1

Compression:

Stored size: 1.26 KB

Contents

require 'csv'
module CsvRails
  module ActiveRecord
    def self.included(base)
      base.extend ClassMethods
      ::ActiveRecord::Relation.send(:include, ClassMethods)
      base.send(:include, InstanceMethods)
    end

    module ClassMethods
      def to_csv(opts={})
        fields = if opts[:fields]
                   opts.delete(:fields)
                 elsif respond_to?(:attribute_names)
                   attribute_names
                 elsif self.is_a?(::ActiveRecord::Relation)
                   @klass.new.attribute_names
                 else
                   new.attribute_names
                 end
        header = fields.map{|f| human_attribute_name(f) }
        all.to_csv(opts.update(:fields => fields, :header => header))
      end

      def csv_header(names)
        names.map{|n| human_attribute_name(n) }
      end
    end

    module InstanceMethods
      def to_csv_ary(fields=nil, opts={})
        fields = attribute_names unless fields
        fields.map{|field|
          field.to_s.split(".").inject(self){|object, f|
            next unless object
            convert_method = "#{f}_as_csv"
            method = object.respond_to?(convert_method) ? convert_method : f
            object.send(method)
          }
        }
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
csv_rails-0.5.1 lib/csv_rails/active_record.rb