Guest User

Untitled

a guest
May 25th, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. gem "mongo", "1.0"
  2. gem "bson_ext", "1.0"
  3. gem "mongo_ext", "0.19.3"
  4. gem "mongo_mapper", "0.7.5"
  5.  
  6. require 'mongo_mapper'
  7.  
  8. MongoMapper.database = 'shopping'
  9.  
  10. class List
  11. include MongoMapper::Document
  12. key :name, String
  13. many :items
  14.  
  15. def destroy_item!(item_id)
  16. items.delete_if do |i|
  17. i.id == item_id
  18. end
  19. save
  20. end
  21. end
  22.  
  23. class Item
  24. include MongoMapper::EmbeddedDocument
  25. key :price, Float
  26. end
  27.  
  28. # Setup prop
  29. list = List.new({:name => 'groceries'})
  30. cheap_item = Item.new({:price => 5.00})
  31. expensive_item = Item.new({:price => 3.00})
  32.  
  33. list.items = [] << cheap_item << expensive_item
  34. list.save
  35.  
  36. puts "Is item count 2: #{list.items.count == 2}"
  37.  
  38. # Deletion by object id directly works fine
  39. list.destroy_item!(expensive_item.id)
  40. puts "Is item count 1: #{list.items.count == 1}"
  41.  
  42. # However if we send the object id as a string we get into trouble
  43. list.destroy_item!(cheap_item.id.to_s)
  44. puts "Is item count 0: #{list.items.count == 0}"
  45.  
  46. # This matters a fair bit when you are using restful resources over the web
  47. # to handle the removal and updating of persisted objects.
  48. #
  49. # For example using sinatra we can handle a post to the
  50. # resource /items/:list_id/:item_id/delete
  51. #
  52. # Rack then makes :item_id available in our params hash as a string,
  53. # and from there you can get easily caught out as in the example above.
  54. #
  55. # I don't mind working around this with my model code - it might not even be a bug
  56. # in mongo mapper bug perse. Just a bit assyemtric considering we can successfully
  57. # query for an object with find with the id represented as a string. The same
  58. # should apply to equivalence tests on object ids.
Add Comment
Please, Sign In to add comment