Module: BunBunBundle::Helpers

Includes:
SafeHtml
Defined in:
lib/bun_bun_bundle/helpers.rb

Overview

Asset helpers for use in views/templates.

Include this module in your view helpers to get access to ‘bun_asset` and tag helpers. Works with ERB, Haml, Slim, or any other templating engine.

Example (ERB):

<img src="<%= bun_asset("images/logo.png") %>">
<%= bun_js_tag("js/app.js") %>
<%= bun_css_tag("css/app.css") %>

Constant Summary collapse

FINGERPRINTED_CSS_REGEX =
/-[0-9a-f]{8}\.css$/

Instance Method Summary collapse

Instance Method Details

#bun_asset(path) ⇒ Object

Returns the public path to an asset from the manifest.

Prepends the configured public_path and asset_host:

bun_asset("js/app.js")       # => "/assets/js/app.js"
bun_asset("images/logo.png") # => "/assets/images/logo-abc123.png" (production)


27
28
29
# File 'lib/bun_bun_bundle/helpers.rb', line 27

def bun_asset(path)
  bun_asset_url(bun_entry(path))
end

#bun_css_tag(source, **options) ⇒ Object

Generates a <link> tag for a CSS entry point.

bun_css_tag("css/app.css")
# => '<link href="/assets/css/app.css" type="text/css" rel="stylesheet">'


50
51
52
53
54
55
56
57
# File 'lib/bun_bun_bundle/helpers.rb', line 50

def bun_css_tag(source, **options)
  entry = bun_entry(source)
  attrs = { type: 'text/css', rel: 'stylesheet' }
          .merge(bun_sri_attrs(entry))
          .merge(options)
          .merge(href: bun_href_with_timestamp(bun_asset_url(entry)))
  bun_safe(%(<link #{bun_html_attrs(attrs)}>))
end

#bun_img_tag(source, **options) ⇒ Object

Generates an <img> tag for an image asset.

Subresource Integrity is intentionally not rendered on images: browsers do not enforce SRI for <img> elements.

bun_img_tag("images/logo.png", alt: "Logo")
# => '<img src="/assets/images/logo.png" alt="Logo">'


67
68
69
70
71
72
# File 'lib/bun_bun_bundle/helpers.rb', line 67

def bun_img_tag(source, **options)
  src = bun_asset(source)
  alt = options.delete(:alt) || File.basename(source, '.*').tr('-_', ' ').capitalize
  attrs = { alt: alt }.merge(options).merge(src: src)
  bun_safe(%(<img #{bun_html_attrs(attrs)}>))
end

#bun_js_tag(source, **options) ⇒ Object

Generates a <script> tag for a JS entry point.

bun_js_tag("js/app.js")
# => '<script src="/assets/js/app.js" type="text/javascript"></script>'


36
37
38
39
40
41
42
43
# File 'lib/bun_bun_bundle/helpers.rb', line 36

def bun_js_tag(source, **options)
  entry = bun_entry(source)
  attrs = { type: 'text/javascript' }
          .merge(bun_sri_attrs(entry))
          .merge(options)
          .merge(src: bun_asset_url(entry))
  bun_safe(%(<script #{bun_html_attrs(attrs)}></script>))
end