Skip to content

Instantly share code, notes, and snippets.

@gbarrancos
Created October 6, 2010 12:29
Show Gist options
  • Save gbarrancos/613267 to your computer and use it in GitHub Desktop.
Save gbarrancos/613267 to your computer and use it in GitHub Desktop.
# in the model
validates_with CoordinatesValidator, :fields => [:location]
# Error messaging needs improvement. Since this validator will only whine if someone is forging requests
# with invalid data, i'm leaving it as it is.
class CoordinatesValidator < ActiveModel::Validator
def validate(record)
if options[:fields].any? { |f| invalid_latlng?(record.send(f)) }
record.errors[:base] << "Invalid latlng value"
end
end
private
def invalid_latlng?(value)
return true if value.size != 2
!(value[0].is_a?(Float) && value[1].is_a?(Float))
end
end
@luchoja
Copy link

luchoja commented Nov 23, 2012

Thanks a lot!. This works very well and it is easily extendable.

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