Sha256: fa3321a98a90866d58df74f9a968b75f87695bcff70b41b4cc588503db14f51e

Contents?: true

Size: 1.02 KB

Versions: 6

Compression:

Stored size: 1.02 KB

Contents

module ActiveModel
  class ArrayExporter
    attr_reader :collection, :exporter, :scope

    def initialize(collection, options = {})
      @collection = Array(collection)
      @scope      = options.delete(:scope)
      @exporter   = options.delete(:exporter)
    end

    def to_csv
      generate_file
    end

    def to_xls
      generate_file(col_sep: "\t")
    end

    private

    def generate_file(options = {})
      CSV.generate(options) do |file|
        file << headers
        collection.each do |object|
          file << exporter_for(object).values
        end
      end
    end

    def exporter_for(object)
      exporter_class = exporter || Exporter.exporter_for(object)
      exporter_class.new(object, scope: scope)
    end

    def headers
      object = collection.first
      attributes = exporter_for(object).attributes

      if object.class.respond_to?(:human_attribute_name)
        attributes.map { |attr| object.class.human_attribute_name(attr) }
      else
        attributes.map(&:to_s)
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
active_model_exporters-0.5.2 lib/active_model/array_exporter.rb
active_model_exporters-0.5.1 lib/active_model/array_exporter.rb
active_model_exporters-0.5.0 lib/active_model/array_exporter.rb
active_model_exporters-0.4.1 lib/active_model/array_exporter.rb
active_model_exporters-0.4.0 lib/active_model/array_exporter.rb
active_model_exporters-0.3.2 lib/active_model/array_exporter.rb