Permalink
Browse files

Add validation for URL format

  • Loading branch information...
drapergeek committed Dec 17, 2012
1 parent ceb4418 commit 30d18510c03986ae2917a017d2e45b8b1ac1438d
@@ -6,11 +6,12 @@ def create
short_url = ShortUrl.new(url: params[:url], name: params[:name])
if short_url.save
flash[:notice] = "Your url: #{short_url.full_url}"
+ redirect_to new_short_url_path
else
- flash[:error] = "#{short_url.name} is already taken"
+ @errors = short_url.errors
+ render :new
end
- redirect_to new_short_url_path
end
def show
View
@@ -1,7 +1,13 @@
class ShortUrl
+ extend ActiveModel::Naming
+ include ActiveModel::Conversion
+ include ActiveModel::Validations
attr_reader :url, :name
- def initialize(options)
+ validate :name_must_be_unique
+ validates :url, format: { with: (/^http(s)?:\/\//), message: "must start with http(s)://" }
+
+ def initialize(options = {})
if options[:name].present?
@name = options[:name]
else
@@ -12,7 +18,7 @@ def initialize(options)
end
def save
- unless existing_entry_with_same_name?
+ if valid?
create_entry
end
end
@@ -30,6 +36,16 @@ def full_url
private
+ def name_must_be_unique
+ if existing_entry_with_same_name?
+ errors.add(:name, "a link already exists named #{name}")
+ end
+ end
+
+ def persisted?
+ false
+ end
+
def existing_entry_with_same_name?
entry_exists_with_name?(@name)
end
@@ -1,8 +1,14 @@
+<% if @errors %>
+<ul>
+ <% @errors.each do |attribute, error|%>
+ <li><%= attribute %> - <%= error %></li>
+ <% end %>
+</ul>
+<% end %>
<%= form_tag short_urls_path do |form| %>
<%= label_tag :url %>
<%= text_field_tag :url %>
<%= label_tag :name %>
<%= text_field_tag :name %>
<%= submit_tag 'Create'%>
<% end %>
-
View
@@ -1,5 +1,5 @@
Shortstuff::Application.routes.draw do
- resources :short_urls, only: [:new, :create]
+ resources :short_urls, only: [:new, :create, :show]
root to: "short_urls#new"
match '/:name' => 'short_urls#show'
@@ -17,7 +17,7 @@
fill_in 'Name', with: 'Search'
click_button 'Create'
- page.should have_content 'Search is already taken'
+ page.should have_content 'name - a link already exists named Search'
end
scenario 'without a name' do
@@ -27,5 +27,13 @@
page.text.should match /Your url: http:\/\/example.com\/\w+/
end
+
+ scenario 'with an invalid url' do
+ visit '/'
+ fill_in 'Url', with: 'google.com'
+ click_button 'Create'
+
+ page.should have_content 'url - must start with http(s)://'
+ end
end

0 comments on commit 30d1851

Please sign in to comment.