Guest User

Untitled

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