Class: Marktable::Table

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/marktable/table.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source, type: :markdown, headers: nil) ⇒ Table

Returns a new instance of Table.



11
12
13
14
15
16
17
18
19
20
# File 'lib/marktable/table.rb', line 11

def initialize(source, type: :markdown, headers: nil)
  parser = Tables::Base.for(type).new(source, headers)
  result = parser.parse
  @rows = result.rows
  @headers = result.headers
  # Validate headers if present and not explicitly disabled
  validate_headers if @headers && headers != false
  # Fix: Initialize @has_headers based on whether @headers is present
  @has_headers = !@headers.nil?
end

Instance Attribute Details

#headersObject (readonly)

Returns the value of attribute headers.



9
10
11
# File 'lib/marktable/table.rb', line 9

def headers
  @headers
end

Instance Method Details

#[](index) ⇒ Object

Support for accessing by index like table



61
62
63
# File 'lib/marktable/table.rb', line 61

def [](index)
  @rows[index]
end

#each(&block) ⇒ Object

Iteration support



23
24
25
26
27
# File 'lib/marktable/table.rb', line 23

def each(&block)
  return enum_for(:each) unless block_given?

  @rows.each(&block)
end

#empty?Boolean

Returns:

  • (Boolean)


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

def empty?
  @rows.empty?
end

#sizeObject Also known as: length

Returns the number of rows



66
67
68
# File 'lib/marktable/table.rb', line 66

def size
  @rows.size
end

#to_aObject

Returns the table as an Array of Hashes if headers are present or Array of Arrays if no headers



31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/marktable/table.rb', line 31

def to_a
  if @has_headers
    # Convert rows to hashes, which will automatically exclude values without headers
    @rows.map(&:to_hash)
  else
    # When no headers, return array of arrays with consistent length
    max_length = @rows.map { |row| row.values.length }.max || 0
    @rows.map do |row|
      values = row.values
      values + Array.new(max_length - values.length, '')
    end
  end
end

#to_csvObject

Generate CSV representation



56
57
58
# File 'lib/marktable/table.rb', line 56

def to_csv
  Formatters::Base.for(:csv).format(@rows, @headers)
end

#to_htmlObject



45
46
47
# File 'lib/marktable/table.rb', line 45

def to_html
  Formatters::Base.for(:html).format(@rows, @headers)
end

#to_mdObject Also known as: generate

Generate markdown representation



50
51
52
# File 'lib/marktable/table.rb', line 50

def to_md
  Formatters::Base.for(:markdown).format(@rows, @headers)
end