Skip to content

Commit

Permalink
Add presence and length validations
Browse files Browse the repository at this point in the history
  • Loading branch information
jgaskins committed Mar 29, 2012
1 parent 0801523 commit 4da0775
Show file tree
Hide file tree
Showing 2 changed files with 114 additions and 0 deletions.
54 changes: 54 additions & 0 deletions 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
60 changes: 60 additions & 0 deletions spec/validations_spec.rb
Expand Up @@ -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
Expand Down

0 comments on commit 4da0775

Please sign in to comment.