Sha256: b65a55fe9e5e350a5ccf027f043893336137f518d433e29885765d35c6ed5880

Contents?: true

Size: 1.76 KB

Versions: 11

Compression:

Stored size: 1.76 KB

Contents

# frozen_string_literal: true

module Nanoc::Int
  # @api private
  class Pattern
    include Nanoc::Int::ContractsSupport

    contract C::Any => self
    def self.from(obj)
      case obj
      when Nanoc::Int::StringPattern, Nanoc::Int::RegexpPattern
        obj
      when String
        Nanoc::Int::StringPattern.new(obj)
      when Regexp
        Nanoc::Int::RegexpPattern.new(obj)
      else
        raise ArgumentError, "Do not know how to convert `#{obj.inspect}` into a Nanoc::Pattern"
      end
    end

    def initialize(_obj)
      raise NotImplementedError
    end

    def match?(_identifier)
      raise NotImplementedError
    end

    def captures(_identifier)
      raise NotImplementedError
    end
  end

  # @api private
  class StringPattern < Pattern
    MATCH_OPTS = File::FNM_PATHNAME | File::FNM_EXTGLOB

    contract String => C::Any
    def initialize(string)
      @string = string
    end

    contract C::Or[Nanoc::Identifier, String] => C::Bool
    def match?(identifier)
      File.fnmatch(@string, identifier.to_s, MATCH_OPTS)
    end

    contract C::Or[Nanoc::Identifier, String] => nil
    def captures(_identifier)
      nil
    end

    contract C::None => String
    def to_s
      @string
    end
  end

  # @api private
  class RegexpPattern < Pattern
    contract Regexp => C::Any
    def initialize(regexp)
      @regexp = regexp
    end

    contract C::Or[Nanoc::Identifier, String] => C::Bool
    def match?(identifier)
      (identifier.to_s =~ @regexp) != nil
    end

    contract C::Or[Nanoc::Identifier, String] => C::Maybe[C::ArrayOf[String]]
    def captures(identifier)
      matches = @regexp.match(identifier.to_s)
      matches && matches.captures
    end

    contract C::None => String
    def to_s
      @regexp.to_s
    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
nanoc-4.8.5 lib/nanoc/base/entities/pattern.rb
nanoc-4.8.4 lib/nanoc/base/entities/pattern.rb
nanoc-4.8.3 lib/nanoc/base/entities/pattern.rb
nanoc-4.8.2 lib/nanoc/base/entities/pattern.rb
nanoc-4.8.1 lib/nanoc/base/entities/pattern.rb
nanoc-4.8.0 lib/nanoc/base/entities/pattern.rb
nanoc-4.7.14 lib/nanoc/base/entities/pattern.rb
nanoc-4.7.13 lib/nanoc/base/entities/pattern.rb
nanoc-4.7.12 lib/nanoc/base/entities/pattern.rb
nanoc-4.7.11 lib/nanoc/base/entities/pattern.rb
nanoc-4.7.10 lib/nanoc/base/entities/pattern.rb