Storing an IP address as an integer

You may want to store an IP address in your database as an integer to save space and increase lookup speed.

You can use IPAddr to convert it to and from an integer.

class Address < ActiveRecord::Base
  require 'IPAddr'
 
  def self.find_by_ip(value)
    find :first, :conditions => {:ip => IPAddr.new(value).to_i}
  end
 
  def ip
    IPAddr.new(read_attribute(:ip), Socket::AF_INET).to_s
  end
 
  def ip=(value)
    write_attribute(:ip, IPAddr.new(value).to_i)
  end
end

Posted by nathan on Jun 02 2007 under ruby on rails | |



Leave a Comment