Sha256: ebde7706846249d65d5a2888ab751055e2a3e4379a934370cbc27495dfd13b7d

Contents?: true

Size: 1.65 KB

Versions: 3

Compression:

Stored size: 1.65 KB

Contents

module Turnip
  class StepDefinition
    class Match < Struct.new(:step_definition, :params, :block)
      def expression; step_definition.expression; end
      def method_name; step_definition.method_name; end
      def called_from; step_definition.called_from; end

      def trace
        trace = %{  - "#{expression}" (#{called_from})}
      end
    end

    attr_reader :expression, :block, :method_name, :called_from

    def initialize(expression, method_name=nil, called_from=nil, &block)
      @expression = expression
      @method_name = method_name || expression
      @called_from = called_from
      @block = block
    end

    def regexp
      @regexp ||= compile_regexp
    end

    def match(description)
      result = description.match(regexp)
      if result
        params = result.captures
        @placeholder_names.each_with_index do |name, index|
          params[index] = Turnip::Placeholder.apply(name.to_sym, params[index])
        end
        Match.new(self, params, block)
      end
    end

  protected

    OPTIONAL_WORD_REGEXP = /(\\\s)?\\\(([^)]+)\\\)(\\\s)?/
    PLACEHOLDER_REGEXP = /:([\w]+)/
    ALTERNATIVE_WORD_REGEXP = /(\w+)((\/\w+)+)/

    def compile_regexp
      @placeholder_names = []
      regexp = Regexp.escape(expression)
      regexp.gsub!(PLACEHOLDER_REGEXP) do |_|
        @placeholder_names << "#{$1}"
        "(?<#{$1}>#{Placeholder.resolve($1.to_sym)})"
      end
      regexp.gsub!(OPTIONAL_WORD_REGEXP) do |_|
        [$1, $2, $3].compact.map { |m| "(?:#{m})?" }.join
      end
      regexp.gsub!(ALTERNATIVE_WORD_REGEXP) do |_|
        "(?:#{$1}#{$2.tr('/', '|')})"
      end
      Regexp.new("^#{regexp}$")
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
turnip-1.2.1 lib/turnip/step_definition.rb
turnip-1.2.0 lib/turnip/step_definition.rb
turnip-1.1.0 lib/turnip/step_definition.rb