Module: Pug

Defined in:
lib/pug-ruby/config.rb,
lib/pug-ruby/compile.rb

Defined Under Namespace

Classes: CompileError, Config, ExecutableError

Class Method Summary collapse

Class Method Details

.check_executable!Object



54
55
56
57
58
59
60
61
62
# File 'lib/pug-ruby/compile.rb', line 54

def check_executable!
  unless @executable_checked
    `pug --version`
    unless $?.success?
      raise ExecutableError, 'No pug executable found in your system. Did you forget to "npm install -g pug-cli"?'
    end
    @executable_checked = true
  end
end

.compile(source, options = {}) ⇒ Object

Raises:



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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/pug-ruby/compile.rb', line 8

def compile(source, options = {})
  check_executable!

  source  = source.read if source.respond_to?(:read)
  options = config.to_hash.merge(options)

  # https://github.com/pugjs/pug-cli
  cmd = ['pug']

  options[:compileDebug]           = options[:compile_debug]
  options[:nameAfterFile]          = options[:name_after_file]
  options[:inlineRuntimeFunctions] = options[:inline_runtime_functions]

  options.respond_to?(:compact) ? options.compact : options.delete_if { |k, v| v.nil? }

  # Command line arguments take precedence over json options
  # https://github.com/pugjs/pug-cli/blob/master/index.js
  cmd.push('--obj',             JSON.generate(options))

  cmd.push('--out',             escape(options[:out]))             if options[:out]
  cmd.push('--path',            escape(options[:filename]))        if options[:filename]
  cmd.push('--basedir',         escape(options[:basedir]))         if options[:basedir]
  cmd.push('--pretty')                                             if options[:pretty]
  cmd.push('--client')                                             if options[:client]
  cmd.push('--name',            escape(options[:name]))            if options[:name]
  cmd.push('--no-debug')                                           unless options[:compile_debug]
  cmd.push('--extension',       escape(options[:extension]))       if options[:extension]
  cmd.push('--silent')                                             if options[:silent]
  cmd.push('--name-after-file', escape(options[:name_after_file])) if options[:name_after_file]
  cmd.push('--doctype',         escape(options[:doctype]))         if options[:doctype]

  stdout, stderr, exit_status = Open3.capture3(*cmd, stdin_data: source)

  raise CompileError.new(stderr) unless exit_status.success?

  if options[:client]
    if options[:inline_runtime_functions]
      %{ (function() { #{stdout}; return #{options[:name]}; }).call(this); }
    else
      %{ (function(pug) { #{stdout}; return #{options[:name]}; }).call(this, pug); }
    end
  else
    stdout
  end
end