Skip to content

Instantly share code, notes, and snippets.

@jlecour
Created May 23, 2011 11:09
Show Gist options
  • Save jlecour/986555 to your computer and use it in GitHub Desktop.
Save jlecour/986555 to your computer and use it in GitHub Desktop.
Touch plugin for MongoMapper
# encoding: UTF-8
module MongoMapper
module Plugins
module Touch
extend ActiveSupport::Concern
module InstanceMethods
def touch(key = :updated_at)
raise "InvalidKey" unless self.key_names.include?(key.to_s)
self.set(key => Time.now.utc)
true
end
end
end
end
end
@jlecour
Copy link
Author

jlecour commented May 23, 2011

It's the first attempt to make the touchmethod (from ActiveRecord) available in Mongo documents.

The idea is to be able to update a Document's date field without updating the whole Document, without any validations or callbacks, … just like in ActiveRecord.

I don't know if it's the best way to do this, but right now it's dead simple and it works with a first level key.

@jlecour
Copy link
Author

jlecour commented May 23, 2011

the "setter" doesn't work if the key doesn't exist yet

@jlecour
Copy link
Author

jlecour commented May 23, 2011

Thanks to Kevin Lawver from the MongoMapper Google Group (http://groups.google.com/group/mongomapper/browse_thread/thread/62faeebcb0584f47) we can do this without using the driver, but the set method of MongoMapper's API.

@jlecour
Copy link
Author

jlecour commented May 23, 2011

But I prefer to store Dates/Times in UTC

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment