Class: CSVtender

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

Instance Method Summary collapse

Constructor Details

#initialize(table = []) ⇒ CSVtender

Creates a new CSVtender.

Parameters:

  • table (Array) (defaults to: [])

    Optional: initial data for the table


4
5
6
7
8
# File 'lib/csvtender.rb', line 4

def initialize(table = [])
  @table = table
  @orientation = :standard
  @headers = false
end

Instance Method Details

#colsObject

Orients the table transposed - table contains columns which contain cells.


30
31
32
33
# File 'lib/csvtender.rb', line 30

def cols
  @orientation = :vertical
  self
end

#countObject

The number of rows this table contains.


43
44
45
# File 'lib/csvtender.rb', line 43

def count
  show.count
end

#inspectObject


19
20
21
# File 'lib/csvtender.rb', line 19

def inspect
  @table
end

#map(mutator = nil, &block) ⇒ Object

Maps each row or column in this table over a user-provided function.


48
49
50
# File 'lib/csvtender.rb', line 48

def map(mutator = nil, &block)
  delegate :map!, mutator, &block
end

#reject(mutator = nil, &block) ⇒ Object

Calls the user-provided function and rejects items for which the function returns truthy.


58
59
60
# File 'lib/csvtender.rb', line 58

def reject(mutator = nil, &block)
  delegate :reject!, mutator, &block
end

#rowsObject

Orients the table traditionally - table contains rows which contain cells.


24
25
26
27
# File 'lib/csvtender.rb', line 24

def rows
  @orientation = :standard
  self
end

#select(mutator = nil, &block) ⇒ Object

Calls the user-provided function and includes only items for which the function returns truthy.


53
54
55
# File 'lib/csvtender.rb', line 53

def select(mutator = nil, &block)
  delegate :select!, mutator, &block
end

#showObject

Outputs the table as an array of rows.


36
37
38
39
40
# File 'lib/csvtender.rb', line 36

def show
  table = nil
  oriented { table = @table }
  table
end

#to_sObject


10
11
12
13
14
15
16
17
# File 'lib/csvtender.rb', line 10

def to_s
  s = @table.count != 1 ? 's' : ''
  meta = [
    "#{@table.count} row#{s}",
    @headers ? 'headers' : nil
  ].compact.join ', '
  "\#<CSVtender: #{meta}>"
end

#with_headersObject

Treat this table as if the first row is a header row.


63
64
65
66
67
68
69
70
71
# File 'lib/csvtender.rb', line 63

def with_headers
  return self if @headers
  oriented do
    @headers = true
    header, *rows = @table
    @table = rows.map! { |row| header.zip(row).to_h }
  end
  self
end

#without_headersObject

Treat this table as if it has no header row.


74
75
76
77
78
79
80
81
# File 'lib/csvtender.rb', line 74

def without_headers
  return self unless @headers
  @headers = false
  header = @table.first.keys
  without_keys = @table.map(&:values)
  @table = [header].concat without_keys
  self
end