Class: RegexpPreview

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file, format, options = {}) ⇒ RegexpPreview

Returns a new instance of RegexpPreview.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/regexp_preview.rb', line 9

def initialize(file, format, options = {})
  @file = file
  @format = format
  case format
  when "regexp"
    @regexp = Regexp.new(options[:regexp])
    @time_format = options[:time_format]
  when "ltsv", "json", "csv", "tsv"
  else
    definition = Fluent::TextParser::TEMPLATE_REGISTRY.lookup(format).call
    raise "Unknown format '#{format}'" unless definition
    definition.configure({}) # NOTE: SyslogParser define @regexp in configure method so call it to grab Regexp object
    @regexp = definition.patterns["format"]
    @time_format = definition.patterns["time_format"]
  end
end

Instance Attribute Details

#fileObject (readonly)

Returns the value of attribute file.



7
8
9
# File 'lib/regexp_preview.rb', line 7

def file
  @file
end

#formatObject (readonly)

Returns the value of attribute format.



7
8
9
# File 'lib/regexp_preview.rb', line 7

def format
  @format
end

#regexpObject (readonly)

Returns the value of attribute regexp.



7
8
9
# File 'lib/regexp_preview.rb', line 7

def regexp
  @regexp
end

#time_formatObject (readonly)

Returns the value of attribute time_format.



7
8
9
# File 'lib/regexp_preview.rb', line 7

def time_format
  @time_format
end

Instance Method Details

#matchesObject



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/regexp_preview.rb', line 26

def matches
  return [] unless @regexp # such as ltsv, json, etc
  reader = FileReverseReader.new(File.open(file))
  matches = reader.tail.map do |line|
    result = {
      :whole => line,
      :matches => [],
    }
    m = line.match(regexp)
    next result unless m

    m.names.each_with_index do |name, index|
      result[:matches] << {
        key: name,
        matched: m[name],
        pos: m.offset(index + 1),
      }
    end
    result
  end
  matches
end