Class: Gizmo::Modify

Inherits:
BaseOperation show all
Defined in:
lib/gizmo/modify.rb

Instance Attribute Summary

Attributes inherited from BaseOperation

#context

Instance Method Summary collapse

Methods inherited from BaseOperation

#create_response, #default_status, #initialize, #set_response_headers

Constructor Details

This class inherits a constructor from Gizmo::BaseOperation

Instance Method Details

#call(criteria, id, attrs, update_strategy = nil) ⇒ Gizmo::Response

Modify a single item using the provided criteria.

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.



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# 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