Hi,
I am writing an application that deals with items and recipes of a
game. I have detailed explanation in the code below, but the main
problem I'm having is that the recipe resource "has" a product item,
and multiple dosages which are basically (quantity, item) tuples, and
I want to make sure that no two recipes with identical product and set
of ingredient dosages are created.
The method I'm having problem with is self.defined under class Recipe.
Thanks for any help.
require 'dm-core'
# Items are identified by names, for example, Bread
# A recipe has one product item, and a few ingredient items each dosed
with a
# quantity, for example, Bread = 2 Flour + 1 Yeast + 1 Water
# A dosage is to used to hold one ingredient item and its quantity
class Item
include DataMapper::Resource
property :name, String, :key => true
has n, :dosages
def self.named(name)
first_or_create(:name => name)
end
end
class Dosage
include DataMapper::Resource
property :id, Serial
property :quantity, Integer
belongs_to :item
belongs_to :recipe
end
class Recipe
include DataMapper::Resource
property :id, Serial
has 1, :product, :class_name => 'Item'
has n, :dosages
has n, :ingredients, :class_name => 'Item', :through => :dosages,
:remote_relationship_name => :item
# return recipe with the given product and ingredient/quantities,
# creating if not existing
#
# Recipe.defined( Item.named('Bread'),
# Item.named('Flour') => 2
# Item.named('Yeast') => 1
# Item.named('Water') => 1 )
def self.defined(product, ingredients_and_quantities)
# how do I find an existing recipe with the given product,
# and quantities and ingredients?
first(:product => product,
:ingredients => ingredienst_and_quantities.keys,
:dosages.all? {|d| ingredients_and_quantities[d.item] ==
d.quantity}
# how to translate to query?
) or
begin
r = Recipe.new
r.product = product
quantities_and_ingredients.each_pair do |ingredient, quantity|
r.dosages << Dosage.new(:quantity => quantity, :item =>
ingredient)
end
r
end
end
end
DataMapper.auto_migrate!
Recipe.defined( Item.named('Bread'),
Item.named('Flour') => 2
Item.named('Yeast') => 1
Item.named('Water') => 1 )
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"DataMapper" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/datamapper?hl=en
-~----------~----~----~----~------~----~------~--~---