Sha256: 2026f6b9d4231be9ad1a9b890749d9622c8dd1697f74c14eba795bafea20150d

Contents?: true

Size: 1.66 KB

Versions: 31

Compression:

Stored size: 1.66 KB

Contents

# frozen_string_literal: true

module Nanoc
  module Extra
    # @api private
    class SrcsetParser
      class InvalidFormat < ::Nanoc::Core::Error
        def initialize
          super('Invalid srcset format')
        end
      end

      REGEX_REST =
        /
          (               # Zero or one of the following:
            (             #   A width descriptor, consisting of:
              \s+         #     ASCII whitespace
              \d+         #     a valid non-negative integer
              w           #     a U+0077 LATIN SMALL LETTER W character
            )
            |
            (             #   A pixel density descriptor, consisting of
              \s+         #     ASCII whitespace
              (\d*\.)?\d+ #     a valid floating-point number
              x           #     and a U+0078 LATIN SMALL LETTER X character.
            )
          )*
        /x.freeze

      def initialize(value)
        @value = value
      end

      def call
        matches = []

        loop do
          match = {}

          scan(/\s*/)
          match[:url] = scan(/[^, ]+/)
          match[:rest] = scan(REGEX_REST)
          scan(/\s*/)

          matches << match

          next if try_scan(/,/)
          break if eos?

          raise(InvalidFormat)
        end

        matches
      rescue InvalidFormat
        @value
      end

      private

      def scan(pattern)
        match = try_scan(pattern)

        match || raise(InvalidFormat)
      end

      def try_scan(pattern)
        scanner.scan(pattern)
      end

      def eos?
        scanner.eos?
      end

      def scanner
        @_scanner ||= StringScanner.new(@value)
      end
    end
  end
end

Version data entries

31 entries across 31 versions & 1 rubygems

Version Path
nanoc-4.12.21 lib/nanoc/extra/srcset_parser.rb
nanoc-4.12.20 lib/nanoc/extra/srcset_parser.rb
nanoc-4.12.19 lib/nanoc/extra/srcset_parser.rb
nanoc-4.12.18 lib/nanoc/extra/srcset_parser.rb
nanoc-4.12.17 lib/nanoc/extra/srcset_parser.rb
nanoc-4.12.16 lib/nanoc/extra/srcset_parser.rb
nanoc-4.12.15 lib/nanoc/extra/srcset_parser.rb
nanoc-4.12.14 lib/nanoc/extra/srcset_parser.rb
nanoc-4.12.13 lib/nanoc/extra/srcset_parser.rb
nanoc-4.12.12 lib/nanoc/extra/srcset_parser.rb
nanoc-4.12.11 lib/nanoc/extra/srcset_parser.rb
nanoc-4.12.10 lib/nanoc/extra/srcset_parser.rb
nanoc-4.12.9 lib/nanoc/extra/srcset_parser.rb
nanoc-4.12.8 lib/nanoc/extra/srcset_parser.rb
nanoc-4.12.7 lib/nanoc/extra/srcset_parser.rb
nanoc-4.12.6 lib/nanoc/extra/srcset_parser.rb
nanoc-4.12.5 lib/nanoc/extra/srcset_parser.rb
nanoc-4.12.4 lib/nanoc/extra/srcset_parser.rb
nanoc-4.12.3 lib/nanoc/extra/srcset_parser.rb
nanoc-4.12.2 lib/nanoc/extra/srcset_parser.rb