Created
December 14, 2010 02:44
-
-
Save demery/739928 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# config/initializers/deletable.rb | |
ActiveRecord::Base.class_eval do | |
before_destroy :check_deletable | |
def self.undeletable_if_used(by_hash) | |
unless by_hash[:by] | |
raise "Expected hash to have key :by and a value of one or more symbols" | |
end | |
define_method(:deletable?) do | |
![by_hash[:by]].flatten.detect { |a| | |
if self.respond_to? "#{a.to_s}_count" | |
self.send("#{a.to_s}_count") > 0 | |
else | |
self.send(a.to_s).count | |
end | |
} | |
end | |
(class << self; self; end).send(:define_method, :checks_for_use_by) do | |
[by_hash[:by]].flatten | |
end | |
end | |
# all AR classes now call check_deletable; | |
# don't break if deletable? isn't defined | |
def check_deletable | |
self.respond_to? "deletable?" ? deletable? : true | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment