Sha256: ffcef42007ea6440f64860b61dcf4b34aa786283f30fd899cac3315937c2ad19

Contents?: true

Size: 1.6 KB

Versions: 10

Compression:

Stored size: 1.6 KB

Contents

module PictureTag
  module Instructions
    # Handles HTML attributes, sourced from configuration and the liquid tag,
    # sent to various elements.
    # Stored as a hash, with string keys.
    class HTMLAttributeSet
      # Initialize with leftovers passed into the liquid tag. These leftovers
      # (params) take the form of an array of strings, called words, which the
      # tag parser has separated.
      def initialize(params)
        @attributes = load_preset

        parse_params(params) if params
        handle_source_url
      end

      def [](key)
        @attributes[key]
      end

      private

      def load_preset
        # Shamelessly stolen from stackoverflow. Deep cloning a hash is
        # surprisingly tricky! I could pull in ActiveSupport and get
        # Hash#deep_dup, but for now I don't think it's necessary.

        Marshal.load(Marshal.dump(PictureTag.preset['attributes'])) || {}
      end

      # Syntax this function processes:
      # class="old way" --picture class="new way" --alt Here's my alt text
      def parse_params(words)
        key = 'implicit'

        words.each do |word|
          if word.match(/^--/)
            key = word.delete_prefix('--')
          elsif @attributes[key]
            @attributes[key] << ' ' + word
          else
            @attributes[key] = word
          end
        end
      end

      def handle_source_url
        return unless PictureTag.preset['link_source'] && self['link'].nil?

        target = PictureTag.source_images.first.shortname

        @attributes['link'] = ImgURI.new(target, source_image: true).to_s
      end
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
jekyll_picture_tag-1.14.0 lib/jekyll_picture_tag/instructions/html_attributes.rb
jekyll_picture_tag-1.13.0 lib/jekyll_picture_tag/instructions/html_attributes.rb
jekyll_picture_tag-1.12.0 lib/jekyll_picture_tag/instructions/html_attributes.rb
jekyll_picture_tag-1.11.0 lib/jekyll_picture_tag/instructions/html_attributes.rb
jekyll_picture_tag-1.10.2 lib/jekyll_picture_tag/instructions/html_attributes.rb
jekyll_picture_tag-1.10.1 lib/jekyll_picture_tag/instructions/html_attributes.rb
jekyll_picture_tag-1.10.0 lib/jekyll_picture_tag/instructions/html_attributes.rb
jekyll_picture_tag-1.9.0 lib/jekyll_picture_tag/instructions/html_attributes.rb
jekyll_picture_tag-1.8.0 lib/jekyll_picture_tag/instructions/html_attributes.rb
jekyll_picture_tag-1.7.1 lib/jekyll_picture_tag/instructions/html_attributes.rb