Method: Mongomatic::Modifiers#pop_last

Defined in:
lib/mongomatic/modifiers.rb

#pop_last(field, update_opts = {}, safe = false) ⇒ Object

MongoDB equivalent: { $pop : { field : 1 } }
Removes the last element in an array (ADDED in 1.1) user.pop_last("friend_ids")



233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/mongomatic/modifiers.rb', line 233

def pop_last(field, update_opts={}, safe=false)
  mongo_field = field.to_s
  field, hash = hash_for_field(mongo_field)
  
  unless hash[field].nil? || hash[field].is_a?(Array)
    raise(UnexpectedFieldType)
  end
  
  op = { "$pop" => { mongo_field => 1 } }
  
  res = true
  safe == true ? res = update!(update_opts, op) : update(update_opts, op)
  
  if res
    hash[field] ||= []
    hash[field].pop
    true
  end
end