Module: Wildmat

Defined in:
lib/wildmat.rb

Constant Summary collapse

VERSION =
'0.9.0'

Class Method Summary collapse

Class Method Details

.backslash(pattern, i, current) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/wildmat.rb', line 34

def self.backslash(pattern, i, current)
  # TODO: raise error? if we reach the end of the pattern
  # in a backslash context
  # return ??? if i > pattern.size
  next_char = pattern[i].chr
  case next_char
  when /\w/
    current << next_char
  else
    current << '\\' << next_char
  end
  literal(pattern, i+1, current)
end

.character_class(pattern, i, current, first = false, assertion = true) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/wildmat.rb', line 52

def self.character_class(pattern, i, current, first=false, assertion=true)
  # TODO: raise error? if we reach the end of the pattern
  # in a character class context
  # return ??? if i > pattern.size
  next_char = pattern[i].chr
  case next_char
  when ']'
    current << (first ? '\\]' : ']')
    return literal(pattern, i+1, current) unless first
  when '^'
    current << next_char
    return character_class(pattern, i+1, current, true, false) if first && assertion
  else
    current << next_char
  end
  character_class(pattern, i+1, current)
end

.first_character_class(pattern, i, current) ⇒ Object



48
49
50
# File 'lib/wildmat.rb', line 48

def self.first_character_class(pattern, i, current)
  character_class(pattern, i, current, true)
end

.literal(pattern, i, current) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/wildmat.rb', line 15

def self.literal(pattern, i, current)
  return current if i >= pattern.size
  next_char = pattern[i].chr
  case next_char
  when '*'
    current << '.*'
  when '?'
    current << '.'
  when '\\'
    return backslash(pattern, i+1, current)
  when '['
    current << '['
    return first_character_class(pattern, i+1, current)
  else
    current << Regexp.escape(next_char)
  end
  literal(pattern, i+1, current)
end

.regexp_pattern(pattern) ⇒ Object



9
10
11
12
13
# File 'lib/wildmat.rb', line 9

def self.regexp_pattern(pattern)
  # * ? [ \ are treated specially
  # all other non-alphanumeric will be escaped
  literal(pattern, 0, '')
end

.to_regexp(pattern) ⇒ Object



5
6
7
# File 'lib/wildmat.rb', line 5

def self.to_regexp(pattern)
  %r(^#{regexp_pattern(pattern)}$)
end