Lazy attributes and partial updates
[railsex.git] / lib / activerecord / changed.rb
blob309a2d93bfa6c9f0690afe677a47a2f80fd0f92f
1 module ActiveRecord
2   module Changed
3     def self.included(base)
4       base.extend ClassMethods
5       base.alias_method_chain :attributes_with_quotes, :changed
6       base.alias_method_chain :write_attribute, :changed
7       base.alias_method_chain :save, :changed
8       base.alias_method_chain :save!, :changed
9       base.alias_method_chain :reload, :changed
10     end
11     
12     module ClassMethods    
13       def lazy_attributes(*args)
14         @@lazy_attributes ||= Array(args).map(&:to_s).to_set
15       end
16     end
17     
18     private
19     
20     def attributes_with_quotes_with_changed(include_primary_key = true, include_readonly_attributes = true)
21       original = attributes_with_quotes_without_changed(include_primary_key, include_readonly_attributes)
22       
23       # Reject only if both supplied arguments are false
24       original.reject! { |key, value| changed_lazy.include?(key) } if !(include_primary_key || include_readonly_attributes)
25       original
26     end
27     
28     def write_attribute_with_changed(attr_name, value)
29       changed_lazy.delete(attr_name.to_s)
30       write_attribute_without_changed(attr_name, value)
31     end
32     
33     def reload_with_changed
34       @changed_lazy = nil
35       reload_without_changed
36     end
37     
38     def changed_lazy
39       @changed_lazy ||= self.class.lazy_attributes.clone
40     end
41     
42     def save_with_changed
43       save_without_changed ensure @changed_lazy = nil
44     end
46     def save_with_changed!
47       save_without_changed! ensure @changed_lazy = nil
48     end
49   end
50 end
52 ActiveRecord::Base.send :include, ActiveRecord::Changed