Method: Regexp::Template#preview

Defined in:
lib/core_ext/regexp.rb

#preview(parent_type = nil) ⇒ Object


88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/core_ext/regexp.rb', line 88

def preview(parent_type=nil)
  numbering = @atoms.map.with_index do |a, index|
    atom_text = render_atom(a)
    # source = @rx.source.gsub(atom_text, atom_text+"|")
    # spacer_count = (atom_text+"|").length/2
    spacer_count = (atom_text).length/2
    "#{" "*(spacer_count-1)}##{index}#{" "*(spacer_count)}"
  end
  @terminal = Terminal.new()
  @terminal.clear_terminal
  rx_source = @rx.source
  descriptions = []
  if(!parent_type)
    @atoms.map.with_index do |a,index|
      if(a.is_a?(Array) && a[0] == :"(" && a[a.length-1] == :")")
        stringified = a.map(&:to_s).join('')
        rx_source = rx_source.gsub(stringified,@terminal.rbg(r:0,b:0,g:5, text:stringified))
        subatoms = a[1,a.length-2]
        if(subatoms[0].to_s.start_with?("?<"))
          name = subatoms.shift
          name = name.to_s.match(/\?\<(?<name>.*)\>/)[:name]
          name = "#{name}"
        else
          name = "anonymous_capture_group"
        end
        if(subatoms.length == 1)
          a =  "#{@terminal.rbg(r:0,b:0,g:5, text:"Capture group \"#{name}\"")} captures #{self.describe(subatoms.first)}"
        elsif(subatoms.length == 2)
          a =    "#{@terminal.rbg(r:0,b:0,g:5, text:"Capture group \"#{name}\"")} captures #{self.describe(subatoms[0])} and #{self.describe(subatoms[0])}"
        else
          subatoms = subatoms.map{|s| self.describe(s)}
          last_subatom = subatoms.pop
        a =    "#{@terminal.rbg(r:0,b:0,g:5, text:"Capture group \"#{name}\"")} captures #{subatoms.join(',')} and #{last_subatom}"
        end
      else
        rx_source = rx_source.gsub(a.to_s,@terminal.rbg(r:0,b:5,g:1, text:a.to_s))
        a =  "#{@terminal.rbg(r:0,b:5,g:1, text:"\"#{a}\"")} matches #{self.describe(a)}"
      end
      descriptions << "##{index}. #{a}"
    end
  elsif(parent_type == :capture)
    @atoms.map do |a|
      if(a.to_s.include?("literal_"))
        "#{a.to_s.gsub("_"," ")}"
      elsif(a.to_s[0] == "(" && a.to_s[a.length-1] == ")")
        "#{self.preview(a.to_s[1,a.length-1],:capture)}"
      elsif(a.to_s[0] == "\\" && matchers.keys.include?(a.to_s[1]))
        "#{matchers[a]}"
      elsif(a.to_s[0] == "\\" && a.length <= 3 && !matchers.keys.include?(a.to_s[1]))
        "literal #{a}"
      else
        "#{a}"
      end
    end
  end
  indent = 1
  indent_str = "\t"*indent
  puts "\n"*2
  puts "#{indent_str}#{rx_source}"
  puts "#{indent_str}#{@terminal.add_formatting(numbering.join(''), :yellow)}"
  descriptions.each{|desc| puts "#{indent_str}#{desc}" }
  return
end