Sha256: f3a50c90a06377d193e27fd8f8e3b0d0b89861f045374af9f821ca34979e26cf

Contents?: true

Size: 1.03 KB

Versions: 3

Compression:

Stored size: 1.03 KB

Contents

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

    def initialize(collection, options = {})
      @collection = 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).class._attributes.dup

      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

3 entries across 3 versions & 1 rubygems

Version Path
active_model_exporters-0.3.1 lib/active_model/array_exporter.rb
active_model_exporters-0.3.0 lib/active_model/array_exporter.rb
active_model_exporters-0.2.0 lib/active_model/array_exporter.rb