Class: Tabulator::Reader::Worksheet

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(rows) ⇒ Worksheet

Returns a new instance of Worksheet.



55
56
57
# File 'lib/tabulator/reader.rb', line 55

def initialize rows
  @rows = rows
end

Class Method Details

.build(rows, **options) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/tabulator/reader.rb', line 19

def self.build rows, **options
  header = options[:header] || 0
  skip = options[:skip] || header + 1

  rejected_rows = *options[:reject]

  rejected_rows.each { |index_definition|
    next rows.delete_if &index_definition if index_definition.is_a? Proc
    rows.slice! index_definition
  }

  header_row = rows[header].reduce([]) { |accepted_headers, raw_header_col|
    accepted_headers << safe_generate_header(raw_header_col, accepted_headers)
  }

  new rows.drop(skip).map { |row|
    header_row.zip(row).to_h
  }
end

.generate_header(text) ⇒ Object



39
40
41
# File 'lib/tabulator/reader.rb', line 39

def self.generate_header text
  I18n.transliterate(text.strip.gsub(/\s/, '_')).downcase.to_sym
end

.safe_generate_header(text, headers) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
# File 'lib/tabulator/reader.rb', line 43

def self.safe_generate_header text, headers
  candidate = generate_header(text)
  suffix = 1

  while headers.include? candidate
    candidate = generate_header([text, suffix].join('_'))
    suffix += 1
  end

  candidate
end

Instance Method Details

#apply(target) ⇒ Object



67
68
69
70
71
72
# File 'lib/tabulator/reader.rb', line 67

def apply target
  self.class.new to_a.map { |row|
    row[target] = yield row[target], row
    row
  }
end

#only(*cols) ⇒ Object



59
60
61
62
63
64
65
# File 'lib/tabulator/reader.rb', line 59

def only *cols
  self.class.new to_a.map { |row|
    row.select { |title, _|
      cols.include? title
    }
  }
end

#rejectObject



74
75
76
77
78
# File 'lib/tabulator/reader.rb', line 74

def reject
  self.class.new to_a.reject { |row|
    yield row
  }
end

#save(path) ⇒ Object



88
89
90
91
92
# File 'lib/tabulator/reader.rb', line 88

def save path
  File.open(path, "w") { |file|
    file.write to_json
  }
end

#to_aObject



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

def to_a
  Marshal.load(Marshal.dump(@rows))
end

#to_json(**dump_options) ⇒ Object



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

def to_json **dump_options
  to_a.to_json(json_dump_options.merge dump_options)
end