Class: Aura::Emitter

Inherits:
Object
  • Object
show all
Defined in:
lib/aura/emitter.rb

Overview

A tiny indentation-aware code builder. Replaces ad-hoc string concatenation in the code generator so emitted Ruby is consistently indented and blocks are hard to leave unbalanced.

e = Emitter.new
e.line "x = 1"
e.block("def forward(x)") { e.line "x" }
e.to_s

Constant Summary collapse

INDENT =
"  "

Instance Method Summary collapse

Constructor Details

#initializeEmitter

Returns a new instance of Emitter.



16
17
18
19
# File 'lib/aura/emitter.rb', line 16

def initialize
  @lines = []
  @depth = 0
end

Instance Method Details

#blankObject

Append a blank line.



30
31
32
33
# File 'lib/aura/emitter.rb', line 30

def blank
  @lines << ""
  self
end

#block(header, footer = "end") ⇒ Object

Emit ‘header` then an indented body produced by the block, then `footer` (defaults to `end`). Used for classes, methods, and Ruby blocks.



42
43
44
45
46
47
# File 'lib/aura/emitter.rb', line 42

def block(header, footer = "end")
  line(header)
  indent { yield self }
  line(footer)
  self
end

#comment(text) ⇒ Object

Append a comment line.



36
37
38
# File 'lib/aura/emitter.rb', line 36

def comment(text)
  line("# #{text}")
end

#indentObject

Increase indentation for the duration of the block.



50
51
52
53
54
55
# File 'lib/aura/emitter.rb', line 50

def indent
  @depth += 1
  yield self
ensure
  @depth -= 1
end

#line(text = "") ⇒ Object

Append a line (or several “n”-separated lines) at the current indent.



22
23
24
25
26
27
# File 'lib/aura/emitter.rb', line 22

def line(text = "")
  text.to_s.split("\n", -1).each do |raw|
    @lines << (raw.empty? ? "" : "#{INDENT * @depth}#{raw}")
  end
  self
end

#to_sObject



57
58
59
# File 'lib/aura/emitter.rb', line 57

def to_s
  "#{@lines.join("\n")}\n"
end