Module: WeasyPDF::ViewHelpers::Assets

Defined in:
lib/weasy_pdf/view_helpers/assets.rb

Overview

Base asset helpers. Resolves assets from public/ directories on disk. When vite_ruby is present, ViteAssets is included on top and overrides resolution to use the Vite manifest instead.

Constant Summary collapse

ASSET_URL_REGEX =
/url\(['"]?([^'")\s]+?)['"]?\)/

Instance Method Summary collapse

Instance Method Details

#weasy_pdf_asset_base64(path) ⇒ Object



39
40
41
42
43
# File 'lib/weasy_pdf/view_helpers/assets.rb', line 39

def weasy_pdf_asset_base64(path)
  disk = find_asset_path(path) { raise WeasyPDF::MissingLocalAsset, path }
  base64 = Base64.strict_encode64(File.binread(disk))
  "data:#{mime_for(path)};base64,#{base64}"
end

#weasy_pdf_asset_path(asset) ⇒ Object

── Asset paths ────────────────────────────────────────────────────



33
34
35
36
37
# File 'lib/weasy_pdf/view_helpers/assets.rb', line 33

def weasy_pdf_asset_path(asset)
  return asset if asset.to_s.start_with?("http://", "https://", "data:", "//")

  resolve_asset_path(asset)
end

#weasy_pdf_image_tag(source, options = {}) ⇒ Object

── Images ─────────────────────────────────────────────────────────



27
28
29
# File 'lib/weasy_pdf/view_helpers/assets.rb', line 27

def weasy_pdf_image_tag(source, options = {})
  image_tag(weasy_pdf_asset_path(source), options)
end

── Stylesheets ────────────────────────────────────────────────────



15
16
17
18
19
20
21
22
23
# File 'lib/weasy_pdf/view_helpers/assets.rb', line 15

def weasy_pdf_stylesheet_link_tag(*sources)
  sources.map do |source|
    source = add_extension(source, "css")
    path = find_asset_path(source) { raise WeasyPDF::MissingLocalAsset, source }
    css = File.read(path, encoding: "utf-8")
    css = rewrite_asset_urls(css)
    "<style type='text/css'>#{css}</style>"
  end.join("\n").html_safe
end

#weasy_pdf_url_base64(url) ⇒ Object



45
46
47
48
49
50
51
52
# File 'lib/weasy_pdf/view_helpers/assets.rb', line 45

def weasy_pdf_url_base64(url)
  require "net/http"
  response = Net::HTTP.get_response(URI.parse(url))
  raise WeasyPDF::MissingRemoteAsset.new(url, response) unless response.is_a?(Net::HTTPSuccess)

  base64 = Base64.strict_encode64(response.body.b)
  "data:#{response.content_type};base64,#{base64}"
end