wiki:ExampleUsage
Last modified 6 years ago Last modified on 09/11/05 06:49:58

Example OOParser Usage

Define a Parser Class

require 'ooparser'
require 'time'

class CommonLogParser < OOParser

    LogLine = Struct::new( :ip, :username, :time, :request, :status, :size )

    # 66.195.186.130 - - [11/Sep/2005:05:08:27 -0700] \
    #   "POST /projects/OOParser/wiki/ExampleUsage HTTP/1.1" 200 7138
    grammar {
        def_rule :logfile, "<common_log_line>*" do |match|
            return match[:common_log_lines]
        end
        
        def_rule :common_log_line, 
          '<ip> <rfc1413> <authuser> [<time>] "<request>" <status> <size>' do |match|
            vals = match.values_at(:ip, :authuser, :time, :request, :status, :size)
            return LogLine::new( *vals )
        end

        def_rule :rfc1413, "<username>"
        def_rule :authuser, "<username>"
        
        # [11/Sep/2005:05:08:27 -0700]
        # [day/month/year:hour:minute:second zone]
        def_rule :time,
          "<day> / <month> / <year> : <hour> : <minute> : <second> <zone>" do |match|
            Time::parse( match[0] )
        end

        def_rule :request, "<method> <uri> <httpversion>" do |match|
            return match.make_hash( :method, :uri, :httpversion )
        end

        # Terminals     
        def_rule :ip, /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/

        def_rule :username, /(\w+|-)/ do |match|
            match[1] == '-' ? nil : match[1]
        end

        def_rule :day, /\d{2}/
        def_rule :month, /(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)/
        def_rule :year, /\d{4}/
        def_rule :hour, /\d{2}/
        def_rule :minute, /\d{2}/
        def_rule :second, /\d{2}/
        
        def_rule :zone, /(+|-)\d{4}/

    }
end