Module: Sghtmltopdf::ViewHelpers

Defined in:
lib/sghtmltopdf/view_helpers.rb

Overview

Action View用のヘルパ。

PDFのレンダリングはHTTPサーバを介さないため、/assets/…のようなURLは ローカルファイルとして解決される(--base-urlの既定は Rails.root/public。[Railtie.default_options])。precompile済みの 本番環境ではこれで素のstylesheet_link_tagもそのまま動くが、開発環境の ようにアセットがまだpublic/へ書き出されていない場合は解決できない。

そこで、

<%= sghtmltopdf_stylesheet_link_tag "pdf" %>

のようにCSSの中身を<style>へ展開するヘルパを用意する(wicked_pdfの wicked_pdf_stylesheet_link_tagに相当)。

Instance Method Summary collapse

Instance Method Details

#sghtmltopdf_asset_path(source) ⇒ Object

アセットのローカルファイルパスを返す。見つからなければnil

  1. public/配下(precompile済み。本番環境)
  2. アセットパイプラインのロードパス(開発環境。Propshaft/Sprockets)

の順に探す。パイプラインの参照はどちらのgemにも依存しないよう respond_to?で分岐している(best effort)。



26
27
28
29
30
31
# File 'lib/sghtmltopdf/view_helpers.rb', line 26

def sghtmltopdf_asset_path(source)
  path = source.to_s
  return path if path.start_with?("/") && File.file?(path)

  from_public_dir(path) || from_asset_pipeline(path)
end

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

image_tagのsrcをローカルファイルパスへ差し替える。



46
47
48
# File 'lib/sghtmltopdf/view_helpers.rb', line 46

def sghtmltopdf_image_tag(source, options = {})
  image_tag(sghtmltopdf_asset_path(source) || source, options)
end

CSSの中身を<style>へ展開する。複数指定でき、見つからないものは 黙って飛ばす(PDF生成そのものは止めない)。



35
36
37
38
39
40
41
42
43
# File 'lib/sghtmltopdf/view_helpers.rb', line 35

def sghtmltopdf_stylesheet_link_tag(*sources)
  css = sources.flatten.filter_map do |source|
    path = sghtmltopdf_asset_path(with_extension(source, ".css"))
    File.read(path) if path
  end
  return "".html_safe if css.empty?

  (:style, css.join("\n").html_safe, type: "text/css")
end