Class: TypstRails::Backends::Gem

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

Overview

Compiles Typst documents in-process using the typst RubyGem (https://rubygems.org/gems/typst), a native extension that embeds the Typst compiler.

This avoids the cost of spawning a subprocess for every render and does not require a separately installed typst executable. It is used automatically when the typst gem is available; add it to your Gemfile to opt in:

gem "typst"

Examples:

backend = TypstRails::Backends::Gem.new
backend.available? #=> true, if the `typst` gem is loaded
pdf_data = backend.compile("/tmp/doc.typ", "/tmp")

Instance Method Summary collapse

Instance Method Details

#available?Boolean

Returns whether the typst gem is installed and loadable.

Returns:

  • (Boolean)

    whether the typst gem is installed and loadable



24
25
26
27
28
29
30
31
32
33
# File 'lib/typst_rails/backends/gem.rb', line 24

def available?
  return true if defined?(::Typst::Pdf)

  begin
    require "typst"
    true
  rescue LoadError
    false
  end
end

#compile(typ_path, root_dir) ⇒ Object

See Also:



36
37
38
39
40
# File 'lib/typst_rails/backends/gem.rb', line 36

def compile(typ_path, root_dir)
  ::Typst::Pdf.new(file: typ_path, root: root_dir).compiled.document
rescue StandardError => e
  raise Error, "Typst compilation failed: #{e.message}"
end