Class: Goodcheck::Pattern

Inherits:
Object
  • Object
show all
Defined in:
lib/goodcheck/pattern.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source:, regexp:) ⇒ Pattern

Returns a new instance of Pattern.



6
7
8
9
# File 'lib/goodcheck/pattern.rb', line 6

def initialize(source:, regexp:)
  @source = source
  @regexp = regexp
end

Instance Attribute Details

#regexpObject (readonly)

Returns the value of attribute regexp.



4
5
6
# File 'lib/goodcheck/pattern.rb', line 4

def regexp
  @regexp
end

#sourceObject (readonly)

Returns the value of attribute source.



3
4
5
# File 'lib/goodcheck/pattern.rb', line 3

def source
  @source
end

Class Method Details

.compile_tokens(source) ⇒ Object



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
54
55
# File 'lib/goodcheck/pattern.rb', line 27

def self.compile_tokens(source)
  tokens = []
  s = StringScanner.new(source)

  until s.eos?
    case
    when s.scan(/\(|\)|\{|\}|\[|\]|\<|\>/)
      tokens << Regexp.escape(s.matched)
    when s.scan(/\s+/)
      tokens << '\s+'
    when s.scan(/(\p{Letter}|\w)+/)
      tokens << Regexp.escape(s.matched)
    when s.scan(%r{[!"#$%&'=\-^~¥\\|`@*:+;/?.,]+})
      tokens << Regexp.escape(s.matched.rstrip)
    when s.scan(/./)
      tokens << Regexp.escape(s.matched)
    end
  end

  if tokens.first =~ /\A\p{Letter}/
    tokens.first.prepend('\b')
  end

  if tokens.last =~ /\p{Letter}\Z/
    tokens.last << '\b'
  end

  Regexp.new(tokens.join('\s*').gsub(/\\s\*(\\s\+\\s\*)+/, '\s+'), Regexp::MULTILINE)
end

.literal(literal, case_insensitive:) ⇒ Object



11
12
13
# File 'lib/goodcheck/pattern.rb', line 11

def self.literal(literal, case_insensitive:)
  new(source: literal, regexp: Regexp.compile(Regexp.escape(literal), case_insensitive))
end

.regexp(regexp, case_insensitive:, multiline:) ⇒ Object



15
16
17
18
19
20
21
# File 'lib/goodcheck/pattern.rb', line 15

def self.regexp(regexp, case_insensitive:, multiline:)
  options = 0
  options |= Regexp::IGNORECASE if case_insensitive
  options |= Regexp::MULTILINE if multiline

  new(source: regexp, regexp: Regexp.compile(regexp, options))
end

.token(tokens) ⇒ Object



23
24
25
# File 'lib/goodcheck/pattern.rb', line 23

def self.token(tokens)
  new(source: tokens, regexp: compile_tokens(tokens))
end