Sha256: f9adee6dc879ba993b92280eb4d644bdfcad081a528a70c21a983831db6af3d0

Contents?: true

Size: 1.33 KB

Versions: 2

Compression:

Stored size: 1.33 KB

Contents

require "json"
class ActiveReport::Record

  attr_accessor :datum, :only, :except, :headers, :options

  def initialize(datum, only: nil, except: nil, headers: nil, options: {})
    @datum   = datum
    @only    = only
    @except  = except
    @headers = headers
    @options = options
  end

  def self.export(datum, only: nil, except: nil, headers: nil, options: {})
    new(datum, only: only, except: except, headers: headers, options: options).export
  end

  def export
    @datum  = @datum.is_a?(ActiveRecord::Relation) ? JSON.parse(@datum.to_json).flatten : [].push(@datum.attributes).compact
    @only   = (@only.is_a?(Array)   ? @only   : [].push(@only).compact).map(&:to_s)
    @except = (@except.is_a?(Array) ? @except : [].push(@except).compact).map(&:to_s)

    CSV.generate(@options) do |csv|
      header = @datum.first.dup.keep_if   { |k,v| @only.include?(k) }   unless @only.empty?
      header = @datum.first.dup.delete_if { |k,v| @except.include?(k) } unless @except.empty?
      csv << (@headers || (header || @datum.first).keys.map { |k| k.to_s.gsub("_", " ").capitalize})

      @datum.each do |data|
        cell = data.dup.keep_if   { |k,v| @only.include?(k) }   unless @only.empty?
        cell = data.dup.delete_if { |k,v| @except.include?(k) } unless @except.empty?
        csv << (cell || data).values
      end
    end
  end

end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
active_report-1.0.0 lib/active_report/record.rb
active_report-0.0.1 lib/active_report/record.rb