/
step_definition.rb
53 lines (46 loc) · 1.35 KB
/
step_definition.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
module Turnip
class StepDefinition
class Match < Struct.new(:step_definition, :params, :block)
def expression; step_definition.expression; end
end
attr_reader :expression, :block
def initialize(expression, &block)
@expression = expression
@block = block
end
def regexp
@regexp ||= compile_regexp
end
def match(description)
result = description.match(regexp)
if result
params = result.captures
result.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+)+)/
COMMAND_REGEXP = /`([^`]+)`/
def compile_regexp
regexp = Regexp.escape(expression)
regexp.gsub!(COMMAND_REGEXP) do |_|
"(?:[`]([^`]+)[`])"
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.gsub!(PLACEHOLDER_REGEXP) do |_|
"(?<#{$1}>#{Placeholder.resolve($1.to_sym)})"
end
Regexp.new("^#{regexp}$")
end
end
end