Created
July 4, 2011 06:19
-
-
Save d11wtq/1062969 to your computer and use it in GitHub Desktop.
Validation always fails with "Address must be an Integer" ?
This file contains 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
class Example | |
include DataMapper::Resource | |
property :id, Serial | |
property :ip_address, IPAddressInteger | |
end | |
example = Example.new | |
example.ip_address = "10.48.1.1" | |
example.valid? | |
# => false | |
Example.properties[:ip_address].valid?(example.ip_address) | |
# => true | |
example.save | |
# => false |
This file contains 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
require 'ipaddr' | |
module DataMapper | |
class Property | |
class IPAddressInteger < Integer | |
def initialize(name, model, options = {}) | |
super | |
@format = if options[:version] == :ipv6 | |
Socket::AF_INET6 | |
else | |
Socket::AF_INET | |
end | |
end | |
def primitive?(value) | |
value.kind_of?(::String) | |
end | |
def valid?(value, negated = false) | |
dump(value).kind_of?(::Integer) | |
end | |
def load(value) | |
if value.kind_of?(::Integer) | |
IPAddr.new(value, @format).to_s | |
else | |
value | |
end | |
end | |
def dump(value) | |
case value | |
when ::String then IPAddr.new(value, @format).to_i | |
when ::Integer then value | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment