Module: UrrlFormatter::ModelAdditions
- Defined in:
- lib/urrl_formatter/model_additions.rb
Instance Method Summary collapse
-
#format_url(attribute) ⇒ Object
To format and validate a URL attribute, call
format_url
in any Active Record model class and pass it the name of an attribute.
Instance Method Details
#format_url(attribute) ⇒ Object
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 |
# File 'lib/urrl_formatter/model_additions.rb', line 13 def format_url(attribute) before_validation do send("#{attribute}=", UrrlFormatter.format_url(send(attribute))) end validates_format_of attribute, with: UrrlFormatter.url_regexp, message: "is not a valid URL" end |