Class: Tabulator::Reader::Worksheet
- Inherits:
-
Object
- Object
- Tabulator::Reader::Worksheet
- Defined in:
- lib/tabulator/reader.rb
Class Method Summary collapse
- .build(rows, **options) ⇒ Object
- .generate_header(text) ⇒ Object
- .safe_generate_header(text, headers) ⇒ Object
Instance Method Summary collapse
- #apply(target) ⇒ Object
-
#initialize(rows) ⇒ Worksheet
constructor
A new instance of Worksheet.
- #only(*cols) ⇒ Object
- #reject ⇒ Object
- #save(path) ⇒ Object
- #to_a ⇒ Object
- #to_json(**dump_options) ⇒ Object
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, ** header = [:header] || 0 skip = [:skip] || header + 1 rejected_rows = *[: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 |
#reject ⇒ Object
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_a ⇒ Object
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 ** to_a.to_json(.merge ) end |