Skip to content

Instantly share code, notes, and snippets.

@d11wtq
Created July 4, 2011 06:19
Show Gist options
  • Save d11wtq/1062969 to your computer and use it in GitHub Desktop.
Save d11wtq/1062969 to your computer and use it in GitHub Desktop.
Validation always fails with "Address must be an Integer" ?
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
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