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.21.2 lib/utils/patterns.rb
utils-0.21.1 lib/utils/patterns.rb
utils-0.21.0 lib/utils/patterns.rb
utils-0.20.0 lib/utils/patterns.rb
utils-0.19.0 lib/utils/patterns.rb
utils-0.18.1 lib/utils/patterns.rb
utils-0.18.0 lib/utils/patterns.rb
utils-0.17.0 lib/utils/patterns.rb
utils-0.16.0 lib/utils/patterns.rb
utils-0.15.1 lib/utils/patterns.rb
utils-0.15.0 lib/utils/patterns.rb
utils-0.14.0 lib/utils/patterns.rb
utils-0.13.0 lib/utils/patterns.rb
utils-0.12.0 lib/utils/patterns.rb
utils-0.11.0 lib/utils/patterns.rb
utils-0.10.1 lib/utils/patterns.rb
utils-0.10.0 lib/utils/patterns.rb