Skip to content

Instantly share code, notes, and snippets.

@releu
Forked from krisleech/README.md
Created March 22, 2012 06:17
Show Gist options
  • Save releu/2156622 to your computer and use it in GitHub Desktop.
Save releu/2156622 to your computer and use it in GitHub Desktop.
State Validator for ActiveModel
puts "State Validator"
class Purchase < ActiveRecord::Base
belongs_to :order
delegate :state_name, :to => :order, :prefix => true
state_machine :state, :initial => :pending do
state :pending
state :confirmed do
validates :order_state_name, :state => :paid
end
end
end
source 'http://rubygems.org'
gem 'activemodel', '>= 3.0.0', :require => 'active_model'
gem 'state_machine', '>= 1.0.0'
gem 'rspec', '~> 2.8.0'
GEM
remote: http://rubygems.org/
specs:
activemodel (3.2.2)
activesupport (= 3.2.2)
builder (~> 3.0.0)
activesupport (3.2.2)
i18n (~> 0.6)
multi_json (~> 1.0)
builder (3.0.0)
diff-lcs (1.1.3)
i18n (0.6.0)
multi_json (1.1.0)
rspec (2.8.0)
rspec-core (~> 2.8.0)
rspec-expectations (~> 2.8.0)
rspec-mocks (~> 2.8.0)
rspec-core (2.8.0)
rspec-expectations (2.8.0)
diff-lcs (~> 1.1.2)
rspec-mocks (2.8.0)
state_machine (1.1.2)
PLATFORMS
ruby
DEPENDENCIES
activemodel (>= 3.0.0)
rspec (~> 2.8.0)
state_machine (>= 1.0.0)
Gem::Specification.new do |s|
s.name = 'state_validator'
s.summary = 'Extending Rails validation to validate State Machines state'
s.description = 'Extending Rails validation to validate State Machines state'
s.version = '0.0.1'
s.platform = Gem::Platform::RUBY
s.files = ['state_validator.rb']
s.require_path = '.'
s.author = 'Jan Bernacki'
s.email = '[email protected]'
s.homepage = 'http://gistflow.com'
s.test_file = 'state_validator_spec.rb'
s.add_development_dependency('rspec', ["~> 2.8"])
s.add_development_dependency('activemodel', ["~> 3.0.0"])
s.add_development_dependency('state_machine', ["~> 1"])
end
module ActiveModel
module Validations
class StateValidator < EachValidator
def validate_each(record, attribute, value)
unless value.to_sym == options[:with].to_sym
error = options[:message] || "#{value} is not #{options[:with]}"
record.errors[attribute] << error
end
end
end
end
end
require 'bundler/setup'
Bundler.require(:default)
require File.expand_path('state_validator')
class Base
include ActiveModel::Validations
attr_accessor :state
state_machine :state, :initial => :active do
state :active
state :inactive
end
end
class Foo < Base
validates :state, :state => :active
end
class Bar < Base
validates :state, :state => :inactive
end
describe 'Validations' do
context 'valid record' do
subject { Foo.new }
it { should be_valid }
end
context 'invalid record' do
subject { Bar.new }
it { should be_invalid }
it 'should add an error' do
subject.valid?
subject.errors[:state].size.should == 1
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment