class Archangel::Liquid::Tags::AssetTag

Asset custom tag for Liquid

Example

{% asset 'my-asset.png' %} #=>
  <img src="path/to/my-asset.png" alt="my-asset.png">
{% asset 'my-asset.png' size:'medium' %} #=>
  <img src="path/to/medium_my-asset.png" alt="my-asset.png">
{% asset 'my-asset.png' alt:'My image' class:'center' %} #=>
  <img src="path/to/my-asset.png" alt="My image" class="center">

Attributes

attributes[R]
key[R]
size[R]

Public Class Methods

new(tag_name, markup, options) click to toggle source

Asset for Liquid

@param tag_name [String] the Liquid tag name @param markup [String] the passed options @param options [Object] options

Calls superclass method
# File lib/archangel/liquid/tags/asset_tag.rb, line 27
def initialize(tag_name, markup, options)
  super

  match = ASSET_ATTRIBUTES_SYNTAX.match(markup)

  if match.blank?
    raise ::Liquid::SyntaxError, Archangel.t("errors.syntax.asset")
  end

  @key = ::Liquid::Variable.new(match[:asset], options).name
  @attributes = {}

  build_attributes(match[:attributes])
end

Public Instance Methods

render(context) click to toggle source

Render the Asset

@param context [Object] the Liquid context @return [String] the rendered Asset

# File lib/archangel/liquid/tags/asset_tag.rb, line 48
def render(context)
  return if key.blank?

  asset = load_asset_for(context["site"].object)

  return if asset.blank?

  asset_decider(asset)
end

Protected Instance Methods

asset_decider(asset) click to toggle source
# File lib/archangel/liquid/tags/asset_tag.rb, line 79
def asset_decider(asset)
  if %r{image/[gif|jpeg|png]}.match?(asset.content_type)
    image_asset(asset)
  else
    linked_asset(asset)
  end
end
build_attributes(attrs) click to toggle source
# File lib/archangel/liquid/tags/asset_tag.rb, line 62
def build_attributes(attrs)
  attrs.scan(KEY_VALUE_ATTRIBUTES_SYNTAX) do |key, value|
    @attributes[key.to_sym] = ::Liquid::Expression.parse(value)
  end

  size = attributes.fetch(:size, nil)

  @size = %w[small tiny].include?(size) ? size : nil
  @attributes.delete(:size)
end
image_asset(asset) click to toggle source
# File lib/archangel/liquid/tags/asset_tag.rb, line 87
def image_asset(asset)
  params = {
    alt: asset.file_name
  }.merge(attributes).merge(
    src: sized_image_asset(asset.file)
  ).compact.reject { |_, value| value.blank? }

  tag("img", params)
end
linked_asset(asset) click to toggle source
# File lib/archangel/liquid/tags/asset_tag.rb, line 97
def linked_asset(asset)
  options = attributes.compact.reject { |_, value| value.blank? }

  link_to(asset.file_name, asset.file.url, options)
end
load_asset_for(site) click to toggle source
# File lib/archangel/liquid/tags/asset_tag.rb, line 73
def load_asset_for(site)
  site.assets.find_by!(file_name: key)
rescue StandardError
  nil
end
sized_image_asset(file) click to toggle source
# File lib/archangel/liquid/tags/asset_tag.rb, line 103
def sized_image_asset(file)
  size.blank? ? file.url : file.send(size).url
end