class FMT

Attributes

errors[RW]

Public Class Methods

new(input, geo, callback) click to toggle source
# File mmdb-lookup, line 8
def initialize input, geo, callback
  @input = input; @geo = geo; @cb = method(callback)
  @errors = 0
end

Public Instance Methods

json() click to toggle source
# File mmdb-lookup, line 30
def json
  require 'json'
  trans = -> (ip) do
    r = {ip: ip}
    info = @geo.get ip
    info ? r.merge(info) : r.merge({error: @errors += 1})
  end

  if @input.is_a?(IO)      # stdin, in which we expect an apache log
    @input.each_line do |line|
      next if line =~ /^\s*$/
      @cb.call trans.call(line.split[0]).to_json
    end
  else                     # argv
    @input.map {|ip| @cb.call trans.call(ip).to_json }
  end
end
shell() click to toggle source
# File mmdb-lookup, line 14
def shell                     # print only the 1st entry
  require 'shellwords'
  ip = @input.to_enum.next.split.first
  r = ["ip=#{ip.shellescape}"]

  info = @geo.get ip
  if !info
    r << "error=#{@errors += 1}"
  else
    r += info.map do |k,v|
      "#{k}=#{(v.is_a?(Array) ? v.join(',') : v.to_s).shellescape}"
    end
  end
  @cb.call r.join "\n"
end