Module: ActiveRecord::WhenChange

Defined in:
lib/active_record/when_change.rb,
lib/active_record/when_change/version.rb

Defined Under Namespace

Modules: ClassMethods Classes: ChangedAttributes

Constant Summary collapse

VALID_OPTIONS =
[:from, :to, :if, :unless]
VERSION =
"0.0.2"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



7
8
9
# File 'lib/active_record/when_change.rb', line 7

def self.included(base)
  base.extend ClassMethods
end

Instance Method Details

#attribute_changed(attr) ⇒ Object



34
35
36
# File 'lib/active_record/when_change.rb', line 34

def attribute_changed(attr)
  @_changed_attrs[attr] ||= ChangedAttributes.new(attr, @old_attributes || {}, self)
end

#when_change(attr, config = {}, method = nil, &block) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/active_record/when_change.rb', line 11

def when_change attr, config={}, method = nil, &block
  # just return if config is blank or (method or block not given)
  return if self.send("id_was".to_sym).nil? || config.blank? || (method == nil && !block_given? )
  config.keys.each{|key| logger.debug("#{key} is not valid options key for ArctiveRecordChanged") unless VALID_OPTIONS.include?(key)}

  new_attribute         = self.send(attr.to_sym)
  old_attribute         = self.send("#{attr}_was".to_sym)
  return if new_attribute == old_attribute

  correct_form    = ( config[:from] and ( config[:from] != old_attribute ) ? false : true )
  correct_to      = ( config[:to] and ( config[:to] != new_attribute ) ? false : true )
  correct_if      = ( (config[:if] and ( eval(config[:if]) != true ) ) ? false : true )
  correct_unless  = ( (config[:unless] and (eval(config[:unless]) == true) )? false : true )

  if correct_form && correct_to && correct_if && correct_unless
    if block_given?
      block.call(self)
    else
      send(method)
    end
  end
end