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.



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

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



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

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
# 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



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

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

#chop!(index) ⇒ Object



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

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

#headersObject



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

def headers
  @sheet.rows.first
end

#rowsObject



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

def rows
  @sheet.rows
end

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



32
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
# File 'lib/flex_excel.rb', line 32

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