Sha256: dc5182ff8de70d8f23c4fb196601a62cc5266f0ca2d6c81a97af4d02822ed556

Contents?: true

Size: 1.63 KB

Versions: 3

Compression:

Stored size: 1.63 KB

Contents

module PictureTag
  module Instructions
    # This class takes in the arguments passed to the liquid tag, and splits it
    # up into 'words' (correctly handling quotes and backslash escapes.)
    #
    # To handle quotes and backslash escaping, we have to parse the string by
    # characters to break it up correctly. I'm sure there's a library to do
    # this, but it's not that much code honestly. If this starts getting big,
    # we'll pull in a new dependency.
    #
    class ArgSplitter
      attr_reader :words

      def initialize(raw_params)
        @words = []
        @word = ''
        @in_quotes = false
        @escaped = false

        raw_params.each_char { |c| handle_char(c) }

        add_word # We have to explicitly add the last one.
      end

      private

      def handle_char(char)
        # last character was a backslash:
        if @escaped
          close_escape char

        # char is a backslash or a quote:
        elsif char.match?(/["\\]/)
          handle_special char

        # Character isn't whitespace, or it's inside double quotes:
        elsif @in_quotes || char.match(/\S/)
          @word << char

        # Character is whitespace outside of double quotes:
        else
          add_word
        end
      end

      def add_word
        return if @word.empty?

        @words << @word
        @word = ''
      end

      def handle_special(char)
        if char == '\\'
          @escaped = true
        elsif char == '"'
          @in_quotes = !@in_quotes
          @word << char
        end
      end

      def close_escape(char)
        @word << char
        @escaped = false
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
jekyll_picture_tag-1.10.2 lib/jekyll_picture_tag/instructions/arg_splitter.rb
jekyll_picture_tag-1.10.1 lib/jekyll_picture_tag/instructions/arg_splitter.rb
jekyll_picture_tag-1.10.0 lib/jekyll_picture_tag/instructions/arg_splitter.rb