Class: TypstRails::Backends::Cli

Inherits:
Base
  • Object
show all
Defined in:
lib/typst_rails/backends/cli.rb

Overview

Compiles Typst documents by shelling out to the typst CLI executable.

This is the original TypstRails backend and remains the default when the typst gem is not installed. It requires Typst to be installed separately and available on PATH (or at Configuration#typst_executable_path).

Examples:

backend = TypstRails::Backends::Cli.new
backend.available? #=> true, if `typst` is on PATH
pdf_data = backend.compile("/tmp/doc.typ", "/tmp")

Instance Method Summary collapse

Constructor Details

#initialize(executable_path: nil) ⇒ Cli

Returns a new instance of Cli.

Parameters:



21
22
23
24
# File 'lib/typst_rails/backends/cli.rb', line 21

def initialize(executable_path: nil)
  super()
  @executable_path = executable_path
end

Instance Method Details

#available?Boolean

Returns whether the configured Typst executable can be found.

Returns:

  • (Boolean)

    whether the configured Typst executable can be found



27
28
29
30
31
# File 'lib/typst_rails/backends/cli.rb', line 27

def available?
  return true if File.exist?(executable_path)

  system("which #{executable_path} > /dev/null 2>&1") == true
end

#compile(typ_path, root_dir) ⇒ Object

See Also:



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/typst_rails/backends/cli.rb', line 34

def compile(typ_path, root_dir)
  output_pdf_path = File.join(root_dir, "#{File.basename(typ_path, ".typ")}_output.pdf")
  cmd = [executable_path, "compile", "--root", root_dir, typ_path, output_pdf_path]

  begin
    _stdout_str, stderr_str, status = Open3.capture3(*cmd)
  rescue Errno::ENOENT => e
    raise Error, "Typst executable not found. Please ensure Typst is installed and in your PATH. (#{e.message})"
  rescue StandardError => e
    raise Error, "Failed to execute Typst compiler: #{e.message}"
  end

  raise_compilation_failure(cmd, stderr_str) unless status.success?
  read_compiled_pdf(output_pdf_path)
ensure
  safe_unlink(output_pdf_path)
end