Created
April 18, 2012 13:47
-
-
Save csexton/2413664 to your computer and use it in GitHub Desktop.
Store the IP Addresses as integers in MongoDB
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Do you have some examples for querying and indexing this field?