Dru
Dru

Reputation: 9820

Validating Urls | Prepending http://

I want to check user submitted urls against a regular expression, if the url doesn't begin with http:// or https://, then I would like to prepend http:// to the beginning then save it.

I have some code but I don't know how to incorporate it into my app. Would this code work? And would I incorporate it into my application to check urls before allowing users to create links.

I've attached the code and files below. Thanks

def add_http(link)
  if (link =~ /http[s]?:\/\//)
    link
  else
    "http://#{link}"
  end
end

Controller https://gist.github.com/1279576

_form https://gist.github.com/1279580

Model https://gist.github.com/1279582

Upvotes: 2

Views: 2145

Answers (3)

Dru
Dru

Reputation: 9820

Fixed the code a bit. This works

  before_save do |link|
      link.url = "http://#{url}" unless link.url=~/^https?:\/\//
  end 

Thanks for the guidance @bandito & @rubyprince

Upvotes: 8

bandito
bandito

Reputation: 447

You can place it in your model

class Link < ActiveRecord::Base
  attr_accessible :title, :url
  before_save :sanitize_url

  private 
  def sanitize_url
    if url_changed?
     url = "http://#{url}" unless url =~ /^https?:\/\//
    end
  end 
end

Upvotes: 6

C. K. Young
C. K. Young

Reputation: 223003

The idea is fine. I'd write it like so, though:

def add_http uri
  uri =~ %r(https?://) ? uri : "http://#{uri}"
end

Much simpler, and no leaning toothpicks! :-D

Upvotes: 5

Related Questions