Browse files

Add basic validations with hashidator

  • Loading branch information...
1 parent c2efaa0 commit 4e84bd01408170697106a921da17ad65876ce296 @namelessjon committed Jul 3, 2010
Showing with 23 additions and 6 deletions.
  1. +23 −6 app.rb
View
29 app.rb
@@ -2,6 +2,7 @@
# Jonathan D. Stott <jonathan.stott@gmail.com>
require 'sinatra/base'
require 'mongo'
+require 'hashidator'
require 'black_book/views'
@@ -18,6 +19,14 @@ class App < ::Sinatra::Base
set :name, 'BlackBook'
set :collection, 'people'
+ set :validator, Hashidator.new(
+ 'name' => String,
+ 'page' => String,
+ 'numbers' => proc { |v| v.nil? ? true : [{'name' => String, 'number' => String } ] },
+ 'emails' => proc { |v| v.nil? ? true : [{'name' => String, 'email' => String } ] },
+ 'addresses' => proc { |v| v.nil? ? true : [{'name' => String, 'address' => String, 'postcode' => String, 'country' => String } ] },
+ )
+
helpers do
def people
settings.mongo[settings.collection]
@@ -79,11 +88,15 @@ def clean_params(param_set=params)
params['person']['page'] = page
clean_params
- @person = people.find_one({:page => page}, :fields => [:_id]) || {}
+ @person = people.find_one({:page => page}) || {}
@person.merge!(params['person'])
- people.save(@person)
- redirect "/#{page}"
+ if settings.validator.validate(@person)
+ people.save(@person)
+ redirect "/#{page}"
+ else
+ mustache :edit
+ end
end
post '/' do
@@ -93,11 +106,15 @@ def clean_params(param_set=params)
params['person'].delete_if { |k,v| !%w|name page numbers emails addresses|.include?(k) }
clean_params
- @person = people.find_one({:page => person['page']}, :fields => [:_id]) || {}
+ @person = people.find_one({:page => params['page']}, :fields => [:_id]) || {}
@person.merge!(params['person'])
- people.save(@person)
- redirect "/#{person['page']}"
+ if settings.validator.validate(@person)
+ people.save(@person)
+ redirect "/#{@person['page']}"
+ else
+ mustache :edit
+ end
end
end
end

0 comments on commit 4e84bd0

Please sign in to comment.