Skip to content

Instantly share code, notes, and snippets.

@csexton
Created April 18, 2012 13:47
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save csexton/2413664 to your computer and use it in GitHub Desktop.
Save csexton/2413664 to your computer and use it in GitHub Desktop.
Store the IP Addresses as integers in MongoDB
module MongoidTypes
#
# Store the IP Addresses as integers in MongoDB.
#
# The documents would look something like this in mongo
#
# { "_id" : ObjectId("4f8e2ea261455b704d000001"), "ip_address" : NumberLong("3232235777") }
#
# To have your model use this class simply set the type for the feild in mongoid
#
# field :ip_address, type: MongoidTypes::IpAddress
#
class IpAddress
include Mongoid::Fields::Serializable
# Read from the db
def deserialize(object)
# Socket::AF_INET -> IPv4
# Socket::AF_INET6 -> IPv6
object ? (::IPAddr.new(object, Socket::AF_INET).to_s) : object
end
# Write to the db
def serialize(object)
object ? (::IPAddr.new(object).to_i) : object
end
end
end
@kandadaboggu
Copy link

Do you have some examples for querying and indexing this field?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment