diff options
author | Marco Ceresa <ceresa@gmail.com> | 2014-12-21 13:39:08 +0100 |
---|---|---|
committer | Marco Ceresa <ceresa@gmail.com> | 2014-12-21 13:39:08 +0100 |
commit | ce5b524748759d23790a710fd1adcca6a547d91d (patch) | |
tree | f73003a3823bba4f0647919a7769e0783f1b310f /lib | |
parent | 27a4d39661507bd068f50cc9cb3f652772ff56a3 (diff) | |
parent | 4fbd9d98e550aa9a8fab8b28c39233ce9f8e7201 (diff) | |
download | ipaddress-ce5b524748759d23790a710fd1adcca6a547d91d.tar.gz |
Merge pull request #52 from gauthier-delacroix/Mongoid-field
Add Mongoid support
Diffstat (limited to 'lib')
-rw-r--r-- | lib/ipaddress.rb | 1 | ||||
-rw-r--r-- | lib/ipaddress/mongoid.rb | 75 |
2 files changed, 76 insertions, 0 deletions
diff --git a/lib/ipaddress.rb b/lib/ipaddress.rb index 7631952..e2161e1 100644 --- a/lib/ipaddress.rb +++ b/lib/ipaddress.rb @@ -14,6 +14,7 @@ require 'ipaddress/ipv4' require 'ipaddress/ipv6' +require 'ipaddress/mongoid' if defined?(Mongoid) module IPAddress diff --git a/lib/ipaddress/mongoid.rb b/lib/ipaddress/mongoid.rb new file mode 100644 index 0000000..3af880a --- /dev/null +++ b/lib/ipaddress/mongoid.rb @@ -0,0 +1,75 @@ +module IPAddress + + # + # Mongoid field serialization + # + # IPAddress objects are converted to String + # + # IPAddress.mongoize IPAddress.parse("172.16.10.1") + # #=> "172.16.10.1" + # + # Prefix will be removed from host adresses + # + # IPAddress.mongoize "172.16.10.1/32" + # #=> "172.16.10.1" + # + # Prefix will be kept for network addresses + # + # IPAddress.mongoize "172.16.10.1/24" + # #=> "172.16.10.1/24" + # + # IPv6 addresses will be stored uncompressed to ease DB search and sorting + # + # IPAddress.mongoize "2001:db8::8:800:200c:417a" + # #=> "2001:0db8:0000:0000:0008:0800:200c:417a" + # IPAddress.mongoize "2001:db8::8:800:200c:417a/64" + # #=> "2001:0db8:0000:0000:0008:0800:200c:417a/64" + # + # Invalid addresses will be serialized as nil + # + # IPAddress.mongoize "invalid" + # #=> nil + # IPAddress.mongoize "" + # #=> nil + # IPAddress.mongoize 1 + # #=> nil + # IPAddress.mongoize nil + # #=> nil + # + def self.mongoize(ipaddress) + ipaddress = self.parse(ipaddress) unless ipaddress.is_a?(IPAddress) + if ipaddress.bits.length == ipaddress.prefix + ipaddress.address + elsif ipaddress.is_a?(IPAddress::IPv6) + ipaddress.to_string_uncompressed + else + ipaddress.to_string + end + rescue ArgumentError + nil + end + + # + # Mongoid field deserialization + # + def self.demongoize(string) + parse(string) + rescue ArgumentError + nil + end + + # + # Delegates to IPAddress.mongoize + # + def self.evolve(ipaddress) + mongoize(ipaddress) + end + + # + # Sends self object to IPAddress#mongoize + # + def mongoize + IPAddress.mongoize(self) + end + +end
\ No newline at end of file |