Module: Property::DirtyProperties

Included in:
Properties
Defined in:
lib/property/dirty.rb

Overview

This module implements ActiveRecord::Dirty functionalities for the properties hash.

Constant Summary collapse

CHANGED_REGEXP =
%r{(.+)_changed\?$}
WAS_REGEXP =
%r{(.+)_was$}

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object



82
83
84
85
86
87
88
89
90
# File 'lib/property/dirty.rb', line 82

def method_missing(method, *args)
  if method.to_s =~ CHANGED_REGEXP
    !changes[$1].nil?
  elsif method.to_s =~ WAS_REGEXP
    (@original_hash || self)[$1]
  else
    super
  end
end

Instance Method Details

#[]=(key, value) ⇒ Object



40
41
42
43
# File 'lib/property/dirty.rb', line 40

def []=(key, value)
  @original_hash ||= self.dup
  super
end

#changedObject



54
55
56
# File 'lib/property/dirty.rb', line 54

def changed
  changes.keys
end

#changed?Boolean

Returns:

  • (Boolean)


50
51
52
# File 'lib/property/dirty.rb', line 50

def changed?
  !changes.empty?
end

#changesObject



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/property/dirty.rb', line 58

def changes
  return {} unless @original_hash
  changes = {}

  # look for updated value
  each do |key, new_value|
    if new_value != (old_value = @original_hash[key])
      changes[key] = [old_value, new_value]
    end
  end

  # look for deleted value
  (@original_hash.keys - keys).each do |key|
    changes[key] = [@original_hash[key], nil]
  end

  changes
end

#clear_changes!Object

This method should be called to reset dirty information before dump



78
79
80
# File 'lib/property/dirty.rb', line 78

def clear_changes!
  remove_instance_variable(:@original_hash) if defined?(@original_hash)
end

#delete(key) ⇒ Object



45
46
47
48
# File 'lib/property/dirty.rb', line 45

def delete(key)
  @original_hash ||= self.dup
  super
end