Class: Decode::Comment::Example

Inherits:
Tag
  • Object
show all
Defined in:
lib/decode/comment/example.rb

Overview

Represents a code example with an optional title.

  • ‘@example Title`

  • ‘@example`

Should contain nested text lines representing the example code.

Constant Summary

Constants inherited from Tag

Tag::PATTERN

Instance Attribute Summary collapse

Attributes inherited from Tag

#The directive that generated the tag., #directive

Attributes inherited from Node

#The children of this node., #children

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Tag

bracketed_content, build, match

Methods inherited from Node

#add, #children?, #each, #filter, #text, #traverse

Constructor Details

#initialize(directive, title = nil) ⇒ Example

Initialize a new example tag.



36
37
38
39
40
41
# File 'lib/decode/comment/example.rb', line 36

def initialize(directive, title = nil)
  super(directive)
  
  # @type ivar @title: String?
  @title = title&.strip unless title&.empty?
end

Instance Attribute Details

#The title of the example.(titleoftheexample.) ⇒ Object (readonly)



44
# File 'lib/decode/comment/example.rb', line 44

attr :title

#titleObject (readonly)

Returns the value of attribute title.



44
45
46
# File 'lib/decode/comment/example.rb', line 44

def title
  @title
end

Class Method Details

.parse(directive, text, lines, tags, level = 0) ⇒ Object

Parse an example directive from text.



23
24
25
26
27
28
29
30
31
# File 'lib/decode/comment/example.rb', line 23

def self.parse(directive, text, lines, tags, level = 0)
  node = self.new(directive, text)
  
  tags.parse(lines, level + 1) do |child|
    node.add(child)
  end
  
  return node
end

Instance Method Details

#codeObject

Get the example code as a single string with leading indentation removed.



48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/decode/comment/example.rb', line 48

def code
  lines = text
  return unless lines
  
  # Get the indentation from the first line
  if indentation = lines.first[/\A\s+/]
    # Remove the base indentation from all lines
    lines = lines.map{|line| line.sub(indentation, "")}
  end
  
  return lines.join("\n")
end