validation_scopes 0.3.0

Sign up to get free protection for your applications and to get access to all the features.
data/.document ADDED
@@ -0,0 +1,5 @@
1
+ README.rdoc
2
+ lib/**/*.rb
3
+ bin/*
4
+ features/**/*.feature
5
+ LICENSE
data/.gitignore ADDED
@@ -0,0 +1,21 @@
1
+ ## MAC OS
2
+ .DS_Store
3
+
4
+ ## TEXTMATE
5
+ *.tmproj
6
+ tmtags
7
+
8
+ ## EMACS
9
+ *~
10
+ \#*
11
+ .\#*
12
+
13
+ ## VIM
14
+ *.swp
15
+
16
+ ## PROJECT::GENERAL
17
+ coverage
18
+ rdoc
19
+ pkg
20
+
21
+ ## PROJECT::SPECIFIC
data/CHANGELOG ADDED
@@ -0,0 +1,11 @@
1
+ == 0.3.0 2009-01-04
2
+
3
+ * Fixed problem with DelegateClass not picking up method definitions that come after the validation_scope block.
4
+
5
+ == 0.2.0 2009-01-04
6
+
7
+ * Added basic unit tests using in-memory sqlite3
8
+
9
+ == 0.1.0 2009-01-03
10
+
11
+ * Initial release. Only tested within an app. Probably has lots of bugs. Test suite forthcoming.
data/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2009 Gabe da Silveira
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,43 @@
1
+ # Validation Scopes
2
+
3
+ This gem adds a simple class method `validation_scope` to `ActiveRecord::Base`. Inside the block you can define validations that don't apply to the life-cycle of the object (ie. they aren't implicitly checked when the object is saved).
4
+
5
+ class Film < ActiveRecord::Base
6
+ validation_scope :warnings do |s|
7
+ s.validates_presence_of :title
8
+ end
9
+ end
10
+
11
+ The generated scope produces 3 helper methods based on the symbol passed to the validation_scope method. Continuing the previous example:
12
+
13
+ film.warnings # analagous to film.errors
14
+ => #<ActiveRecord::Errors>
15
+
16
+ film.no_warnings? # analagous to film.valid?
17
+ => true
18
+
19
+ film.has_warnings? # analagous to film.invalid?
20
+ => false
21
+
22
+ All standard `ActiveRecord::Validations` should work.
23
+
24
+
25
+ ## Caveats
26
+
27
+ Due to the use of a proxy DelegateClass to store each additional set of validations, and some heavy meta-programming to tie it all together with a clean API, there are likely to be some unexpected and confusing edge cases. Please let me know if you discover anything wonky. I believe the opacity of the solution is worth the convenience it provides in exposing the entirety of the Validations API.
28
+
29
+ ### Don't use private methods
30
+
31
+ Because the any validation method supplied as a symbol (eg. `validate :verify_something`) is actually running in the context of a delegate class, private methods won't work as they would in standard validations.
32
+
33
+
34
+ ## Implementation
35
+
36
+ The implementation of this gem is meta-programming heavy and very dependent on the internal structure of ActiveRecord as of Rails 2.3.5. The goal was to be able to utilize the entire functionality of ActiveRecord validations with a minimum of code. The resulting code is a bit more magic than I would have liked, but it seems to be working for me so far. I plan on forward porting to Rails 3 and maybe it will be nicer.
37
+
38
+ The core of the implemention is a dynamically created proxy_class that has ActiveRecord::Validations included in order to isolate its own copy of @errors. The proxy class is a DelegateClass which gets initialized to the base ActiveRecord object so that validations can use any of the methods of the base object. Although the use of DelegateClass raises a few issues, it seemed like the cleanest way to do the integration so that all of the ActiveRecord::Validations concerns just work without too much regard to the specifics of the method implementations.
39
+
40
+
41
+ ## Copyright
42
+
43
+ Copyright (c) 2010 Gabe da Silveira. See LICENSE for details.
data/Rakefile ADDED
@@ -0,0 +1,53 @@
1
+ require 'rubygems'
2
+ require 'rake'
3
+
4
+ begin
5
+ require 'jeweler'
6
+ Jeweler::Tasks.new do |gem|
7
+ gem.name = "validation_scopes"
8
+ gem.summary = %Q{Create sets of validations independent of the life-cycle of an ActiveRecord object}
9
+ gem.description = %Q{Define additional sets of validations beyond the standard "errors" that is tied to the ActiveRecord life-cycle. These additional sets can be defined with all the standard ActiveRecord::Validation macros, and the resulting collection is a standard ActiveRecord::Errors object.}
10
+ gem.email = "gabe@websaviour.com"
11
+ gem.homepage = "http://github.com/dasil003/validation_scopes"
12
+ gem.authors = ["Gabe da Silveira"]
13
+ gem.add_development_dependency "shoulda", ">= 0"
14
+ # gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings
15
+ end
16
+ Jeweler::GemcutterTasks.new
17
+ rescue LoadError
18
+ puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler"
19
+ end
20
+
21
+ require 'rake/testtask'
22
+ Rake::TestTask.new(:test) do |test|
23
+ test.libs << 'lib' << 'test'
24
+ test.pattern = 'test/**/test_*.rb'
25
+ test.verbose = true
26
+ end
27
+
28
+ begin
29
+ require 'rcov/rcovtask'
30
+ Rcov::RcovTask.new do |test|
31
+ test.libs << 'test'
32
+ test.pattern = 'test/**/test_*.rb'
33
+ test.verbose = true
34
+ end
35
+ rescue LoadError
36
+ task :rcov do
37
+ abort "RCov is not available. In order to run rcov, you must: sudo gem install spicycode-rcov"
38
+ end
39
+ end
40
+
41
+ task :test => :check_dependencies
42
+
43
+ task :default => :test
44
+
45
+ require 'rake/rdoctask'
46
+ Rake::RDocTask.new do |rdoc|
47
+ version = File.exist?('VERSION') ? File.read('VERSION') : ""
48
+
49
+ rdoc.rdoc_dir = 'rdoc'
50
+ rdoc.title = "validation_scopes #{version}"
51
+ rdoc.rdoc_files.include('README*')
52
+ rdoc.rdoc_files.include('lib/**/*.rb')
53
+ end
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.3.0
@@ -0,0 +1,59 @@
1
+ require 'delegate'
2
+ require 'active_record'
3
+
4
+ module ValidationScopes
5
+ def self.included(base) # :nodoc:
6
+ base.extend ClassMethods
7
+ end
8
+
9
+ module ClassMethods
10
+ def validation_scope(scope)
11
+ base_class = self
12
+ deferred_proxy_class_declaration = Proc.new do
13
+ proxy_class = Class.new(DelegateClass(base_class)) do
14
+ include ActiveRecord::Validations
15
+
16
+ def initialize(record)
17
+ @base_record = record
18
+ super(record)
19
+ end
20
+
21
+ # Hack since DelegateClass doesn't seem to be making AR::Base class methods available.
22
+ def errors
23
+ @errors ||= ActiveRecord::Errors.new(@base_record)
24
+ end
25
+ end
26
+
27
+ yield proxy_class
28
+
29
+ proxy_class
30
+ end
31
+
32
+ define_method(scope) do
33
+ send("validation_scope_proxy_for_#{scope}").errors
34
+ end
35
+
36
+ define_method("no_#{scope}?") do
37
+ send("validation_scope_proxy_for_#{scope}").valid?
38
+ end
39
+
40
+ define_method("has_#{scope}?") do
41
+ send("validation_scope_proxy_for_#{scope}").invalid?
42
+ end
43
+
44
+ define_method("init_validation_scope_for_#{scope}") do
45
+ unless instance_variable_defined?("@#{scope}")
46
+ klass = deferred_proxy_class_declaration.call
47
+ instance_variable_set("@#{scope}", klass.new(self))
48
+ end
49
+ end
50
+
51
+ define_method("validation_scope_proxy_for_#{scope}") do
52
+ send "init_validation_scope_for_#{scope}"
53
+ instance_variable_get("@#{scope}")
54
+ end
55
+ end
56
+ end
57
+ end
58
+
59
+ ActiveRecord::Base.send(:include, ValidationScopes)
data/test/db/schema.rb ADDED
@@ -0,0 +1,9 @@
1
+ ActiveRecord::Schema.define do
2
+ create_table "users" do |t|
3
+ t.column "name", :string
4
+ t.column "email", :string
5
+ t.column "age", :integer
6
+ t.column "bio", :text
7
+ t.column "sponsor_id", :integer
8
+ end
9
+ end
@@ -0,0 +1,13 @@
1
+ one:
2
+ id: 1
3
+ name: Gabe da Silveira
4
+ email: gabe@websaviour.com
5
+ age: 31
6
+ bio: Technical web creative
7
+ sponsored:
8
+ id: 2
9
+ name: Sven Pulpello
10
+ email: sven@funk.com
11
+ age: 3
12
+ bio: Alter-ego extraordinaire
13
+ sponsor_id: 1
data/test/helper.rb ADDED
@@ -0,0 +1,19 @@
1
+ require 'rubygems'
2
+ require 'test/unit'
3
+ require 'shoulda'
4
+
5
+ $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
6
+ $LOAD_PATH.unshift(File.dirname(__FILE__))
7
+ require 'validation_scopes'
8
+
9
+ ActiveRecord::Base.establish_connection(
10
+ :adapter => "sqlite3",
11
+ :database => ":memory:"
12
+ )
13
+
14
+ require 'db/schema.rb'
15
+
16
+ Dir['test/models/*.rb'].each { |f| require f }
17
+
18
+ require 'active_record/fixtures'
19
+ Fixtures.create_fixtures('test/fixtures/', ActiveRecord::Base.connection.tables)
@@ -0,0 +1,25 @@
1
+ class User < ActiveRecord::Base
2
+ belongs_to :sponsor, :class_name => 'User'
3
+
4
+ validates_presence_of :name
5
+
6
+ validation_scope :warnings do |s|
7
+ s.validates_presence_of :email
8
+ s.validates_format_of :email, :with => %r{\A.+@.+\Z}
9
+ s.validates_inclusion_of :age, :in => 0..99
10
+ s.validate do |r|
11
+ if r.sponsor_id.present? && r.sponsor.nil?
12
+ r.warnings.add(:sponsor_id, "Sponsor ID was defined but record not present")
13
+ end
14
+ end
15
+ end
16
+
17
+ validation_scope :alerts do |s|
18
+ s.validate :age_under_100
19
+ s.validate { |r| r.alerts.add(:email, "We have a hotmail user.") if r.email =~ %r{@hotmail\.com\Z} }
20
+ end
21
+
22
+ def age_under_100
23
+ alerts.add_to_base("We have a centenarian on our hands") if age && age >= 100
24
+ end
25
+ end
@@ -0,0 +1,59 @@
1
+ require 'helper'
2
+
3
+ class TestValidationScopes < Test::Unit::TestCase
4
+ context "A model with warnings and alerts" do
5
+ setup do
6
+ @user = User.find(1)
7
+ end
8
+
9
+ should "have warnings defined" do
10
+ assert_nothing_raised { @user.warnings }
11
+ end
12
+
13
+ should "check for warnings and find none" do
14
+ assert ! @user.has_warnings?
15
+ assert @user.no_warnings?
16
+ end
17
+
18
+ should "raise warning if age set negative" do
19
+ @user.age = -1
20
+ assert @user.has_warnings?
21
+ assert @user.warnings.on(:age)
22
+ end
23
+
24
+ should "raise warning for inline validation" do
25
+ @user.sponsor_id = 12345
26
+ assert @user.has_warnings?
27
+ assert @user.warnings.on(:sponsor_id)
28
+ end
29
+
30
+ should "not add warning to main errors instance" do
31
+ @user.email = ''
32
+ assert @user.has_warnings?
33
+ assert @user.valid?
34
+ assert @user.errors.empty?
35
+ end
36
+
37
+ should "not add errors to the warnings instance" do
38
+ @user.name = ''
39
+ assert @user.invalid?
40
+ assert @user.warnings.empty?
41
+ end
42
+
43
+ context "validating alerts with a private method" do
44
+ setup do
45
+ @user.age = 100
46
+ @user.email = "zappa@hotmail.com"
47
+ end
48
+
49
+ should "set alerts but not errors" do
50
+ assert @user.has_alerts?, "no alerts raised"
51
+ assert @user.alerts.on(:base), "centenarian alert not raised"
52
+ assert @user.alerts.on(:email), "hotmail alert not raised"
53
+ assert @user.valid?, "user not valid"
54
+ assert @user.errors.empty?, "user errors not empty"
55
+ end
56
+ end
57
+ end
58
+
59
+ end
@@ -0,0 +1,60 @@
1
+ # Generated by jeweler
2
+ # DO NOT EDIT THIS FILE DIRECTLY
3
+ # Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command
4
+ # -*- encoding: utf-8 -*-
5
+
6
+ Gem::Specification.new do |s|
7
+ s.name = %q{validation_scopes}
8
+ s.version = "0.3.0"
9
+
10
+ s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
11
+ s.authors = ["Gabe da Silveira"]
12
+ s.date = %q{2010-01-04}
13
+ s.description = %q{Define additional sets of validations beyond the standard "errors" that is tied to the ActiveRecord life-cycle. These additional sets can be defined with all the standard ActiveRecord::Validation macros, and the resulting collection is a standard ActiveRecord::Errors object.}
14
+ s.email = %q{gabe@websaviour.com}
15
+ s.extra_rdoc_files = [
16
+ "LICENSE",
17
+ "README.md"
18
+ ]
19
+ s.files = [
20
+ ".document",
21
+ ".gitignore",
22
+ "CHANGELOG",
23
+ "LICENSE",
24
+ "README.md",
25
+ "Rakefile",
26
+ "VERSION",
27
+ "lib/validation_scopes.rb",
28
+ "test/db/schema.rb",
29
+ "test/fixtures/users.yml",
30
+ "test/helper.rb",
31
+ "test/models/user.rb",
32
+ "test/test_validation_scopes.rb",
33
+ "validation_scopes.gemspec"
34
+ ]
35
+ s.homepage = %q{http://github.com/dasil003/validation_scopes}
36
+ s.rdoc_options = ["--charset=UTF-8"]
37
+ s.require_paths = ["lib"]
38
+ s.rubygems_version = %q{1.3.5}
39
+ s.summary = %q{Create sets of validations independent of the life-cycle of an ActiveRecord object}
40
+ s.test_files = [
41
+ "test/db/schema.rb",
42
+ "test/helper.rb",
43
+ "test/models/user.rb",
44
+ "test/test_validation_scopes.rb"
45
+ ]
46
+
47
+ if s.respond_to? :specification_version then
48
+ current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
49
+ s.specification_version = 3
50
+
51
+ if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
52
+ s.add_development_dependency(%q<shoulda>, [">= 0"])
53
+ else
54
+ s.add_dependency(%q<shoulda>, [">= 0"])
55
+ end
56
+ else
57
+ s.add_dependency(%q<shoulda>, [">= 0"])
58
+ end
59
+ end
60
+
metadata ADDED
@@ -0,0 +1,81 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: validation_scopes
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.3.0
5
+ platform: ruby
6
+ authors:
7
+ - Gabe da Silveira
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+
12
+ date: 2010-01-04 00:00:00 -08:00
13
+ default_executable:
14
+ dependencies:
15
+ - !ruby/object:Gem::Dependency
16
+ name: shoulda
17
+ type: :development
18
+ version_requirement:
19
+ version_requirements: !ruby/object:Gem::Requirement
20
+ requirements:
21
+ - - ">="
22
+ - !ruby/object:Gem::Version
23
+ version: "0"
24
+ version:
25
+ description: Define additional sets of validations beyond the standard "errors" that is tied to the ActiveRecord life-cycle. These additional sets can be defined with all the standard ActiveRecord::Validation macros, and the resulting collection is a standard ActiveRecord::Errors object.
26
+ email: gabe@websaviour.com
27
+ executables: []
28
+
29
+ extensions: []
30
+
31
+ extra_rdoc_files:
32
+ - LICENSE
33
+ - README.md
34
+ files:
35
+ - .document
36
+ - .gitignore
37
+ - CHANGELOG
38
+ - LICENSE
39
+ - README.md
40
+ - Rakefile
41
+ - VERSION
42
+ - lib/validation_scopes.rb
43
+ - test/db/schema.rb
44
+ - test/fixtures/users.yml
45
+ - test/helper.rb
46
+ - test/models/user.rb
47
+ - test/test_validation_scopes.rb
48
+ - validation_scopes.gemspec
49
+ has_rdoc: true
50
+ homepage: http://github.com/dasil003/validation_scopes
51
+ licenses: []
52
+
53
+ post_install_message:
54
+ rdoc_options:
55
+ - --charset=UTF-8
56
+ require_paths:
57
+ - lib
58
+ required_ruby_version: !ruby/object:Gem::Requirement
59
+ requirements:
60
+ - - ">="
61
+ - !ruby/object:Gem::Version
62
+ version: "0"
63
+ version:
64
+ required_rubygems_version: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: "0"
69
+ version:
70
+ requirements: []
71
+
72
+ rubyforge_project:
73
+ rubygems_version: 1.3.5
74
+ signing_key:
75
+ specification_version: 3
76
+ summary: Create sets of validations independent of the life-cycle of an ActiveRecord object
77
+ test_files:
78
+ - test/db/schema.rb
79
+ - test/helper.rb
80
+ - test/models/user.rb
81
+ - test/test_validation_scopes.rb