Created
April 30, 2012 00:58
-
-
Save burtlo/2554546 to your computer and use it in GitHub Desktop.
Trivial Example of a the Recipe creation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Measurements | |
def cup | |
self * 48 | |
end | |
alias_method :cups, :cup | |
def tsp ; self ; end | |
alias_method :tsps, :tsp | |
def dozen ; self * 12 ; end | |
alias_method :dozens, :dozen | |
end | |
class Fixnum | |
include Measurements | |
end | |
class Float | |
include Measurements | |
end | |
class Ingredient | |
attr_reader :name, :amount, :preparation | |
def initialize(name,amount,preparation = "") | |
@name = name | |
@amount = amount | |
@preparation = preparation | |
end | |
end | |
class Cookbook | |
attr_reader :recipes | |
def self.recipe(name,&block) | |
@recipes ||= [] | |
recipe = Recipe.new(name) | |
recipe.instance_eval(&block) | |
@recipes << recipe | |
recipe | |
end | |
end | |
module MarkdownRenderer | |
def to_markdown | |
formatted_ingredients = @ingredients.map do |name,i| | |
"* #{i.amount} tsps of #{i.name}" | |
end.join("\n") | |
formatted_instructions = @instructions.map {|i| "* #{i}" }.join("\n") | |
"# #{name}\n\n" + | |
"#{serves}\n\n" + | |
"## Ingredients\n\n" + | |
formatted_ingredients + | |
"\n\n## Instructions\n\n" + | |
formatted_instructions | |
end | |
end | |
class Recipe | |
attr_reader :name | |
def initialize(name) | |
@name = name | |
end | |
attr_reader :ingredients | |
def ingredient(name,amount,preparation = "") | |
#puts "Adding #{name} in amount #{amount} with preparation #{preparation}" | |
@ingredients ||= {} | |
@ingredients[name] = Ingredient.new name, amount, preparation | |
end | |
attr_reader :instructions | |
def instruction(message) | |
#puts "Instruction: #{message}" | |
@instructions = [] | |
@instructions << message | |
end | |
def serves(amount = nil,unit = nil) | |
if amount and unit | |
@serves = "Serving up #{amount} of #{unit}! Hot and Fresh!" | |
else | |
@serves | |
end | |
end | |
def half | |
0.5 | |
end | |
include MarkdownRenderer | |
end | |
cookie_recipe = Cookbook.recipe "Chocolate Chip Cookies" do | |
ingredient "butter", 1.cup, "softened" | |
ingredient "salt", half.tsp | |
ingredient "semisweet chocolate chips", 2.cups | |
instruction "Preheat oven to 350 degrees F (175 degrees C)." | |
serves 4.dozen, "cookies" | |
end | |
puts cookie_recipe.to_markdown |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment