Class: Aura::Emitter
- Inherits:
-
Object
- Object
- Aura::Emitter
- 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
-
#blank ⇒ Object
Append a blank line.
-
#block(header, footer = "end") ⇒ Object
Emit ‘header` then an indented body produced by the block, then `footer` (defaults to `end`).
-
#comment(text) ⇒ Object
Append a comment line.
-
#indent ⇒ Object
Increase indentation for the duration of the block.
-
#initialize ⇒ Emitter
constructor
A new instance of Emitter.
-
#line(text = "") ⇒ Object
Append a line (or several “n”-separated lines) at the current indent.
- #to_s ⇒ Object
Constructor Details
#initialize ⇒ Emitter
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
#blank ⇒ Object
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, = "end") line(header) indent { yield self } line() 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 |
#indent ⇒ Object
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_s ⇒ Object
57 58 59 |
# File 'lib/aura/emitter.rb', line 57 def to_s "#{@lines.join("\n")}\n" end |