Module: MarkdownAdapter
- Defined in:
- lib/taf/markdown_adapter.rb
Constant Summary collapse
- TAG_PREFIX =
Markdown format constants
"#".freeze
- TODO_PREFIX =
"- [ ]".freeze
- DONE_PREFIX =
"- [x]".freeze
- INDENT_SIZE =
Number of spaces per indent level
2
Class Method Summary collapse
-
.flatten_item(item, indent_level, rows) ⇒ Object
Recursively flattens a tree item and its children.
-
.read(file) ⇒ Object
Reads markdown and returns data as a tree structure.
-
.write(file, data) ⇒ Object
Writes data to markdown file (flattens tree structure).
Class Method Details
.flatten_item(item, indent_level, rows) ⇒ Object
Recursively flattens a tree item and its children
81 82 83 84 85 86 87 88 89 90 |
# File 'lib/taf/markdown_adapter.rb', line 81 def self.flatten_item(item, indent_level, rows) prefix = item.status == "todo" ? TODO_PREFIX : DONE_PREFIX indent = ' ' * (indent_level * INDENT_SIZE) rows << "#{indent}#{prefix} #{item.text}" # Recursively add children item.children.each do |child| flatten_item(child, indent_level + 1, rows) end end |
.read(file) ⇒ Object
Reads markdown and returns data as a tree structure
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
# File 'lib/taf/markdown_adapter.rb', line 12 def self.read(file) return {} unless File.exist?(file) rows = File .readlines(file) .map(&:rstrip) .reject { |line| line.nil? || line.empty? } {}.tap do |data| tag = TafHelper::DEFAULT_TAG # Stack to track parent at each indent level stack = [] rows.each do |row| if row.start_with?("#{TAG_PREFIX} ") tag = row.delete_prefix("#{TAG_PREFIX} ") data[tag] ||= [] stack = [] # Reset stack for new tag elsif tag.nil? next else # Calculate indent level from leading spaces leading_spaces = row[/^\s*/].length indent_level = leading_spaces / INDENT_SIZE stripped_row = row.lstrip # Trim stack to current indent level stack = stack[0...indent_level] # Determine parent parent = indent_level > 0 ? stack[indent_level - 1] : nil # Create the item status = stripped_row.start_with?("#{TODO_PREFIX} ") ? "todo" : "done" prefix = status == "todo" ? TODO_PREFIX : DONE_PREFIX item = Todo.new( status: status, text: stripped_row.delete_prefix("#{prefix} "), children: [], parent: parent ) # Add to parent's children or to root if indent_level == 0 data[tag] << item else parent.children << item end # Push current item onto stack stack[indent_level] = item end end end end |
.write(file, data) ⇒ Object
Writes data to markdown file (flattens tree structure)
69 70 71 72 73 74 75 76 77 78 |
# File 'lib/taf/markdown_adapter.rb', line 69 def self.write(file, data) rows = [] data.each do |tag, items| rows << "#{TAG_PREFIX} #{tag}" items.each do |item| flatten_item(item, 0, rows) end end File.write(file, rows.join("\n")) end |