rails_devs_for_data_integrity 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/.gitignore ADDED
@@ -0,0 +1,3 @@
1
+ pkg
2
+ tmp
3
+ log/*
data/MIT-LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2009 [name of plugin creator]
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 ADDED
@@ -0,0 +1,36 @@
1
+ RailsDevsForDataIntegrity
2
+ =========================
3
+ Rails Devs For Data Integrity catches unique key and foreign key violations
4
+ coming from the MySQLdatabase and converts them into an error on the
5
+ ActiveRecord object similar to validation errors
6
+
7
+ class User < ActiveRecord::Base
8
+ handle_unique_key_violation :user_name, :message => 'is taken"
9
+ handle_foreign_key_violation :primary_email_id, :message => 'is not available'
10
+ end
11
+
12
+ Instead of this nasty MySQL foreign key error:
13
+ ActiveRecord::StatementInvalid: Mysql::Error: Cannot add or update a child row:
14
+ a foreign key constraint fails (`zoo_development/animals`,
15
+ CONSTRAINT `fk_animal_species` FOREIGN KEY (`species_id`)
16
+ REFERENCES `species` (`id`) ON DELETE SET NULL ON UPDATE CASCADE)
17
+
18
+ >> user.errors.on(:user_name)
19
+ => "association does not exist."
20
+
21
+ Or in the case of a unique key violation:
22
+
23
+ >> user.errors.on(:primary_email_id)
24
+ => "is a duplicate."
25
+
26
+ ==== Developers
27
+ * Blythe Dunham http://snowgiraffe.com
28
+
29
+ === Install
30
+ * Rdoc: http://snowgiraffe.com/rdocs/rails_devs_for_data_integrity
31
+ * Github Project: http://github.com/blythedunham/rails_devs_for_data_integrity/tree/master
32
+ * Install: script/plugin install git://github.com/blythedunham/rails_devs_for_data_integrity.git
33
+
34
+
35
+
36
+ Copyright (c) 2009 [name of plugin creator], released under the MIT license
data/Rakefile ADDED
@@ -0,0 +1,56 @@
1
+ require 'rubygems'
2
+ require 'rake'
3
+
4
+ begin
5
+ require 'jeweler'
6
+ Jeweler::Tasks.new do |gem|
7
+ gem.name = "rails_devs_for_data_integrity"
8
+ gem.summary = %Q{Gracefully handles MySQL unique and foreign key violations by adding an error to the ActiveRecord object}
9
+ gem.description = %Q{Rails Devs For Data Integrity catches unique key and foreign key violations
10
+ coming from the MySQLdatabase and converts them into an error on the
11
+ ActiveRecord object similar to validation errors
12
+ }
13
+ gem.email = "blythe@snowgiraffe.com"
14
+ gem.homepage = "http://github.com/blythedunham/rails_devs_for_data_integrity"
15
+ gem.authors = ["Blythe Dunham"]
16
+ gem.add_development_dependency "thoughtbot-shoulda", ">= 0"
17
+ # gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings
18
+ end
19
+ Jeweler::GemcutterTasks.new
20
+ rescue LoadError
21
+ puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler"
22
+ end
23
+
24
+ require 'rake/testtask'
25
+ Rake::TestTask.new(:test) do |test|
26
+ test.libs << 'lib' << 'test'
27
+ test.pattern = 'test/**/test_*.rb'
28
+ test.verbose = true
29
+ end
30
+
31
+ begin
32
+ require 'rcov/rcovtask'
33
+ Rcov::RcovTask.new do |test|
34
+ test.libs << 'test'
35
+ test.pattern = 'test/**/test_*.rb'
36
+ test.verbose = true
37
+ end
38
+ rescue LoadError
39
+ task :rcov do
40
+ abort "RCov is not available. In order to run rcov, you must: sudo gem install spicycode-rcov"
41
+ end
42
+ end
43
+
44
+ task :test => :check_dependencies
45
+
46
+ task :default => :test
47
+
48
+ require 'rake/rdoctask'
49
+ Rake::RDocTask.new do |rdoc|
50
+ version = File.exist?('VERSION') ? File.read('VERSION') : ""
51
+
52
+ rdoc.rdoc_dir = 'rdoc'
53
+ rdoc.title = "rails_devs_for_data_integrity #{version}"
54
+ rdoc.rdoc_files.include('README*')
55
+ rdoc.rdoc_files.include('lib/**/*.rb')
56
+ end
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.1.3
data/init.rb ADDED
@@ -0,0 +1 @@
1
+ require File.dirname(__FILE__) + '/lib/rails_devs_for_data_integrity'
data/install.rb ADDED
@@ -0,0 +1 @@
1
+ # Install hook code here
@@ -0,0 +1,218 @@
1
+ # Rails Devs For Data Integrity catches unique key and foreign key violations
2
+ # coming from the MySQLdatabase and converts them into an error on the
3
+ # ActiveRecord object similar to validation errors
4
+ #
5
+ # class User < ActiveRecord::Base
6
+ # handle_unique_key_violation :user_name, :message => 'is taken"
7
+ # handle_foreign_key_violation :primary_email_id, :message => 'is not available'
8
+ # end
9
+ #
10
+ # Instead of this nasty MySQL foreign key error:
11
+ # ActiveRecord::StatementInvalid: Mysql::Error: Cannot add or update a child row:
12
+ # a foreign key constraint fails (`zoo_development/animals`,
13
+ # CONSTRAINT `fk_animal_species` FOREIGN KEY (`species_id`)
14
+ # REFERENCES `species` (`id`) ON DELETE SET NULL ON UPDATE CASCADE)
15
+ #
16
+ # >> user.errors.on(:user_name)
17
+ # => "association does not exist."
18
+ #
19
+ # Or in the case of a unique key violation:
20
+ #
21
+ # >> user.errors.on(:primary_email_id)
22
+ # => "is a duplicate."
23
+ # ==== Developers
24
+ # * Blythe Dunham http://snowgiraffe.com
25
+ #
26
+ # === Install
27
+ # * Rdoc: http://snowgiraffe.com/rdocs/rails_devs_for_data_integrity
28
+ # * Github Project: http://github.com/blythedunham/rails_devs_for_data_integrity/tree/master
29
+ # * Install: script/plugin install git://github.com/blythedunham/rails_devs_for_data_integrity.git
30
+
31
+ module ActiveRecord::RailsDevsForDataIntegrity
32
+
33
+ def self.included(base)#:nodoc
34
+ base.send :class_inheritable_hash, :unique_key_check_options
35
+ base.send :class_inheritable_hash, :foreign_key_check_options
36
+ base.send :attr_reader, :duplicate_exception
37
+ base.send :attr_reader, :foreign_key_exception
38
+
39
+ base.unique_key_check_options = {}
40
+ base.foreign_key_check_options = {}
41
+
42
+ base.extend ClassMethods
43
+ end
44
+
45
+ module ClassMethods
46
+ # Handle a MySQL unique key violation by placing an error message on +name+
47
+ # Currently only one duplicate key per table is supported because no parsing support
48
+ # to determine the violating key
49
+ #
50
+ # +name+ - the field name of the duplicate key.
51
+ #
52
+ # == Options
53
+ # <tt>:message</tt> - custom message. Defaults 'is not unique'.
54
+ #
55
+ # == Example
56
+ # class User < ActiveRecord::Base
57
+ # handle_unique_key_violation :user_name, :message => 'is taken"
58
+ # end
59
+ def handle_unique_key_violation(name, options={})
60
+ alias_data_integrity_methods
61
+ self.unique_key_check_options = options.merge(:field_name => name)
62
+ end
63
+
64
+ # Handle a MySQL foreign key violation by placing an error message on violating
65
+ # foreign key field
66
+ #
67
+ # +name+ - the field name of the duplicate key.
68
+ #
69
+ # == Options
70
+ # <tt>:message</tt> - custom message. Defaults 'association does not exist'.
71
+ #
72
+ # == Example
73
+ # class User < ActiveRecord::Base
74
+ # handle_foreign_key_violation :primary_email_id, :message => 'is does not exist"
75
+ # end
76
+ def handle_foreign_key_violation(name, options={})
77
+ alias_data_integrity_methods
78
+ self.foreign_key_check_options = {name.to_sym => options}
79
+ end
80
+
81
+ # Handle a MySQL foreign key violations by placing an error message on violating
82
+ # foreign key field
83
+ #
84
+ # <tt>:message</tt> - custom message. Defaults 'association does not exist'.
85
+ #== Options
86
+ # Options are a hash of foreign_key field name to options (messages). Without options
87
+ # all violations use the default.
88
+ #
89
+ # == Example
90
+ # class User < ActiveRecord::Base
91
+ # handle_foreign_key_violations :primary_email_id => {:message => 'is does not exist"}
92
+ # end
93
+ def handle_foreign_key_violations(options={})
94
+ self.foreign_key_check_options = options
95
+ alias_data_integrity_methods
96
+ end
97
+
98
+ protected
99
+
100
+ #alias insert and update methods
101
+ def alias_data_integrity_methods#:nodoc:
102
+ return if method_defined?(:create_or_update_without_data_integrity_check)
103
+ alias_method_chain :create_or_update, :data_integrity_check
104
+ alias_method_chain :save!, :data_integrity_check
105
+ end
106
+ end
107
+
108
+ # Add a duplicate error message to errors based on the exception
109
+ def add_unique_key_error(exception)
110
+ if unique_key_check_options[:field_name]
111
+ self.errors.add(unique_key_check_options[:field_name], unique_key_check_options[:message]||"is a duplicate.")
112
+ else
113
+ self.errors.add_to_base(unique_key_check_options[:message]||"Duplicate field.")
114
+ end
115
+ end
116
+
117
+ # Add a foreign key error message to errors based on the exception
118
+ def add_foreign_key_error(exception, foreign_key=nil)
119
+
120
+ foreign_key ||= foreign_key_from_error_message(exception)
121
+ message = foreign_key_check_options[foreign_key.to_sym][:message] if foreign_key_check_options[foreign_key.to_sym]
122
+ message ||= "association does not exist."
123
+
124
+ if self.class.column_names.include?(foreign_key.to_s)
125
+ self.errors.add(foreign_key, message)
126
+ else
127
+ self.errors.add_to_base(" #{foreign_key} #{message}")
128
+ end
129
+ end
130
+
131
+ # Return the foreign key name from the foreign key exception
132
+ def foreign_key_from_error_message(exception)
133
+ if (match = exception.to_s.match(/^Mysql::Error.*foreign key constraint fails.*FOREIGN KEY\s*\(`?([\w_]*)`?\)/))
134
+ return match[1].dup
135
+ end
136
+ end
137
+
138
+ # The classes unique key check options
139
+ def unique_key_check_options
140
+ self.class.unique_key_check_options
141
+ end
142
+
143
+ # The classes foreign key check options
144
+ def foreign_key_check_options
145
+ self.class.foreign_key_check_options
146
+ end
147
+
148
+ # If +exception+ is a unique key violation or a foreign key error,
149
+ # excute the block if it exists. If not and a record exists, add the
150
+ # appropriate error messages. Reraise any exceptions that are not data integrity violation errors
151
+ # Sometimes better to use +execute_with_data_integrity_check+ block
152
+ #
153
+ # +exception+ - Exception thrown from save (insert or update)
154
+ # +record+ - The activerecord object to add errors
155
+ #
156
+ # ===Example
157
+ #
158
+ # def save_safe
159
+ # record = self
160
+ # save
161
+ # rescue ActiveRecord::StatementInvalid => exception
162
+ # handle_data_integrity_error(exception, record)
163
+ # end
164
+ def handle_data_integrity_error(exception, record=nil, &block)
165
+ @duplicate_exception = exception if exception.to_s =~ /^Mysql::Error: Duplicate entry/
166
+ @foreign_key_exception = exception if exception.to_s =~ /^Mysql::Error.*foreign key constraint fails /
167
+
168
+ if @duplicate_exception || @foreign_key_exception
169
+ if block
170
+ yield
171
+ elsif record
172
+ record.add_unique_key_error(exception) if @duplicate_exception
173
+ record.add_foreign_key_error(exception) if @foreign_key_exception
174
+ record
175
+ end
176
+ else
177
+ raise exception
178
+ end
179
+ end
180
+
181
+ # Executes the block and traps data integrity violations
182
+ # Populates the +record+ errors objects with an appropriate message if such violation occurs
183
+ #
184
+ # ===Example
185
+ # def save_safe
186
+ # execute_with_data_integrity_check(self) { save }
187
+ # end
188
+ def execute_with_data_integrity_check(record = nil, &block)
189
+ @duplicate_exception = nil
190
+ @foreign_key_exception = nil
191
+ yield record
192
+ true
193
+ rescue ActiveRecord::StatementInvalid => exception
194
+ handle_data_integrity_error(exception, record)
195
+ return false
196
+ end
197
+
198
+ # do a create or update with data integrity check
199
+ def create_or_update_with_data_integrity_check(options={})
200
+ execute_with_data_integrity_check(self) do
201
+ return create_or_update_without_data_integrity_check
202
+ end
203
+ end
204
+
205
+ # save! with data integrity check
206
+ # RecordNotSaved will be thrown by save! before converting to the standard
207
+ # validation error ActiveRecord::RecordInvalid
208
+ def save_with_data_integrity_check!(*args)
209
+ unless save(*args)
210
+ raise ActiveRecord::RecordInvalid.new(self) if @duplicate_exception||@foreign_key_exception
211
+ raise ActiveRecord::RecordNotSaved
212
+ end
213
+ true
214
+ end
215
+ end
216
+
217
+ ActiveRecord::Base.send :include, ActiveRecord::RailsDevsForDataIntegrity
218
+
@@ -0,0 +1,59 @@
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{rails_devs_for_data_integrity}
8
+ s.version = "0.1.3"
9
+
10
+ s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
11
+ s.authors = ["Blythe Dunham"]
12
+ s.date = %q{2009-12-17}
13
+ s.description = %q{Rails Devs For Data Integrity catches unique key and foreign key violations
14
+ coming from the MySQLdatabase and converts them into an error on the
15
+ ActiveRecord object similar to validation errors
16
+ }
17
+ s.email = %q{blythe@snowgiraffe.com}
18
+ s.extra_rdoc_files = [
19
+ "README"
20
+ ]
21
+ s.files = [
22
+ ".gitignore",
23
+ "MIT-LICENSE",
24
+ "README",
25
+ "Rakefile",
26
+ "VERSION",
27
+ "init.rb",
28
+ "install.rb",
29
+ "lib/rails_devs_for_data_integrity.rb",
30
+ "rails_devs_for_data_integrity.gemspec",
31
+ "tasks/rails_devs_for_data_integrity_tasks.rake",
32
+ "test/rails_devs_for_data_integrity_test.rb",
33
+ "test/test_helper.rb",
34
+ "uninstall.rb"
35
+ ]
36
+ s.homepage = %q{http://github.com/blythedunham/rails_devs_for_data_integrity}
37
+ s.rdoc_options = ["--charset=UTF-8"]
38
+ s.require_paths = ["lib"]
39
+ s.rubygems_version = %q{1.3.5}
40
+ s.summary = %q{Gracefully handles MySQL unique and foreign key violations by adding an error to the ActiveRecord object}
41
+ s.test_files = [
42
+ "test/rails_devs_for_data_integrity_test.rb",
43
+ "test/test_helper.rb"
44
+ ]
45
+
46
+ if s.respond_to? :specification_version then
47
+ current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
48
+ s.specification_version = 3
49
+
50
+ if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
51
+ s.add_development_dependency(%q<thoughtbot-shoulda>, [">= 0"])
52
+ else
53
+ s.add_dependency(%q<thoughtbot-shoulda>, [">= 0"])
54
+ end
55
+ else
56
+ s.add_dependency(%q<thoughtbot-shoulda>, [">= 0"])
57
+ end
58
+ end
59
+
@@ -0,0 +1,4 @@
1
+ # desc "Explaining what the task does"
2
+ # task :rails_devs_for_data_integrity do
3
+ # # Task goes here
4
+ # end
@@ -0,0 +1,8 @@
1
+ require 'test_helper'
2
+
3
+ class RailsDevsForDataIntegrityTest < ActiveSupport::TestCase
4
+ # Replace this with your real tests.
5
+ test "the truth" do
6
+ assert true
7
+ end
8
+ end
@@ -0,0 +1,3 @@
1
+ require 'rubygems'
2
+ require 'active_support'
3
+ require 'active_support/test_case'
data/uninstall.rb ADDED
@@ -0,0 +1 @@
1
+ # Uninstall hook code here
metadata ADDED
@@ -0,0 +1,77 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rails_devs_for_data_integrity
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.3
5
+ platform: ruby
6
+ authors:
7
+ - Blythe Dunham
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+
12
+ date: 2009-12-17 00:00:00 -08:00
13
+ default_executable:
14
+ dependencies:
15
+ - !ruby/object:Gem::Dependency
16
+ name: thoughtbot-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: "Rails Devs For Data Integrity catches unique key and foreign key violations\n coming from the MySQLdatabase and converts them into an error on the\n ActiveRecord object similar to validation errors\n "
26
+ email: blythe@snowgiraffe.com
27
+ executables: []
28
+
29
+ extensions: []
30
+
31
+ extra_rdoc_files:
32
+ - README
33
+ files:
34
+ - .gitignore
35
+ - MIT-LICENSE
36
+ - README
37
+ - Rakefile
38
+ - VERSION
39
+ - init.rb
40
+ - install.rb
41
+ - lib/rails_devs_for_data_integrity.rb
42
+ - rails_devs_for_data_integrity.gemspec
43
+ - tasks/rails_devs_for_data_integrity_tasks.rake
44
+ - test/rails_devs_for_data_integrity_test.rb
45
+ - test/test_helper.rb
46
+ - uninstall.rb
47
+ has_rdoc: true
48
+ homepage: http://github.com/blythedunham/rails_devs_for_data_integrity
49
+ licenses: []
50
+
51
+ post_install_message:
52
+ rdoc_options:
53
+ - --charset=UTF-8
54
+ require_paths:
55
+ - lib
56
+ required_ruby_version: !ruby/object:Gem::Requirement
57
+ requirements:
58
+ - - ">="
59
+ - !ruby/object:Gem::Version
60
+ version: "0"
61
+ version:
62
+ required_rubygems_version: !ruby/object:Gem::Requirement
63
+ requirements:
64
+ - - ">="
65
+ - !ruby/object:Gem::Version
66
+ version: "0"
67
+ version:
68
+ requirements: []
69
+
70
+ rubyforge_project:
71
+ rubygems_version: 1.3.5
72
+ signing_key:
73
+ specification_version: 3
74
+ summary: Gracefully handles MySQL unique and foreign key violations by adding an error to the ActiveRecord object
75
+ test_files:
76
+ - test/rails_devs_for_data_integrity_test.rb
77
+ - test/test_helper.rb