Skip to content

Instantly share code, notes, and snippets.

@scalabl3
Created July 23, 2012 00:09
Show Gist options
  • Save scalabl3/3161434 to your computer and use it in GitHub Desktop.
Save scalabl3/3161434 to your computer and use it in GitHub Desktop.
Automatic Versioning
#Current key is always the most current version of the document. Everytime it gets modified, we increase the count of versions and save current couchbase version of document #as a version with current_version - 1 appended.
#So:
#create_doc
#mydoc = { "txt" => "my first text" }
#replace_doc
#mydoc::version = 2
#mydoc::version::1 = { "txt" => "my_first_text", "auto_version" => 1, "auto_version_stamp" => "6/28/2012 20:35" }
#mydoc = { "txt" => "my_second_text", "auto_version" => 2 }
#replace_doc
#mydoc::version = 3
#mydoc::version::1 = { "txt" => "my_first_text", "auto_version" => 1, "auto_version_stamp" => "6/28/2012 20:35" }
#mydoc::version::2 = { "txt" => "my_second_text", "auto_version" => 2, "auto_version_stamp" => "6/28/2012 20:40" }
#mydoc = { "txt" => "my third text", "auto_version" => 3 }
#replace_doc
#mydoc::version = 4
#mydoc::version::1 = { "txt" => "my_first_text", "auto_version" => 1, "auto_version_stamp" => "6/28/2012 20:35" }
#mydoc::version::2 = { "txt" => "my_second_text", "auto_version" => 2, "auto_version_stamp" => "6/28/2012 20:40" }
#mydoc::version::3 = { "txt" => "my_third_text", "auto_version" => 3, "auto_version_stamp" => "6/28/2012 20:45" }
#mydoc = { "txt" => "my fourth text", "auto_version" => 4 }
def replace_document ( key, value, args = {} )
if args.has_key_and_value?(:auto_version)
version_tracker_key = key + "::version"
initialize_document ( version_tracker_key, 1 )
current_version = increment_atomic_count(version_tracker_key)
# if the value is a Map then add the version to the doc
if value.is_a? Map
value[:auto_version] = current_version
end
# if there are previous versions, save current existing doc as a version, and straight key will be current version
if current_version > 1
doc = get_document(key)
doc[:version_stamp] = Time.now.getUtc
doc[:auto_version] = current_version - 1
add_document(key + "::version::#{current_version - 1}", doc)
end
end
COUCH.replace(key, value)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment