Module: MongoMapper::Dirty

Defined in:
lib/mongo_mapper/dirty.rb

Constant Summary collapse

DIRTY_SUFFIXES =
['_changed?', '_change', '_will_change!', '_was']

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/mongo_mapper/dirty.rb', line 5

def method_missing(method, *args, &block)
  if method.to_s =~ /(_changed\?|_change|_will_change!|_was)$/
    method_suffix = $1
    key = method.to_s.gsub(method_suffix, '')
    
    if key_names.include?(key)
      case method_suffix
        when '_changed?'
          key_changed?(key)
        when '_change'
          key_change(key)
        when '_will_change!'
          key_will_change!(key)
        when '_was'
          key_was(key)
      end
    else
      super
    end
  else
    super
  end
end

Instance Method Details

#changedObject

List of keys with unsaved changes.

person.changed # => []
person.name = 'bob'
person.changed # => ['name']


37
38
39
# File 'lib/mongo_mapper/dirty.rb', line 37

def changed
  changed_keys.keys
end

#changed?Boolean

Returns:



29
30
31
# File 'lib/mongo_mapper/dirty.rb', line 29

def changed?
  !changed_keys.empty?
end

#changesObject

Map of changed attrs => [original value, new value].

person.changes # => {}
person.name = 'bob'
person.changes # => { 'name' => ['bill', 'bob'] }


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

def changes
  changed.inject({}) { |h, attribute| h[attribute] = key_change(attribute); h }
end

#initialize(attrs = {}) ⇒ Object



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

def initialize(attrs={})
  super(attrs)
  changed_keys.clear unless new?
end

#save(*args) ⇒ Object

Attempts to save the record and clears changed keys if successful.



55
56
57
58
59
60
# File 'lib/mongo_mapper/dirty.rb', line 55

def save(*args)
  if status = super
    changed_keys.clear
  end
  status
end

#save!(*args) ⇒ Object

Attempts to save! the record and clears changed keys if successful.



63
64
65
66
67
# File 'lib/mongo_mapper/dirty.rb', line 63

def save!(*args)
  status = super
  changed_keys.clear
  status
end