Browse files

Add presence and length validations

  • Loading branch information...
1 parent 0801523 commit 4da07754cadb742c5e4dc0fd290d0e7f8b7ec2b9 @jgaskins committed Mar 29, 2012
Showing with 114 additions and 0 deletions.
  1. +54 −0 lib/perpetuity/validations.rb
  2. +60 −0 spec/validations_spec.rb
View
54 lib/perpetuity/validations.rb
@@ -1,14 +1,68 @@
module Perpetuity
class ValidationSet
+ include Enumerable
+
def initialize
@validations = []
end
def validations
@validations
end
+
+ def << object
+ @validations << object
+ end
+
+ def each &block
+ validations.each &block
+ end
+
+ def valid? object
+ each do |validation|
+ return false unless validation.pass?(object)
+ end
+
+ true
+ end
+
+ def present attribute
+ self << Perpetuity::Validations::Presence.new(attribute)
+ end
+
+ def length attribute, options = {}
+ self << Perpetuity::Validations::Length.new(attribute, options)
+ end
end
class Validation
end
+
+ module Validations
+ class Presence
+ def initialize attribute
+ @attribute = attribute
+ end
+
+ def pass? object
+ !object.send(@attribute).nil?
+ end
+ end
+
+ class Length
+ def initialize attribute, options
+ @attribute = attribute
+ @options = options
+ end
+
+ def pass? object
+ length = object.send(@attribute).length
+
+ return false unless @options[:at_least].nil? or @options[:at_least] <= length
+ return false unless @options[:at_most].nil? or @options[:at_most] >= length
+
+ true
+ end
+ end
+ end
end
View
60 spec/validations_spec.rb
@@ -4,6 +4,66 @@
it 'contains validations' do
subject.validations.should_not be_nil
end
+
+ it 'can add validations' do
+ o = "Validation"
+ subject << o
+
+ subject.first.should == o
+ end
+
+ it 'validates an object' do
+ o = "Validation"
+ o.stub(pass?: true)
+ subject << o
+
+ subject.valid?("object").should be_true
+ end
+
+ it 'invalidates an object' do
+ o = "Validation"
+ o.stub(pass?: false)
+ subject << o
+
+ subject.valid?("object").should be_false
+ end
+
+ describe 'validation types' do
+ let(:valid_object) { Object.new }
+
+ it 'validates presence of an attribute' do
+ valid_object.stub(email: 'me@example.com')
+ subject.present :email
+
+ subject.count.should == 1
+ subject.valid?(valid_object).should be_true
+ end
+
+ it 'validates length of an attribute' do
+ valid_object.stub(email: 'me@example.com')
+ subject.length :email, at_most: 14
+ subject.length :email, at_least: 14
+
+ subject.count.should == 2
+ subject.valid?(valid_object).should be_true
+ end
+
+ it 'invalidates when attribute is too short' do
+ valid_object.stub(email: 'foo')
+ subject.length :email, at_least: 4
+
+ subject.count.should == 1
+ subject.valid?(valid_object).should be_false
+ end
+
+ it 'invalidates when attribute is too long' do
+ valid_object.stub(email: 'me@example.com')
+ subject.length :email, at_most: 4
+
+ subject.count.should == 1
+ subject.valid?(valid_object).should be_false
+ end
+ end
end
describe Perpetuity::Validation do

0 comments on commit 4da0775

Please sign in to comment.