Sha256: d2bdd48134e26ca57744b14fc7af2b620d51bf9de3397e971fd6599415667446

Contents?: true

Size: 1.28 KB

Versions: 5

Compression:

Stored size: 1.28 KB

Contents

module Turnip
  class Placeholder
    class Match < Struct.new(:regexp, :block);end

    class << self
      def add(name, &block)
        placeholders[name] = Placeholder.new(name, &block)
      end

      def resolve(name)
        find(name).regexp
      end

      def apply(name, value)
        find(name).apply(value)
      end

      def find(name)
        placeholders[name] or default
      end

    private

      def placeholders
        @placeholders ||= {}
      end

      def default
        @default ||= new(:default) do
          match %r((?:"([^"]*)"|'([^']*)'|([a-zA-Z0-9_-]+))) do |first, second, third|
            first or second or third
          end
        end
      end
    end

    def initialize(name, &block)
      @name = name
      @matches = []
      instance_eval(&block)
    end

    def apply(value)
      match, params = find_match(value)
      if match and match.block then match.block.call(*params) else value end
    end

    def match(regexp, &block)
      @matches << Match.new(regexp, block)
    end

    def regexp
      Regexp.new(@matches.map(&:regexp).join('|'))
    end

  private

    def find_match(value)
      @matches.each do |m|
        result = value.scan(m.regexp)
        return m, result.flatten unless result.empty?
      end
      nil
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
turnip-1.2.1 lib/turnip/placeholder.rb
turnip-1.2.0 lib/turnip/placeholder.rb
turnip-1.1.0 lib/turnip/placeholder.rb
turnip-1.0.0 lib/turnip/placeholder.rb
turnip-0.3.1 lib/turnip/placeholder.rb