Sha256: e97aa00243ba6e206ca3248ef16c1fcfb758fd324f654b3715975fa385419e06

Contents?: true

Size: 1.87 KB

Versions: 2

Compression:

Stored size: 1.87 KB

Contents

require "json"
class ActiveReport::Record

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

  def initialize(datum, model: nil, only: nil, except: nil, headers: nil, options: {})
    @datum   = datum
    @model   = model
    @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 self.import(datum, model: nil, only: nil, except: nil, headers: nil, options: {})
    new(datum, model: model, only: only, except: except, headers: headers, options: options).import
  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

  def import
    if @model.nil? || (@model.superclass != ActiveRecord::Base)
      raise ArgumentError,
        "Model must be an ActiveRecord::Base object."
    end

    processed_datum = ActiveReport::Hash.import(@datum, headers: @headers, options: @options)
    processed_datum.each { |data| @model.create(data) }
  end

end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
active_report-1.2.0 lib/active_report/record.rb
active_report-1.1.0 lib/active_report/record.rb