March 14, 2008
1 comment so far

Custom Rails URL Validation

A short example showing how to validate a user provided link in Rails. In the following code, assume we have a Site class that contains a name and link to represent a user's website.

Whenever one attempts to save a Site object, the method valid_link will check for the existence of the URL represented in the 'link' field.

class Site < ActiveRecord::Base
  require 'open-uri'

  belongs_to :user

  validates_presence_of :name
  validate :valid_link

  def valid_link
    begin
      Timeout::timeout(2) do
        open link #ping the server to see if url is valid
      end
    rescue Timeout::Error
      #the url exists but is too large to open within the timeout period
    rescue
      errors.add_to_base("Link provided is not valid")
    end
  end
end

leave comments

if you would like to make a comment, please fill out the form below.

name (required)

email (required)

website

Comments
 

      1. Willie Bens March 20, 2008 2:37 pm

    Hello There:

    Would you be so kind and please tell me how to go about setting up
    Ruby and Rails or Ruby on Rails on a CentOS box.

    I want to start learning Ruby on Rails.
    Even if I do not understand much of your code, I appreciate you did that.

    –Willie Bens