Class: LogParser::Template

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(pattern) ⇒ Template

Returns a new instance of Template.



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

def initialize(pattern)
  build_regexp(pattern)
end

Instance Attribute Details

#fieldsObject (readonly)

Returns the value of attribute fields.



3
4
5
# File 'lib/logparser/template.rb', line 3

def fields
  @fields
end

#regexpObject (readonly)

Returns the value of attribute regexp.



3
4
5
# File 'lib/logparser/template.rb', line 3

def regexp
  @regexp
end

Instance Method Details

#apply(str) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
# File 'lib/logparser/template.rb', line 17

def apply(str)
  if matches = str.match(@regexp)
    hash = {}
    @fields.each_with_index do |key, i|
      hash[key] = matches[i+1]
    end
    return hash
  else
    return nil
  end
end

#build_regexp(pattern) ⇒ Object



9
10
11
12
13
14
15
# File 'lib/logparser/template.rb', line 9

def build_regexp(pattern)
  @fields = []
  @regexp = Regexp.new("\\A" << Regexp.escape(pattern).gsub(/:([a-z_][a-z0-9_]*)/){
    @fields << $1.to_sym
    "(.*?)"
  } << "\\Z" )
end