Class: Rubulex::RegexpParser

Inherits:
Object
  • Object
show all
Defined in:
lib/rubulex/regexp_parser.rb

Instance Method Summary collapse

Constructor Details

#initialize(regex, options, data) ⇒ RegexpParser

Returns a new instance of RegexpParser.



5
6
7
8
9
10
11
12
13
# File 'lib/rubulex/regexp_parser.rb', line 5

def initialize(regex, options, data)
  self.options = options
  self.regex = regex
  self.data = data
  @match_result = nil
  @match_groups = nil

  parse
end

Instance Method Details

#data=(data) ⇒ Object



15
16
17
# File 'lib/rubulex/regexp_parser.rb', line 15

def data=(data)
  @data = data[0..4095] || ""
end

#options=(options) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/rubulex/regexp_parser.rb', line 25

def options=(options)
  options = options.match(/(?<options>(?<option>[imxo]){,4})/)[:options].split(//)

  options_lookup_table = Hash.new(0)
  options_lookup_table["i"] = Regexp::IGNORECASE
  options_lookup_table["m"] = Regexp::MULTILINE
  options_lookup_table["x"] = Regexp::EXTENDED

  @options = options.inject(0) do |result, option|
    result | options_lookup_table[option]
  end
end

#parseObject



38
39
40
41
42
43
# File 'lib/rubulex/regexp_parser.rb', line 38

def parse
  @data.match(@regex) do |match|
    @match_result = render_match_result(@data.dup)
    @match_groups = render_match_groups(@data.dup)
  end
end

#regex=(regex) ⇒ Object



19
20
21
22
23
# File 'lib/rubulex/regexp_parser.rb', line 19

def regex=(regex)
  @regex = Regexp.new(regex, @options)
rescue RegexpError => error
  @regex = //
end

#render_match_groups(data) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/rubulex/regexp_parser.rb', line 56

def render_match_groups(data)
  match_groups = []

  matches = data.to_enum(:scan, @regex).map { Regexp.last_match }
  matches.each do |match_data|
    sub_match_set = []
    match_data.captures.each_with_index do |match_text, i|
      sub_match_set << Struct::MatchRelation.new(i+1, match_text)
    end
      match_groups << sub_match_set
  end

  match_groups.map.with_index { |sub_set, index|
    group = "<dl><dt>Match #{h(index + 1)}</dt>"
    group << sub_set.map { |match|
      "<dd>#{h(match.name)}: #{h(match.text)}</dd>"
    }.join
    group << "</dl>"
  }.join("<br />")
end

#render_match_result(data) ⇒ Object



45
46
47
48
49
50
51
52
53
54
# File 'lib/rubulex/regexp_parser.rb', line 45

def render_match_result(data)
  colors = ->() do
    (@colors ||= [:red, :green, :darkorange, :blue].cycle).next
  end
  data.gsub!(@regex) do |match|
    "<span class='#{h(colors.call)}'>#{h(match)}</span>"
  end

  data.gsub(/\n/,"<br />")
end

#resultObject



77
78
79
80
81
82
# File 'lib/rubulex/regexp_parser.rb', line 77

def result
  {
    match_result: @match_result,
    match_groups: @match_groups
  }
end