Skip to content

Instantly share code, notes, and snippets.

@asanger
Created December 10, 2014 15:25
Show Gist options
  • Save asanger/4e6a93362a172dfa2e62 to your computer and use it in GitHub Desktop.
Save asanger/4e6a93362a172dfa2e62 to your computer and use it in GitHub Desktop.
List dirty model changes in a human readable format
# Probably not the ideal way to handle this, but it should output the changes made to a model after it's been updated.
# If you want to grab the changes before the model is saved, change '.previous_changes' to '.changes'
# Hash contains a hash of changes in this following format:
# {attribute_name_1 => [old_value, new_value], attribute_name_2 => [old_value, new_value]}
change_hash = your_changed_object.previous_changes
# If we don't want to include the "updated_at" (or some other attributes), delete their keys from the hash
change_hash.delete("updated_at")
# Output all of the changes to a string in sentence form ("Changed name from 'Bob' to 'Joe'")
changes = change_hash.map{ |k,v| "changed '#{k}' from '#{v[0]}' to '#{v[1]}'" }.to_sentence
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment