dependent_protect 0.0.2

Sign up to get free protection for your applications and to get access to all the features.
data/Gemfile ADDED
@@ -0,0 +1,11 @@
1
+ source :rubygems
2
+ gemspec
3
+
4
+ group :development, :test do
5
+ gem 'rake', '~> 0.9.2'
6
+ gem 'rdoc', '~> 3.12'
7
+ gem 'rspec'
8
+ gem 'simplecov'
9
+ gem 'simplecov-rcov'
10
+ gem 'sqlite3'
11
+ end
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License
2
+
3
+ Copyright (c) Tom Preston-Werner
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,21 @@
1
+ = dependent => :protect option
2
+
3
+ Adds a new option :protect for the parameter <tt>:depends</tt> from +has_many+
4
+ method. This option forbids destroying records with associated records in a
5
+ association created with <tt>:dependent => :protect</tt> option, more or less
6
+ like <tt>ON DELETE RESTRICT</tt> SQL statement. If you try to destroy a record with
7
+ associated records it will raise a
8
+ ActiveRecord::ReferentialIntegrityProtectionError (defined also in this
9
+ plugin).
10
+
11
+ Based on the idea and the code from diego.algorta@gmail.com in Ruby on Rails
12
+ ticket #3837 (http://dev.rubyonrails.org/ticket/3837).
13
+
14
+ You can download this plugin at:
15
+
16
+ http://svn.ruido-blanco.net/dependent_protect/trunk
17
+
18
+ == Author
19
+
20
+ Daniel Rodr�guez Troiti�o <drodrigueztroitino@yahoo.es>, based on the ideas and
21
+ the code from <diego.algorta@gmail.com>.
data/Rakefile ADDED
@@ -0,0 +1,150 @@
1
+ require 'rubygems'
2
+ require 'rake'
3
+ require 'date'
4
+
5
+ #############################################################################
6
+ #
7
+ # Helper functions
8
+ #
9
+ #############################################################################
10
+
11
+ def name
12
+ @name ||= Dir['*.gemspec'].first.split('.').first
13
+ end
14
+
15
+ def version
16
+ line = File.read("lib/#{name}.rb")[/^\s*VERSION\s*=\s*.*/]
17
+ line.match(/.*VERSION\s*=\s*['"](.*)['"]/)[1]
18
+ end
19
+
20
+ def date
21
+ Date.today.to_s
22
+ end
23
+
24
+ def rubyforge_project
25
+ name
26
+ end
27
+
28
+ def gemspec_file
29
+ "#{name}.gemspec"
30
+ end
31
+
32
+ def gem_file
33
+ "#{name}-#{version}.gem"
34
+ end
35
+
36
+ def replace_header(head, header_name)
37
+ head.sub!(/(\.#{header_name}\s*= ').*'/) { "#{$1}#{send(header_name)}'"}
38
+ end
39
+
40
+ #############################################################################
41
+ #
42
+ # Standard tasks
43
+ #
44
+ #############################################################################
45
+
46
+ desc 'Default: run specs.'
47
+ task :default => :spec
48
+
49
+ require 'rspec/core/rake_task'
50
+
51
+ desc "Run specs"
52
+ RSpec::Core::RakeTask.new do |t|
53
+ t.pattern = "./spec/**/*_spec.rb" # don't need this, it's default.
54
+ # Put spec opts in a file named .rspec in root
55
+ end
56
+
57
+ desc "Generate SimpleCov test coverage and open in your browser"
58
+ task :coverage do
59
+ ENV['COVERAGE'] = 'true'
60
+ Rake::Task['spec'].invoke
61
+ end
62
+
63
+ require 'rdoc/task'
64
+ RDoc::Task.new do |rdoc|
65
+ rdoc.rdoc_dir = 'rdoc'
66
+ rdoc.title = "#{name} #{version}"
67
+ rdoc.rdoc_files.include('README*')
68
+ rdoc.rdoc_files.include('lib/**/*.rb')
69
+ end
70
+
71
+ desc "Open an irb session preloaded with this library"
72
+ task :console do
73
+ sh "irb -rubygems -r ./lib/#{name}.rb"
74
+ end
75
+
76
+ #############################################################################
77
+ #
78
+ # Custom tasks (add your own tasks here)
79
+ #
80
+ #############################################################################
81
+
82
+
83
+
84
+ #############################################################################
85
+ #
86
+ # Packaging tasks
87
+ #
88
+ #############################################################################
89
+
90
+ desc "Create tag v#{version} and build and push #{gem_file} to Rubygems"
91
+ task :release => :build do
92
+ unless `git branch` =~ /^\* master$/
93
+ puts "You must be on the master branch to release!"
94
+ exit!
95
+ end
96
+ sh "git commit --allow-empty -a -m 'Release #{version}'"
97
+ sh "git tag v#{version}"
98
+ sh "git push origin master"
99
+ sh "git push origin v#{version}"
100
+ sh "gem push pkg/#{name}-#{version}.gem"
101
+ end
102
+
103
+ desc "Build #{gem_file} into the pkg directory"
104
+ task :build => :gemspec do
105
+ sh "mkdir -p pkg"
106
+ sh "gem build #{gemspec_file}"
107
+ sh "mv #{gem_file} pkg"
108
+ end
109
+
110
+ desc "Generate #{gemspec_file}"
111
+ task :gemspec => :validate do
112
+ # read spec file and split out manifest section
113
+ spec = File.read(gemspec_file)
114
+ head, manifest, tail = spec.split(" # = MANIFEST =\n")
115
+
116
+ # replace name version and date
117
+ replace_header(head, :name)
118
+ replace_header(head, :version)
119
+ replace_header(head, :date)
120
+ #comment this out if your rubyforge_project has a different name
121
+ replace_header(head, :rubyforge_project)
122
+
123
+ # determine file list from git ls-files
124
+ files = `git ls-files`.
125
+ split("\n").
126
+ sort.
127
+ reject { |file| file =~ /^\./ }.
128
+ reject { |file| file =~ /^(rdoc|pkg)/ }.
129
+ map { |file| " #{file}" }.
130
+ join("\n")
131
+
132
+ # piece file back together and write
133
+ manifest = " s.files = %w[\n#{files}\n ]\n"
134
+ spec = [head, manifest, tail].join(" # = MANIFEST =\n")
135
+ File.open(gemspec_file, 'w') { |io| io.write(spec) }
136
+ puts "Updated #{gemspec_file}"
137
+ end
138
+
139
+ desc "Validate #{gemspec_file}"
140
+ task :validate do
141
+ libfiles = Dir['lib/*'] - ["lib/#{name}.rb", "lib/#{name}"]
142
+ unless libfiles.empty?
143
+ puts "Directory `lib` should only contain a `#{name}.rb` file and `#{name}` dir."
144
+ exit!
145
+ end
146
+ unless Dir['VERSION*'].empty?
147
+ puts "A `VERSION` file at root level violates Gem best practices."
148
+ exit!
149
+ end
150
+ end
@@ -0,0 +1,76 @@
1
+ ## This is the rakegem gemspec template. Make sure you read and understand
2
+ ## all of the comments. Some sections require modification, and others can
3
+ ## be deleted if you don't need them. Once you understand the contents of
4
+ ## this file, feel free to delete any comments that begin with two hash marks.
5
+ ## You can find comprehensive Gem::Specification documentation, at
6
+ ## http://docs.rubygems.org/read/chapter/20
7
+ Gem::Specification.new do |s|
8
+ s.specification_version = 2 if s.respond_to? :specification_version=
9
+ s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
10
+ s.rubygems_version = '1.3.5'
11
+
12
+ ## Leave these as is they will be modified for you by the rake gemspec task.
13
+ ## If your rubyforge_project name is different, then edit it and comment out
14
+ ## the sub! line in the Rakefile
15
+ s.name = 'dependent_protect'
16
+ s.version = '0.0.2'
17
+ s.date = '2012-04-09'
18
+ s.rubyforge_project = 'dependent_protect'
19
+
20
+ ## Make sure your summary is short. The description may be as long
21
+ ## as you like.
22
+ s.summary = "Add dependent protect/restrict functionality to ActiveRecord 2.x."
23
+ s.description = "This gem is not needed in Rails 3 as dependent => :raise is included in 3.0."
24
+
25
+ ## List the primary authors. If there are a bunch of authors, it's probably
26
+ ## better to set the email to an email list or something. If you don't have
27
+ ## a custom homepage, consider using your GitHub URL or the like.
28
+ s.authors = ["Michael Noack"]
29
+ s.email = 'development@travellink.com.au'
30
+ s.homepage = 'http://github.com/sealink/dependent_protect'
31
+
32
+ ## This gets added to the $LOAD_PATH so that 'lib/NAME.rb' can be required as
33
+ ## require 'NAME.rb' or'/lib/NAME/file.rb' can be as require 'NAME/file.rb'
34
+ s.require_paths = %w[lib]
35
+
36
+ ## This sections is only necessary if you have C extensions.
37
+ # s.require_paths << 'ext'
38
+ # s.extensions = %w[ext/extconf.rb]
39
+
40
+ ## If your gem includes any executables, list them here.
41
+ # s.executables = ["name"]
42
+
43
+ ## Specify any RDoc options here. You'll want to add your README and
44
+ ## LICENSE files to the extra_rdoc_files list.
45
+ s.rdoc_options = ["--charset=UTF-8"]
46
+ s.extra_rdoc_files = %w[README.md LICENSE]
47
+
48
+ ## List your runtime dependencies here. Runtime dependencies are those
49
+ ## that are needed for an end user to actually USE your code.
50
+ s.add_dependency('activerecord', [">= 2.3.0", "< 3.0.0"])
51
+
52
+ ## List your development dependencies here. Development dependencies are
53
+ ## those that are only needed during development
54
+ # s.add_development_dependency('DEVDEPNAME', [">= 1.1.0", "< 2.0.0"])
55
+
56
+ ## Leave this section as-is. It will be automatically generated from the
57
+ ## contents of your Git repository via the gemspec task. DO NOT REMOVE
58
+ ## THE MANIFEST COMMENTS, they are used as delimiters by the task.
59
+ # = MANIFEST =
60
+ s.files = %w[
61
+ Gemfile
62
+ LICENSE
63
+ README.md
64
+ Rakefile
65
+ dependent_protect.gemspec
66
+ lib/dependent_protect.rb
67
+ spec/dependent_protect_spec.rb
68
+ spec/schema.rb
69
+ spec/spec_helper.rb
70
+ ]
71
+ # = MANIFEST =
72
+
73
+ ## Test files will be grabbed from the file list. Make sure the path glob
74
+ ## matches what you actually use.
75
+ s.test_files = s.files.select { |path| path =~ /^test\/test_.*\.rb/ }
76
+ end
@@ -0,0 +1,95 @@
1
+ # DependentProtect
2
+ #
3
+ require 'activerecord'
4
+
5
+ module DependentProtect
6
+ VERSION = '0.0.2'
7
+
8
+ DESTROY_PROTECT_ERROR_MESSAGE = 'Cant destroy because there are dependent_count dependent_type dependent on dependee_type dependee.\n\n\nThese include:\ndependent_examples'
9
+
10
+ def self.included(base)
11
+ super
12
+ base.extend(ClassMethods)
13
+
14
+ klass = Class.new(ActiveRecord::ActiveRecordError)
15
+ ActiveRecord.const_set('DependencyError', klass)
16
+
17
+ base.class_eval do
18
+ class << self
19
+ alias_method_chain :has_one, :protect
20
+ alias_method_chain :has_many, :protect
21
+ alias_method_chain :has_and_belongs_to_many, :protect
22
+ end
23
+ end
24
+ end
25
+
26
+ module ClassMethods
27
+ # We should be aliasing configure_dependency_for_has_many but that method
28
+ # is private so we can't. We alias has_many instead trying to be as fair
29
+ # as we can to the original behaviour.
30
+ def has_one_with_protect(association_id, options = {}, &extension) #:nodoc:
31
+ reflection = create_reflection(:has_one, association_id, options, self)
32
+ add_dependency_callback!(reflection, options)
33
+ has_one_without_protect(association_id, options, &extension)
34
+ end
35
+
36
+ def has_many_with_protect(association_id, options = {}, &extension) #:nodoc:
37
+ reflection = create_reflection(:has_many, association_id, options, self)
38
+ add_dependency_callback!(reflection, options)
39
+ has_many_without_protect(association_id, options, &extension)
40
+ end
41
+
42
+ def has_and_belongs_to_many_with_protect(association_id, options = {}, &extension)
43
+ reflection = create_reflection(:has_and_belongs_to_many, association_id, options, self)
44
+ add_dependency_callback!(reflection, options)
45
+ has_and_belongs_to_many_without_protect(association_id, options, &extension)
46
+ end
47
+
48
+ private
49
+ def add_dependency_callback!(reflection, options)
50
+ # This would break if has_many :dependent behaviour changes. One
51
+ # solution is removing both the second when and the else branches but
52
+ # the exception message wouldn't be exact.
53
+ condition = if reflection.collection?
54
+ "record.#{reflection.name}.empty?"
55
+ else
56
+ "record.#{reflection.name}.nil?"
57
+ end
58
+
59
+ case reflection.options[:dependent]
60
+ when :rollback
61
+ options.delete(:dependent)
62
+ module_eval "before_destroy, :protect_rollback, :unless => proc{ |record| #{condition} }"
63
+ when :raise
64
+ options.delete(:dependent)
65
+ error = reflection.collection? ? dependency_error(reflection) : "Cannot remove as the associated object is dependent on this."
66
+ module_eval <<-METHOD
67
+ def protect_raise_#{reflection.name}
68
+ raise ActiveRecord::DependencyError, "#{error}"
69
+ end
70
+ METHOD
71
+ module_eval "before_destroy :protect_raise_#{reflection.name}, :unless => proc{ |record| #{condition} }"
72
+ end
73
+ end
74
+
75
+ def protect_rollback
76
+ raise ActiveRecord::Rollback
77
+ end
78
+
79
+ def dependency_error(reflection)
80
+ # TODO: gotta be a more easier approach!
81
+ count_code = "#{reflection.name}.count"
82
+ first_five_code = reflection.name.to_s+'.first(5).map{|o| "#{o.id}: #{o.to_s}"}'
83
+ DESTROY_PROTECT_ERROR_MESSAGE.
84
+ gsub('dependent_type', reflection.class_name.to_s.underscore.gsub('_', ' ').pluralize).
85
+ gsub('dependent_examples', '#{(' + first_five_code + ' + [("...and #{' + count_code + ' - 5} more" if ' + count_code + ' > 5)]).join("\n")}').
86
+ gsub('dependent_count', '#{' + count_code + '}').
87
+ gsub('dependee_type', '#{self.class.to_s.underscore.gsub(\'_\', \' \')}').
88
+ gsub('dependee', '#{self}')
89
+ end
90
+
91
+ end
92
+ end
93
+
94
+
95
+ ActiveRecord::Base.send(:include, DependentProtect)
@@ -0,0 +1,43 @@
1
+ require 'spec_helper'
2
+
3
+ DB_FILE = 'tmp/test_db'
4
+ FileUtils.mkdir_p File.dirname(DB_FILE)
5
+ FileUtils.rm_f DB_FILE
6
+
7
+ ActiveRecord::Base.establish_connection :adapter => 'sqlite3', :database => DB_FILE
8
+
9
+ load 'spec/schema.rb'
10
+
11
+ class OrderInvoice < ActiveRecord::Base
12
+ belongs_to :order
13
+ end
14
+
15
+ class Order < ActiveRecord::Base
16
+ belongs_to :category
17
+ has_one :order_invoice, :dependent => :raise
18
+ end
19
+
20
+ class Category < ActiveRecord::Base
21
+ has_many :orders, :dependent => :raise
22
+ end
23
+
24
+ describe DependentProtect do
25
+ it 'should restrict has_many relationships' do
26
+ category = Category.create!
27
+ order = Order.create!(:category => category)
28
+ lambda{category.reload.destroy}.should raise_error(ActiveRecord::DependencyError)
29
+
30
+ order.destroy
31
+ lambda{category.reload.destroy}.should_not raise_error
32
+ end
33
+
34
+ it 'should restrict has_one relationships' do
35
+ order = Order.create!
36
+ order_invoice = OrderInvoice.create!(:order => order)
37
+ lambda{order.reload.destroy}.should raise_error(ActiveRecord::DependencyError)
38
+
39
+ order_invoice.destroy
40
+ lambda{order.reload.destroy}.should_not raise_error
41
+ end
42
+ end
43
+
data/spec/schema.rb ADDED
@@ -0,0 +1,13 @@
1
+ ActiveRecord::Schema.define(:version => 1) do
2
+ create_table :categories do |t|
3
+ end
4
+
5
+ create_table :order_invoices do |t|
6
+ t.integer :order_id
7
+ end
8
+
9
+ create_table :orders do |t|
10
+ t.integer :category_id
11
+ end
12
+ end
13
+
@@ -0,0 +1,23 @@
1
+ # This file was generated by the `rspec --init` command. Conventionally, all
2
+ # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
3
+ # Require this file using `require "spec_helper.rb"` to ensure that it is only
4
+ # loaded once.
5
+ #
6
+ # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
7
+
8
+ require 'rubygems'
9
+ require 'bundler/setup'
10
+ require 'dependent_protect'
11
+
12
+ if ENV['COVERAGE']
13
+ require 'simplecov'
14
+ require 'simplecov-rcov'
15
+ SimpleCov.formatter = SimpleCov::Formatter::RcovFormatter
16
+ SimpleCov.start
17
+ end
18
+
19
+ RSpec.configure do |config|
20
+ config.treat_symbols_as_metadata_keys_with_true_values = true
21
+ config.run_all_when_everything_filtered = true
22
+ config.filter_run :focus
23
+ end
metadata ADDED
@@ -0,0 +1,79 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: dependent_protect
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.2
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - Michael Noack
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2012-04-09 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: activerecord
16
+ requirement: !ruby/object:Gem::Requirement
17
+ none: false
18
+ requirements:
19
+ - - ! '>='
20
+ - !ruby/object:Gem::Version
21
+ version: 2.3.0
22
+ - - <
23
+ - !ruby/object:Gem::Version
24
+ version: 3.0.0
25
+ type: :runtime
26
+ prerelease: false
27
+ version_requirements: !ruby/object:Gem::Requirement
28
+ none: false
29
+ requirements:
30
+ - - ! '>='
31
+ - !ruby/object:Gem::Version
32
+ version: 2.3.0
33
+ - - <
34
+ - !ruby/object:Gem::Version
35
+ version: 3.0.0
36
+ description: This gem is not needed in Rails 3 as dependent => :raise is included
37
+ in 3.0.
38
+ email: development@travellink.com.au
39
+ executables: []
40
+ extensions: []
41
+ extra_rdoc_files:
42
+ - README.md
43
+ - LICENSE
44
+ files:
45
+ - Gemfile
46
+ - LICENSE
47
+ - README.md
48
+ - Rakefile
49
+ - dependent_protect.gemspec
50
+ - lib/dependent_protect.rb
51
+ - spec/dependent_protect_spec.rb
52
+ - spec/schema.rb
53
+ - spec/spec_helper.rb
54
+ homepage: http://github.com/sealink/dependent_protect
55
+ licenses: []
56
+ post_install_message:
57
+ rdoc_options:
58
+ - --charset=UTF-8
59
+ require_paths:
60
+ - lib
61
+ required_ruby_version: !ruby/object:Gem::Requirement
62
+ none: false
63
+ requirements:
64
+ - - ! '>='
65
+ - !ruby/object:Gem::Version
66
+ version: '0'
67
+ required_rubygems_version: !ruby/object:Gem::Requirement
68
+ none: false
69
+ requirements:
70
+ - - ! '>='
71
+ - !ruby/object:Gem::Version
72
+ version: '0'
73
+ requirements: []
74
+ rubyforge_project: dependent_protect
75
+ rubygems_version: 1.8.21
76
+ signing_key:
77
+ specification_version: 2
78
+ summary: Add dependent protect/restrict functionality to ActiveRecord 2.x.
79
+ test_files: []