诗歌rails之Hacking ActiveRecord
1 # test_helper.rb
2 class Test::Unit::TestCase
3 self.use_transactional_fixtures = true
4 self.use_instantiated_fixtures = false
5
6 def disable_validation
7 ActiveRecord::Base.disable_validation!
8 yield
9 ActiveRecord::Base.enable_validation!
10 end
11 end
12
13 module ValidationDisabler
14 def self.included(base)
15 base.class_eval do
16 extend ClassMethods
17 alias_method_chain :valid?, :disable_check
18 end
19 end
20
21 def valid_with_disable_check?
22 if self.class.validation_disabled?
23 true
24 else
25 valid_without_disable_check?
26 end
27 end
28
29 module ClassMethods
30 def disable_validation!
31 @@disable_validation = true
32 end
33
34 def enable_validation!
35 @@disable_validation = false
36 end
37
38 def validation_disabled?
39 @@disable_validation ||= false
40 end
41 end
42 end
43
44 class ActiveRecord::Base
45 include ValidationDisabler
46 end
47
48
2 class Test::Unit::TestCase
3 self.use_transactional_fixtures = true
4 self.use_instantiated_fixtures = false
5
6 def disable_validation
7 ActiveRecord::Base.disable_validation!
8 yield
9 ActiveRecord::Base.enable_validation!
10 end
11 end
12
13 module ValidationDisabler
14 def self.included(base)
15 base.class_eval do
16 extend ClassMethods
17 alias_method_chain :valid?, :disable_check
18 end
19 end
20
21 def valid_with_disable_check?
22 if self.class.validation_disabled?
23 true
24 else
25 valid_without_disable_check?
26 end
27 end
28
29 module ClassMethods
30 def disable_validation!
31 @@disable_validation = true
32 end
33
34 def enable_validation!
35 @@disable_validation = false
36 end
37
38 def validation_disabled?
39 @@disable_validation ||= false
40 end
41 end
42 end
43
44 class ActiveRecord::Base
45 include ValidationDisabler
46 end
47
48
莫愁前路无知己,天下无人不识君。