Class: Pfu::Generator

Inherits:
Object
  • Object
show all
Defined in:
lib/pfu/generator.rb

Class Method Summary collapse

Class Method Details

.write(opts) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/pfu/generator.rb', line 5

def self.write(opts)
  newpath  = "lib/puppet/functions/#{opts[:namespace]}/#{opts[:name]}.rb"
  if File.exist?(newpath)
    $logger.error "Cowardly refusing to overwrite #{newpath}"
    return
  end

  opts[:fullname] = case opts[:namespace]
  when '', nil
    opts[:name]
  else
    "#{opts[:namespace]}::#{opts[:name]}"
  end

  template = File.join(File.dirname(__FILE__), '..', '..', 'templates', 'function.erb')
  contents = ERB.new(File.read(template), nil, '-').result(binding)

  begin
    # syntax check the code before writing it
    RubyVM::InstructionSequence.compile(contents)
    FileUtils.mkdir_p("lib/puppet/functions/#{opts[:namespace]}")
    File.write(newpath, contents)
    $logger.info "Created #{newpath}."
  rescue Exception => e
    $logger.error "Oh crap; the generated function isn't valid Ruby code!"
    $logger.error e.message
    $logger.debug e.backtrace.join("\n")
  end

end