Sha256: c6d531f13136daa729c94b6f7780b2fb23cd2bee77bc0afc690db2774062a1ef

Contents?: true

Size: 880 Bytes

Versions: 1

Compression:

Stored size: 880 Bytes

Contents

require_relative "initialize_with_redis"
require 'ipaddr'

class Trifle
  class Finder
    include InitializeWithRedis

    def handle ip
      ip_i = IPAddr.new(ip).native.to_i
      find(ip_i, 0, max)
    rescue ArgumentError => ex
      nil
    end

    protected

    def find ip_i, lower, upper
      index = (lower+upper)/2
      current = entry_for(index)

      if in_range(current, ip_i)
        current.last(2)
      elsif lower >= upper
        nil
      elsif ip_i < current[0]
        find ip_i, lower, index-1
      else
        find ip_i, index+1, upper
      end
    end

    def max
      redis.llen(key)-1
    end

    def entry_for index
      entry = redis.lindex(key, index).split(":")
      entry[0] = entry[0].to_i
      entry[1] = entry[1].to_i
      entry
    end

    def in_range range, ip_i
      range[0] <= ip_i && ip_i <= range[1]
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
trifle-0.0.9 lib/trifle/finder.rb