module AWS::Record::DirtyTracking

Provides a way to track changes in your records.

my_book = Book['bookid']

my_book.changed? #=> false
my_book.title #=> "My Book"
my_book.title = "My Awesome Book"
my_book.changed? #=> true

You can inspect further and get a list of changed attributes

my_book.changed #=> ['title']

Or you can get a more detailed description of the changes. {changes} returns a hash of changed attributes (keys) with their old and new values.

my_book.changes
#=> { 'title' => ['My Book', 'My Awesome Book']

For every configured attribute you also get a handful of methods for inspecting changes on that attribute. Given the following attribute:

string_attr :title

You can now call any of the following methods:

* title_changed?
* title_change
* title_was
* reset_title!
* title_will_change!

Given the title change from above:

my_book.title_changed? #=> true
my_book.title_change #=> ['My Book', 'My Awesome Book']
my_book.title_was #=> ['My Book']

my_book.reset_title!
my_book.title #=> 'My Book'

In-Place Editing

Dirty tracking works by comparing incoming attribute values upon assignment against the value that was there previously. If you use functions against the value that modify it (like gsub!) you must notify your record about the coming change.

my_book.title #=> 'My Book'
my_book.title_will_change!
my_book.title.gsub!(%rMy/, 'Your')
my_book.title_change #=> ['My Book', 'Your Book']

Partial Updates

Dirty tracking makes it possible to only persist those attributes that have changed since they were loaded. This speeds up requests against AWS when saving data.

Public Instance Methods

changed() click to toggle source

Returns an array of attribute names that have changes.

book.changed #=> []
person.title = 'New Title'
book.changed #=> ['title']

@return [Array] Returns an array of attribute names that have

unsaved changes.
# File lib/aws/record/dirty_tracking.rb, line 108
def changed
  orig_values.keys
end
changed?() click to toggle source

Returns true if this model has unsaved changes.

b = Book.new(:title => 'My Book')
b.changed?
#=> true

New objects and objects freshly loaded should not have any changes:

b = Book.new
b.changed?      #=> false

b = Book.first
b.changed?      #=> false

@return [Boolean] Returns true if any of the attributes have

unsaved changes.
# File lib/aws/record/dirty_tracking.rb, line 96
def changed?
  !orig_values.empty?
end
changes() click to toggle source

Returns the changed attributes in a hash. Keys are attribute names, values are two value arrays. The first value is the previous attribute value, the second is the current attribute value.

book.title = 'New Title'
book.changes
#=> { 'title' => ['Old Title', 'New Title'] }

@return [Hash] Returns a hash of attribute changes.

# File lib/aws/record/dirty_tracking.rb, line 121
def changes
  changed.inject({}) do |changes, attr_name|
    changes[attr_name] = attribute_change(attr_name)
    changes
  end
end