Module: WickedPdf::AssetHelper

Defined in:
lib/wicked_pdf/asset_helper.rb

Constant Summary collapse

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

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.add_extension(filename, extension) ⇒ Object



11
12
13
# File 'lib/wicked_pdf/asset_helper.rb', line 11

def self.add_extension(filename, extension)
  filename.to_s.split('.').include?(extension) ? filename : "#{filename}.#{extension}"
end

.root_pathObject



7
8
9
# File 'lib/wicked_pdf/asset_helper.rb', line 7

def self.root_path
  String === Rails.root ? Pathname.new(Rails.root) : Rails.root
end

Instance Method Details

#wicked_pdf_asset_base64(path) ⇒ Object



15
16
17
18
19
20
21
22
23
# File 'lib/wicked_pdf/asset_helper.rb', line 15

def wicked_pdf_asset_base64(path)
  wicked_pdf_asset_cache(:base64, path) do
    asset = find_asset(path)
    raise "Could not find asset '#{path}'" if asset.nil?

    base64 = Base64.encode64(asset.to_s).gsub(/\s+/, '')
    "data:#{asset.content_type};base64,#{Rack::Utils.escape(base64)}"
  end
end

#wicked_pdf_asset_path(asset) ⇒ Object



60
61
62
63
64
65
66
# File 'lib/wicked_pdf/asset_helper.rb', line 60

def wicked_pdf_asset_path(asset)
  if (pathname = asset_pathname(asset).to_s) =~ URI_REGEXP
    pathname
  else
    "file:///#{pathname}"
  end
end

#wicked_pdf_image_tag(img, options = {}) ⇒ Object



42
43
44
# File 'lib/wicked_pdf/asset_helper.rb', line 42

def wicked_pdf_image_tag(img, options = {})
  image_tag wicked_pdf_asset_path(img), options
end

#wicked_pdf_javascript_include_tag(*sources) ⇒ Object



51
52
53
54
55
56
57
58
# File 'lib/wicked_pdf/asset_helper.rb', line 51

def wicked_pdf_javascript_include_tag(*sources)
  wicked_pdf_asset_cache(:javascript, *sources) do
    sources.collect do |source|
      source = WickedPdf::AssetHelper.add_extension(source, 'js')
      "<script type='text/javascript'>#{read_asset(source)}</script>"
    end.join("\n").html_safe
  end
end

#wicked_pdf_javascript_src_tag(jsfile, options = {}) ⇒ Object



46
47
48
49
# File 'lib/wicked_pdf/asset_helper.rb', line 46

def wicked_pdf_javascript_src_tag(jsfile, options = {})
  jsfile = WickedPdf::AssetHelper.add_extension(jsfile, 'js')
  javascript_include_tag wicked_pdf_asset_path(jsfile), options
end


25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/wicked_pdf/asset_helper.rb', line 25

def wicked_pdf_stylesheet_link_tag(*sources)
  wicked_pdf_asset_cache(:stylesheet, *sources) do
    stylesheet_contents = sources.collect do |source|
      source = WickedPdf::AssetHelper.add_extension(source, 'css')
      "<style type='text/css'>#{read_asset(source)}</style>"
    end.join("\n")

    stylesheet_contents.gsub(ASSET_URL_REGEX) do
      if Regexp.last_match[1].starts_with?('data:')
        "url(#{Regexp.last_match[1]})"
      else
        "url(#{wicked_pdf_asset_path(Regexp.last_match[1])})"
      end
    end.html_safe
  end
end