Module: UrlFormatter::ModelAdditions

Defined in:
lib/url_formatter/model_additions.rb

Instance Method Summary (collapse)

Instance Method Details

- (Object) format_url(attribute)

To format and validate a URL attribute, call format_url in any Active Record model class and pass it the name of an attribute.

class User < ActiveRecord::Base
  format_url :website
end

This will add a before_validation callback to add "http://" to the attribute if a protocol doesn't exist already. It then validates the format of the URL.



13
14
15
16
17
18
19
# File 'lib/url_formatter/model_additions.rb', line 13

def format_url(attribute)
  before_validation do
    send("#{attribute}=", UrlFormatter.format_url(send(attribute)))
  end
  
  validates_format_of attribute, with: UrlFormatter.url_regexp, message: "is not a valid URL"
end