Class: Oozby::Render

Inherits:
Object
  • Object
show all
Defined in:
lib/oozby/render.rb

Overview

takes in an oozby abstract tree, and writes out openscad source code

Instance Method Summary collapse

Constructor Details

#initialize(ooz: nil) ⇒ Render

Returns a new instance of Render.



5
6
7
# File 'lib/oozby/render.rb', line 5

def initialize ooz: nil
  @oozby = ooz
end

Instance Method Details

#escape(thing) ⇒ Object



9
10
11
# File 'lib/oozby/render.rb', line 9

def escape thing
  JSON.generate(thing, quirks_mode: true)
end

#render(code_tree, clean: true) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/oozby/render.rb', line 13

def render code_tree, clean: true
  output = []
  code_tree.each do |node|
    if node.key? :method
      # function call
      method_name = (node[:modifier].to_s || '') + node[:method].to_s
      
      args = node[:args].map { |a| escape(a) }
      node[:named_args].each do |key, value|
        args.push "#{key} = #{escape(value)}"
      end
      
      call = "#{method_name}(#{args.join(', ')})"
      if node[:children].nil? or node[:children].empty?
        output.push "#{call};"
      elsif node[:children].length == 1
        rendered_kids = render(node[:children])
        output.push "#{call} " + rendered_kids.shift
        output.push *rendered_kids
      else
        output.push "#{call} {"
        output.push   *render(node[:children]).map { |line| if clean then "  #{line}" else line.to_s end }
        output.push "}"
      end
      
    elsif node.key? :comment
      output.push "/* #{node[:comment]} */"
    elsif node.key? :assign
      output.push "#{node[:assign]} = #{escape(node[:value])};"
    elsif node.key? :import
      output.push "#{node[:execute] ? 'include' : 'use'} <#{node[:import]}>;"
    end
  end
  
  output
end