class Gizmo::Modify

Public Instance Methods

call(criteria, id, attrs, update_strategy=nil) click to toggle source

Modify a single item using the provided criteria.

@param [Mongoid::Criteria] criteria the criteria to use for finding the item to update @param [String, Moped::BSON::ObjectId] id the ID of the item being updated @param [Hash] attrs the attributes used to update an existing instance @param [Proc] update_strategy The default update strategy does a mass update of attributes, which is not always ideal. A block can be given which will be passed two parameters: the item to update and the attributes. The block must return the data it wishes to send back in the response.

@return [Gizmo::Response]

# File lib/gizmo/modify.rb, line 15
def call(criteria, id, attrs, update_strategy=nil)
  attrs.delete '_id'

  response = create_response
  #TODO: refactor this pattern
  if criteria.is_a? Mongoid::Criteria
    item = criteria.where(:id=>id).first
    raise Mongoid::Errors::DocumentNotFound.new(criteria.klass, :id=>id) if item.nil?
  else
    item = criteria.find id
  end

  if update_strategy.nil?
    item.update_attributes!(attrs)
  else
    item = update_strategy.call item, attrs
  end
  response.data = item
  response
end