Class: ActiveReport::Hash

Inherits:
Base
  • Object
show all
Defined in:
lib/active_report/hash.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

evaluate

Constructor Details

#initialize(datum, only: nil, except: nil, headers: nil, options: {}) ⇒ Hash

Returns a new instance of Hash.



5
6
7
8
# File 'lib/active_report/hash.rb', line 5

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

Instance Attribute Details

#datumObject

Returns the value of attribute datum.



3
4
5
# File 'lib/active_report/hash.rb', line 3

def datum
  @datum
end

#exceptObject

Returns the value of attribute except.



3
4
5
# File 'lib/active_report/hash.rb', line 3

def except
  @except
end

#headersObject

Returns the value of attribute headers.



3
4
5
# File 'lib/active_report/hash.rb', line 3

def headers
  @headers
end

#onlyObject

Returns the value of attribute only.



3
4
5
# File 'lib/active_report/hash.rb', line 3

def only
  @only
end

#optionsObject

Returns the value of attribute options.



3
4
5
# File 'lib/active_report/hash.rb', line 3

def options
  @options
end

Class Method Details

.export(datum, only: nil, except: nil, headers: nil, options: {}) ⇒ Object



10
11
12
# File 'lib/active_report/hash.rb', line 10

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

.import(datum, only: nil, except: nil, headers: nil, options: {}) ⇒ Object



14
15
16
# File 'lib/active_report/hash.rb', line 14

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

Instance Method Details

#exportObject



18
19
20
21
22
23
24
25
# File 'lib/active_report/hash.rb', line 18

def export
  @datum, @only, @except = munge(@datum), munge(@only), munge(@except)

  CSV.generate(@options) do |csv|
    csv << (@headers || (filter_first(@datum) || @datum.first).keys.map { |header| humanize(header) })
    @datum.lazy.each { |data| csv << (filter(data) || data).values }
  end
end

#importObject



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/active_report/hash.rb', line 27

def import
  @only, @except = munge(@only), munge(@except)

  datum = []
  CSV.foreach(@datum, @options).with_index do |data, line|
    data = encode_to_utf8(data) if force_encoding?

    if @headers.nil? && line.zero?
      @headers = data
    else
      subdata = {}
      @headers.lazy.each_with_index do |header, i|
        subdata.store(header.to_s, data.fetch(i, nil))
      end
      filter(subdata)
      datum.push(subdata)
    end
  end

  datum = datum.first if datum.size == 1
  datum = metatransform(datum)
  datum
end