Module: PlusPlus::Base
- Defined in:
- lib/plus_plus/base.rb
Instance Method Summary collapse
Instance Method Details
#plus_plus(*args) ⇒ Object
3 4 5 6 7 8 9 10 11 12 13 14 |
# File 'lib/plus_plus/base.rb', line 3 def plus_plus(*args) = args. association, column = args self.after_create { self.plus_plus_on_create_or_destroy association, column, } self.after_destroy { self.plus_plus_on_create_or_destroy association, column, } end |
#plus_plus_on_change(*args) ⇒ Object
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/plus_plus/base.rb', line 16 def plus_plus_on_change(*args) = args. association, column = args self.after_update do association_model = self.send(association) raise "No association #{association}" if association_model.nil? raise "No :changed option specified" if [:changed].nil? raise "No :plus option specified" if [:plus].nil? raise "No :minus option specified" if [:minus].nil? return unless self.changes.include?([:changed]) dup = self.dup changed = [:changed] offset = if [:value] [:value].respond_to?(:call) ? self.instance_exec(&[:value]) : [:value] else 1 end self.changes.each { |k, v| dup[k] = v.first } # Create a 'snapshot' of what the model did look like prev_satisfied_for_minus = [:minus].respond_to?(:call) ? dup.instance_exec(&[:minus]) : dup.send(changed) == [:minus] self_satisfied_for_plus = [:plus].respond_to?(:call) ? self.instance_exec(&[:plus]) : self.send(changed) == [:plus] self_satisfied_for_minus = [:minus].respond_to?(:call) ? self.instance_exec(&[:minus]) : self.send(changed) == [:minus] prev_satisfied_for_plus = [:plus].respond_to?(:call) ? dup.instance_exec(&[:plus]) : dup.send(changed) == [:plus] updated_val = if prev_satisfied_for_minus && self_satisfied_for_plus association_model.send(column) + offset elsif prev_satisfied_for_plus && self_satisfied_for_minus association_model.send(column) - offset else nil end association_model.send [:update_method] || :update_columns, {column => updated_val} if updated_val end end |