Class: FlexExcel

Inherits:
Object
  • Object
show all
Defined in:
lib/flex_excel.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, sheet) ⇒ FlexExcel

Returns a new instance of FlexExcel.



28
29
30
31
# File 'lib/flex_excel.rb', line 28

def initialize (path, sheet)
  @sheet = SimpleXlsxReader.open(path).sheets[sheet]
  @rows = @sheet.rows
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object



76
77
78
# File 'lib/flex_excel.rb', line 76

def method_missing (method, *args)
  @rows.send(method, *args)
end

Class Method Details

.mass_cast(hashes, scheme) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/flex_excel.rb', line 7

def mass_cast (hashes, scheme)
  keys = hashes.first.keys

  hashes.each { |hash|
    hash.values.each_with_index { |value, index|
      if scheme[index].is_a?(Array)
        new_value = value
        scheme[index].each { |meth|
          new_value = new_value.send(meth)
        }
        hash.store(keys[index], new_value)
      elsif scheme[index] != 0
        hash.store(keys[index], value.send(scheme[index]))
      end
    }
  }
  hashes
end

Instance Method Details

#add_headers!(headers) ⇒ Object



68
69
70
# File 'lib/flex_excel.rb', line 68

def add_headers! (headers)
  @rows.unshift(headers)
end

#chop!(index) ⇒ Object



72
73
74
# File 'lib/flex_excel.rb', line 72

def chop! (index)
  @rows.map { |row| row[0..index]}
end

#headersObject



84
85
86
# File 'lib/flex_excel.rb', line 84

def headers
  @sheet.rows.first
end

#rowsObject



80
81
82
# File 'lib/flex_excel.rb', line 80

def rows
  @sheet.rows
end

#to_hash(mode = nil, labels = [], convert = {}, filter = {}) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/flex_excel.rb', line 33

def to_hash (mode = nil, labels = [], convert = {}, filter = {})
  hdr = headers
  raise ArgumentError('Headers must be unique') if hdr.compact.size != hdr.compact.uniq.size
  output = []
  @rows[1..-1].each { |row|
    hash = {}
    hdr.each_with_index { |label, index|

      if filter.keys.include?(label.downcase) && filter[label.downcase] ==
          row[index]
        hash = nil
        break
      else

        if convert.empty?
          key = label
        else
          key = convert[label.downcase] unless label.nil?
        end

        if mode.nil?
          hash.store(key, row[index]) unless label.nil?
        elsif mode == 'trim'
          hash.store(key, row[index]) unless label.nil? || labels.include?(label.downcase)
        elsif mode == 'keep'
          hash.store(key, row[index]) if key != nil && labels.include?(label.downcase)
        end
      end

    }
    output << hash
  }
  output.compact!
end