|
| 1 | +package gemini |
| 2 | + |
| 3 | +// DocumentBuilder allows programatic document creation using the builder pattern. |
| 4 | +// |
| 5 | +// Example: |
| 6 | +// ``` |
| 7 | +// document := NewDocumentBuilder() |
| 8 | +// document.AddH1Header("Hello world!") |
| 9 | +// document.AddLine("Reasons to use this builder:") |
| 10 | +// document.AddBullet("It's easy to use.") |
| 11 | +// document.AddBullet("it's easy to grok the code!") |
| 12 | +// document.AddLink("/about", "click here for more!") |
| 13 | +// |
| 14 | +// responseWriter.Write(document.Build()) |
| 15 | +// ``` |
| 16 | +type DocumentBuilder struct { |
| 17 | + body string |
| 18 | +} |
| 19 | + |
| 20 | +// Instantiate a new DocumentBuilder. |
| 21 | +func NewDocumentBuilder() DocumentBuilder { |
| 22 | + return DocumentBuilder{} |
| 23 | +} |
| 24 | + |
| 25 | +// Add a new line to the document. Adds a newline to the end of the line if none is present. |
| 26 | +func (self *DocumentBuilder) AddLine(line string) { |
| 27 | + // Insure lines are always newline terminated |
| 28 | + if len(line) == 0 || line[len(line) - 1] != '\n' { |
| 29 | + line += "\n" |
| 30 | + } |
| 31 | + |
| 32 | + self.body += line |
| 33 | +} |
| 34 | + |
| 35 | +// Add an H1 (#) header line to the document. |
| 36 | +func (self *DocumentBuilder) AddH1Header(header string) { |
| 37 | + self.AddLine("# " + header) |
| 38 | +} |
| 39 | + |
| 40 | +// Add an H2 (##) header line to the document. |
| 41 | +func (self *DocumentBuilder) AddH2Header(header string) { |
| 42 | + self.AddLine("## " + header) |
| 43 | +} |
| 44 | + |
| 45 | +// Add an H3 (###) header line to the document. |
| 46 | +func (self *DocumentBuilder) AddH3Header(header string) { |
| 47 | + self.AddLine("### " + header) |
| 48 | +} |
| 49 | + |
| 50 | +// Add a quote line to the document. |
| 51 | +func (self *DocumentBuilder) AddQuote(header string) { |
| 52 | + self.AddLine("> " + header) |
| 53 | +} |
| 54 | + |
| 55 | +// Add an unordered list item to the document. |
| 56 | +func (self *DocumentBuilder) AddBullet(header string) { |
| 57 | + self.AddLine("* " + header) |
| 58 | +} |
| 59 | + |
| 60 | +// Add a toggle formatting line to the document. |
| 61 | +func (self *DocumentBuilder) ToggleFormatting() { |
| 62 | + self.AddLine("```") |
| 63 | +} |
| 64 | + |
| 65 | +// Add an aliased link line to the document. |
| 66 | +func (self *DocumentBuilder) AddLink(url string, title string) { |
| 67 | + self.AddLine("=> " + url + "\t" + title) |
| 68 | +} |
| 69 | + |
| 70 | +// Add a link line to the document. |
| 71 | +func (self *DocumentBuilder) AddRawLink(url string) { |
| 72 | + self.AddLine("=> " + url) |
| 73 | +} |
| 74 | + |
| 75 | +// Build the document into a serialized byte slice. |
| 76 | +func (self *DocumentBuilder) Build() []byte { |
| 77 | + return []byte(self.body) |
| 78 | +} |
0 commit comments