Skip to content

Instantly share code, notes, and snippets.

@JeanMertz
Created April 11, 2011 10:50
Show Gist options
  • Save JeanMertz/913352 to your computer and use it in GitHub Desktop.
Save JeanMertz/913352 to your computer and use it in GitHub Desktop.
# app/validators/domain_validator.rb
require "resolv"
class DomainValidator < ActiveModel::EachValidator
def validate_each(object,attribute,value)
begin
domain = Resolv::DNS.new.getresource(value, Resolv::DNS::Resource::IN::CNAME)
valid = true if domain.name.to_s == "mydomain.com"
rescue Exception => e
valid = false
end
object.errors[attribute] << (options[:message] || "is not setup correctly") unless valid
end
end
# app/models/account.rb
class Account < ActiveRecord::Base
validates :domain, :presence => true,
:uniqueness => { :case_sensitive => false },
:format => { :with => /^([a-z\d]+)([\-]{1}[a-z\d]+)*\.[a-z.]+$/i },
:domain => true
attr_accessible :domain
end
# spec/models/account_spec.rb
# This test (and others not testing the validator above) should skip that specific validation
# for speed and to be able to use non-existing domain names
it "rejects a record if the domain is already taken" do
Factory(:account, :domain => "yourcompany.com")
Factory.build(:account, :domain => "yourcompany.com").should_not be_valid
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment