Module: Jade::Codegen::Pretty
Constant Summary collapse
- INDENT =
" "
Instance Method Summary collapse
- #array(items) ⇒ Object
- #block(header, body, footer = "end") ⇒ Object
-
#call(callee, args, width: 80, open: '(', close: ')') ⇒ Object
‘callee(a, b, c)` on one line when it fits, multi-line with trailing comma when it doesn’t or when an arg is already multi-line.
- #hash(pairs) ⇒ Object
- #indent(str, levels = 1) ⇒ Object
- #lambda(params, body) ⇒ Object
- #multiline?(str) ⇒ Boolean
- #newline(count = 1) ⇒ Object
Instance Method Details
#array(items) ⇒ Object
31 32 33 |
# File 'lib/jade/codegen/pretty.rb', line 31 def array(items) "[#{items.join(', ')}]" end |
#block(header, body, footer = "end") ⇒ Object
16 17 18 |
# File 'lib/jade/codegen/pretty.rb', line 16 def block(header, body, = "end") body.empty? ? "#{header}\n#{}" : "#{header}\n#{indent(body)}\n#{}" end |
#call(callee, args, width: 80, open: '(', close: ')') ⇒ Object
‘callee(a, b, c)` on one line when it fits, multi-line with trailing comma when it doesn’t or when an arg is already multi-line. Pass ‘open:`/`close:` to emit `Struct[a, b, c]`-shaped construction.
38 39 40 41 42 43 44 45 46 |
# File 'lib/jade/codegen/pretty.rb', line 38 def call(callee, args, width: 80, open: '(', close: ')') "#{callee}#{open}#{args.join(', ')}#{close}".then do |oneline| if oneline.length <= width && args.none? { multiline?(it) } oneline else "#{callee}#{open}\n#{indent(args.join(",\n"))},\n#{close}" end end end |
#hash(pairs) ⇒ Object
24 25 26 27 28 29 |
# File 'lib/jade/codegen/pretty.rb', line 24 def hash(pairs) pairs .map { |k, v| "#{k.inspect} => #{v}" } .join(', ') .then { "{ #{it} }" } end |
#indent(str, levels = 1) ⇒ Object
12 13 14 |
# File 'lib/jade/codegen/pretty.rb', line 12 def indent(str, levels = 1) str.gsub(/^(?!$)/, INDENT * levels) end |
#lambda(params, body) ⇒ Object
20 21 22 |
# File 'lib/jade/codegen/pretty.rb', line 20 def lambda(params, body) multiline?(body) ? block("->(#{params}) {", body, "}") : "->(#{params}) { #{body} }" end |
#multiline?(str) ⇒ Boolean
48 49 50 |
# File 'lib/jade/codegen/pretty.rb', line 48 def multiline?(str) str.include?("\n") end |
#newline(count = 1) ⇒ Object
8 9 10 |
# File 'lib/jade/codegen/pretty.rb', line 8 def newline(count = 1) "\n" * count end |