Module: Jade::Codegen::Pretty

Extended by:
Pretty
Included in:
Pretty
Defined in:
lib/jade/codegen/pretty.rb

Constant Summary collapse

INDENT =
"  "

Instance Method Summary collapse

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, footer = "end")
  body.empty? ? "#{header}\n#{footer}" : "#{header}\n#{indent(body)}\n#{footer}"
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

Returns:

  • (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