Skip to content

Instantly share code, notes, and snippets.

@byroot
Created February 11, 2011 18:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save byroot/822751 to your computer and use it in GitHub Desktop.
Save byroot/822751 to your computer and use it in GitHub Desktop.
module Mongoid
module Mutation
def as(klass, extra_attributes={})
klass.new(attributes_for(klass, extra_attributes)).tap do |mutation|
mutation.new_record = new_record?
mutation.send(:modifications)['_type'] = [self._type, klass.name]
end
end
def as!(klass, extra_attributes={})
new_attributes = Hash[attributes_for(klass, extra_attributes, false).map{ |k, v| [k, [nil, v]]}].merge({'_type' => [self._type, klass.name]})
send(:modifications).update(new_attributes)
save!
klass.find(self._id)
end
private
def attributes_for(klass, extra_attributes, new_record=true)
shared_fields = klass.fields.keys
shared_fields << '_id' if new_record
shared_attributes = self.attributes.slice(*shared_fields)
shared_attributes.merge(extra_attributes)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment