Guest User

Untitled

a guest
May 8th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.94 KB | None | 0 0
  1. require 'dm-core'
  2.  
  3. DataMapper::Logger.new(STDOUT, :debug)
  4. DataMapper.setup :default,
  5. :adapter => 'postgres',
  6. :host => 'localhost',
  7. :port => 5432,
  8. :username => 'dofus_treasury',
  9. :password => 'dofus_treasury',
  10. :database => 'dofus_treasury'
  11.  
  12.  
  13. # Items are identified by names, for example, Bread
  14. # A recipe has one product item, and a few ingredient items each dosed with a
  15. # quantity, for example, Bread = 2 Flour + 1 Yeast + 1 Water
  16. # A dosage is to used to hold one ingredient item and its quantity
  17.  
  18. class Item
  19. include DataMapper::Resource
  20.  
  21. property :name, String, :key => true
  22. has n, :dosages
  23.  
  24. has n, :producing_recipes, :class_name => 'Recipe',
  25. :child_key => [:product_name]
  26. has n, :consuming_recipes, :class_name => 'Recipe',
  27. :through => :dosages,
  28. :remote_relationship_name => :recipe
  29.  
  30. def self.named(name)
  31. first_or_create(:name => name)
  32. end
  33. end
  34.  
  35. class Dosage
  36. include DataMapper::Resource
  37.  
  38. property :quantity, Integer
  39. property :item_name, String, :key => true
  40. property :recipe_id, Integer, :key => true
  41.  
  42. belongs_to :item
  43. belongs_to :recipe
  44. end
  45.  
  46. class Recipe
  47. include DataMapper::Resource
  48.  
  49. property :id, Serial
  50. belongs_to :product, :class_name => 'Item',
  51. :child_key => [:product_name]
  52. has n, :dosages
  53. has n, :ingredients, :class_name => 'Item',
  54. :through => :dosages,
  55. :remote_relationship_name => :item
  56.  
  57. # return recipe with the given product and ingredient/quantities,
  58. # creating if not existing
  59. #
  60. # Recipe.defined( Item.named('Bread'),
  61. # Item.named('Flour') => 2,
  62. # Item.named('Yeast') => 1,
  63. # Item.named('Water') => 1 )
  64. def self.defined(product, ingredients_and_quantities)
  65. # FIXME the current implementation does not check for existing recipes with
  66. # the given product, ingredients and quantities; instead it assumes
  67. # that recipes are unique by product
  68. # first(:product => product,
  69. # :ingredients => ingredienst_and_quantities.keys,
  70. # :dosages.all? {|d| ingredients_and_quantities[d.item] == d.quantity}
  71. # # how to translate to query?
  72. # ) \
  73. (product.producing_recipes || []).first or
  74. begin
  75. r = Recipe.new
  76. r.product = product
  77. ingredients_and_quantities.each_pair do |ingredient, quantity|
  78. r.dosages << Dosage.new(:quantity => quantity, :item => ingredient)
  79. end
  80. r
  81. end
  82. end
  83. end
  84.  
  85. DataMapper.auto_upgrade!
Add Comment
Please, Sign In to add comment