Guest User

Untitled

a guest
Jul 15th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.83 KB | None | 0 0
  1. require 'dm-core'
  2.  
  3. # An item is identified by a name, for example, Bread
  4. class Item
  5. include DataMapper::Resource
  6.  
  7. property :name, String, :key => true, :length => 100
  8. has n, :stacks
  9.  
  10. # recipes which produce this item
  11. has n, :producing_recipes, :model => 'Recipe',
  12. :child_key => [:product_name]
  13.  
  14. # recipes which use this item as an ingredient
  15. def consuming_recipes
  16. Recipe.all.select do |recipe|
  17. recipe.ingredients.any? do |ingredient|
  18. ingredient == self
  19. end
  20. end
  21. end
  22.  
  23. # items which are products of consuming_recipes
  24. def derivatives
  25. consuming_recipes.map(&:product)
  26. end
  27.  
  28. # items which are ingredients in producing_recipes
  29. has n, :materials, :model => 'Item',
  30. :through => :producing_recipes,
  31. :remote_relationship_name => :items,
  32. :child_key => [:item_name]
  33. end
  34.  
  35.  
  36. # A stack contains a number of the same item
  37. class Stack
  38. include DataMapper::Resource
  39. property :id, Serial
  40. property :quantity, Integer
  41. belongs_to :item
  42. belongs_to :bag
  43. end
  44.  
  45. # A bag contains a number of stacks
  46. class Bag
  47. include DataMapper::Resource
  48. property :id, Serial
  49. property :type, Discriminator
  50. has n, :stacks
  51. has n, :items, :through => :stacks
  52.  
  53. def [](item, default=0)
  54. if stack = stacks.first('item.name' => item.name)
  55. stack.quantity
  56. else
  57. default
  58. end
  59. end
  60.  
  61. def []=(item, quantity)
  62. if stack = stacks.first('item.name' => item.name)
  63. stack.quantity = quantity
  64. else
  65. stacks << Stack.new(:item_name => item.name, :quantity => quantity)
  66. end
  67. end
  68.  
  69. def quantities
  70. {}.tap do |ret|
  71. stacks.each {|stack| ret[stack.item] = stack.quantity}
  72. end
  73. end
  74. end
  75.  
  76. # A recipe has one product item, and a few ingredient items each with a
  77. # quantity, for example, Bread = 2 Flour + 1 Yeast + 1 Water
  78. class Recipe < Bag
  79. # include DataMapper::Resource
  80. belongs_to :product, :model => 'Item',
  81. :child_key => [:product_name]
  82. alias_method :ingredients, :items
  83. end
  84.  
  85. # An identity is identified by an url, and has an inventory
  86. class Identity
  87. include DataMapper::Resource
  88.  
  89. property :url, String, :key => true, :length => 100
  90. has 1, :inventory
  91. has n, :items, :through => :inventory
  92. end
  93.  
  94. # An inventory has a number of different items, and belongs to an identity
  95. class Inventory < Bag
  96. # include DataMapper::Resource
  97. belongs_to :identity
  98. end
Add Comment
Please, Sign In to add comment