Sha256: 03dbafceeb35cf728935775a595199d55fb7a2cf5862e89a623c9082c429f71e

Contents?: true

Size: 1.35 KB

Versions: 77

Compression:

Stored size: 1.35 KB

Contents

module Utils
  module Patterns
    class Pattern
      def initialize(opts = {})
        @cset    = opts[:cset]
        @icase   = opts[:icase]
        @pattern = opts[:pattern] or
          raise ArgumentError, "pattern option required"
        @pattern = @pattern.gsub(/[^#{@cset}]/, '') if @cset
      end

      attr_reader :matcher

      def method_missing(*a, &b)
        @matcher.__send__(*a, &b)
      rescue ArgumentError => e
        raise e unless e.message.include?('invalid byte sequence in UTF-8')
      end
    end

    class FuzzyPattern < Pattern
      def initialize(opts = {})
        super
        r = @pattern.split(//).grep(/[[:print:]]/).map { |x|
          "(#{Regexp.quote(x)})"
        } * '.*?'
        @matcher = Regexp.new(
          "\\A(?:.*/.*?#{r}|.*#{r})",
          @icase ? Regexp::IGNORECASE : 0)
      end
    end

    class RegexpPattern < Pattern
      def initialize(opts = {})
        super
        @matcher = Regexp.new(@pattern, @icase ? Regexp::IGNORECASE : 0)
      end
    end

    def choose(argument, pattern_opts, default: ?f)
      case argument
      when /^r/, (default == ?r ? nil : :not)
        RegexpPattern.new(pattern_opts)
      when /^f/, (default == ?f ? nil : :not)
        FuzzyPattern.new(pattern_opts)
      else
        raise ArgumentError, 'argument -p has to be f=fuzzy or r=regexp'
      end
    end
  end
end

Version data entries

77 entries across 77 versions & 1 rubygems

Version Path
utils-0.60.1 lib/utils/patterns.rb
utils-0.60.0 lib/utils/patterns.rb
utils-0.59.2 lib/utils/patterns.rb
utils-0.59.1 lib/utils/patterns.rb
utils-0.59.0 lib/utils/patterns.rb
utils-0.58.0 lib/utils/patterns.rb
utils-0.57.1 lib/utils/patterns.rb
utils-0.57.0 lib/utils/patterns.rb
utils-0.56.1 lib/utils/patterns.rb
utils-0.56.0 lib/utils/patterns.rb
utils-0.55.0 lib/utils/patterns.rb
utils-0.54.1 lib/utils/patterns.rb
utils-0.54.0 lib/utils/patterns.rb
utils-0.53.1 lib/utils/patterns.rb
utils-0.53.0 lib/utils/patterns.rb
utils-0.52.1 lib/utils/patterns.rb
utils-0.52.0 lib/utils/patterns.rb
utils-0.51.1 lib/utils/patterns.rb
utils-0.51.0 lib/utils/patterns.rb
utils-0.50.0 lib/utils/patterns.rb