Class: DrgDSL::PrettyPrinter

Inherits:
Object
  • Object
show all
Includes:
Visitor
Defined in:
lib/drgdsl/pretty_printer.rb

Constant Summary collapse

OUTPUT_FORMATS =
%i[string html bash].freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Visitor

included, #visit

Constructor Details

#initialize(output_format: :string, multiline: true) ⇒ PrettyPrinter

Returns a new instance of PrettyPrinter.

Parameters:

  • output_format (Symbol) (defaults to: :string)
  • multiline (Boolean) (defaults to: true)


33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/drgdsl/pretty_printer.rb', line 33

def initialize(output_format: :string,
               multiline: true)

  @indentation_level = 0
  @indentation_string = '  '

  unless OUTPUT_FORMATS.include?(output_format)
    raise "Unknown output format: #{output_format.inspect}"
  end

  @output_format = output_format
  @multiline = multiline
end

Instance Attribute Details

#indentation_levelObject (readonly)

Returns the value of attribute indentation_level.



17
18
19
# File 'lib/drgdsl/pretty_printer.rb', line 17

def indentation_level
  @indentation_level
end

#indentation_stringObject (readonly)

Returns the value of attribute indentation_string.



17
18
19
# File 'lib/drgdsl/pretty_printer.rb', line 17

def indentation_string
  @indentation_string
end

#output_formatObject (readonly)

Returns the value of attribute output_format.



17
18
19
# File 'lib/drgdsl/pretty_printer.rb', line 17

def output_format
  @output_format
end

Class Method Details

.pretty_print(expression, **options) ⇒ String

Parameters:

  • expression (String)

Returns:

  • (String)


21
22
23
24
25
26
27
28
29
# File 'lib/drgdsl/pretty_printer.rb', line 21

def self.pretty_print(expression, **options)
  ast = Parser.parse(expression)
  ast = ParenCleaner.clean(ast) if options.delete(:remove_redundant_parens)

  output = ast.accept(new(**options))
  output_format = options[:output_format]
  return "<pre>#{output}</pre>" if output_format == :html
  output
end

Instance Method Details

#cache?Boolean

Returns:

  • (Boolean)


55
56
57
# File 'lib/drgdsl/pretty_printer.rb', line 55

def cache?
  true
end

#cache_key(n) ⇒ Object



59
60
61
62
63
64
65
66
67
# File 'lib/drgdsl/pretty_printer.rb', line 59

def cache_key(n)
  [
    n.hash,
    @indentation_level,
    @indentation_string,
    @output_format,
    @multiline
  ].hash
end

#multiline?Boolean

Returns:

  • (Boolean)


47
48
49
# File 'lib/drgdsl/pretty_printer.rb', line 47

def multiline?
  @multiline
end

#visit_nilObject



51
52
53
# File 'lib/drgdsl/pretty_printer.rb', line 51

def visit_nil
  ''
end