Module: ActionPubsub::ActiveRecord::OnChange::ClassMethods

Defined in:
lib/action_pubsub/active_record/on_change.rb

Instance Method Summary collapse

Instance Method Details

#on_change(*attribute_names, &block) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/action_pubsub/active_record/on_change.rb', line 15

def on_change(*attribute_names, &block)
  options = attribute_names.extract_options!

  attribute_names.each do |attribute|
    @_on_change_watches[attribute] = { :block => block }
    @_on_change_watches[attribute].merge!(options)
  end

  on :changed do |record|
    record.previous_changes.each_pair do |k,vals|
      if self.class.react_to_changed?(record, k, vals)
        old_value, new_value = vals
        self.instance_exec(new_value, old_value, &self.class.watched_attributes[k][:block])
      end
    end
  end
end

#react_to_changed?(resource, attribute_name, value) ⇒ Boolean

Returns:

  • (Boolean)


33
34
35
36
37
38
39
40
41
42
# File 'lib/action_pubsub/active_record/on_change.rb', line 33

def react_to_changed?(resource, attribute_name, value)
  old_value, new_value = value
  return false unless watching_attribute?(attribute_name)
  result = true
  result &&= old_value == watched_attributes[attribute_name][:from] if watched_attributes[attribute_name].key?(:from)
  result &&= new_value == watched_attributes[attribute_name][:to] if watched_attributes[attribute_name].key?(:to)
  result &&= watched_attributes[attribute_name][:if].call(resource) if watched_attributes[attribute_name].key?(:if)
  result &&= !watched_attributes[attribute_name][:unless].call(resource) if watched_attributes[attribute_name].key?(:unless)
  return result
end

#watched_attributesObject



48
49
50
# File 'lib/action_pubsub/active_record/on_change.rb', line 48

def watched_attributes
  self.instance_variable_get(:@_on_change_watches)
end

#watching_attribute?(attribute_name) ⇒ Boolean

Returns:

  • (Boolean)


44
45
46
# File 'lib/action_pubsub/active_record/on_change.rb', line 44

def watching_attribute?(attribute_name)
  watched_attributes.key?(attribute_name)
end