Sha256: 520c9cab0b205d85d37c9c7419cf1d1ddf164aeaa0505091f20a9f586fb838ca

Contents?: true

Size: 1.27 KB

Versions: 4

Compression:

Stored size: 1.27 KB

Contents

# frozen_string_literal: true

require 'singleton'

module Metka
  ##
  # Returns a new Metka::TagList using the given tag string.
  #
  # Example:
  # tag_list = Metka::GenericParser.instance.("One , Two, Three")
  # tag_list # ["One", "Two", "Three"]
  class GenericParser
    include Singleton

    def call(value)
      TagList.new.tap do |tag_list|
        case value
        when String
          value = value.to_s.dup
          gsub_quote_pattern!(tag_list, value, double_quote_pattern)
          gsub_quote_pattern!(tag_list, value, single_quote_pattern)

          tag_list.merge value.split(Regexp.new joined_delimiter).map(&:strip).reject(&:empty?)
        when Enumerable
          tag_list.merge value.reject(&:empty?)
        end
      end
    end

    private

    def gsub_quote_pattern!(tag_list, value, pattern)
      value.gsub!(pattern) {
        tag_list.add(Regexp.last_match[2])
        ''
      }
    end

    def joined_delimiter
      delimeter = Metka.config.delimiter
      delimeter.is_a?(Array) ? delimeter.join('|') : delimeter
    end

    def single_quote_pattern
      /(\A|#{joined_delimiter})\s*'(.*?)'\s*(?=#{joined_delimiter}\s*|\z)/
    end

    def double_quote_pattern
      /(\A|#{joined_delimiter})\s*"(.*?)"\s*(?=#{joined_delimiter}\s*|\z)/
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
metka-1.0.3 lib/metka/generic_parser.rb
metka-1.0.2 lib/metka/generic_parser.rb
metka-1.0.1 lib/metka/generic_parser.rb
metka-1.0.0 lib/metka/generic_parser.rb