Class: Minidown::TableElement
- Defined in:
- lib/minidown/elements/table_element.rb
Constant Summary collapse
- AlignSpecRegexp =
/\A\|?\s*([\-:]\-+[\-:]\s*(?:\|\s*[\-:]\-+[\-:]\s*)*)\|?\s*\z/
Instance Attribute Summary
Attributes inherited from Element
#children, #content, #doc, #nodes
Instance Method Summary collapse
- #check_column_spec(raw_column_spec) ⇒ Object
-
#initialize(doc, content, raw_head) ⇒ TableElement
constructor
A new instance of TableElement.
- #parse ⇒ Object
- #to_html ⇒ Object
Methods inherited from Element
#blank?, #raw_content, #raw_content=, #unparsed_lines
Methods included from HtmlHelper
Constructor Details
#initialize(doc, content, raw_head) ⇒ TableElement
Returns a new instance of TableElement.
5 6 7 8 9 10 |
# File 'lib/minidown/elements/table_element.rb', line 5 def initialize doc, content, raw_head super doc, content @raw_head = raw_head @heads = @raw_head.split('|'.freeze).map! &:strip @column_count = @heads.count end |
Instance Method Details
#check_column_spec(raw_column_spec) ⇒ Object
12 13 14 15 16 17 18 |
# File 'lib/minidown/elements/table_element.rb', line 12 def check_column_spec raw_column_spec if @valid.nil? @valid = Utils::Regexp[:pipe_symbol] =~ raw_column_spec && AlignSpecRegexp =~ raw_column_spec && (column_spec_str = $1) && (@column_specs = column_spec_str.split('|'.freeze).map! &:strip) && @column_specs.count == @column_count else @valid end end |
#parse ⇒ Object
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/minidown/elements/table_element.rb', line 20 def parse if @valid nodes << self @bodys = [] @column_specs.map! do |column_spec| if column_spec[0] == column_spec[-1] column_spec[0] == ':'.freeze ? 'center'.freeze : nil else column_spec[0] == ':'.freeze ? 'left'.freeze : 'right'.freeze end end while line = unparsed_lines.shift if Utils::Regexp[:table] =~ line && (cells = $1.split('|'.freeze).map! &:strip) && @column_count == cells.count @bodys << cells else unparsed_lines.unshift line break end end else raise 'table column specs not valid' end end |
#to_html ⇒ Object
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
# File 'lib/minidown/elements/table_element.rb', line 45 def to_html attrs = @column_specs.map do |align| {align: align}.freeze if align end build_tag 'table'.freeze do |table| thead = build_tag 'thead'.freeze do |thead| tr = build_tag 'tr'.freeze do |tr| @heads.each_with_index do |cell, i| th = build_tag 'th'.freeze, attrs[i] do |th| th << cell end tr << th end end thead << tr end table << thead tbody = build_tag 'tbody'.freeze do |tbody| @bodys.each do |row| tr = build_tag 'tr'.freeze do |tr| row.each_with_index do |cell, i| td = build_tag 'td'.freeze, attrs[i] do |td| td << TextElement.new(doc, cell).to_html end tr << td end end tbody << tr end end table << tbody end end |