-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecipe.rb
78 lines (69 loc) · 1.63 KB
/
recipe.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
require 'yaml'
class Recipe
class << self
def describe(&block)
if block_given?
instance_eval(&block)
else
"Pass a block"
end
end
def recipe(*args, &block)
if block_given?
data_holder = DataHolder.new
args.each do |arg|
data_holder.recipe_name = arg.downcase
data_holder.instance_eval(&block)
end
data_holder.save_recipe
else
raise NotImplementedError
end
end
def for(recipe_name)
data_holder = DataHolder.new
data_holder.recipe_name = recipe_name
data_holder.find_formula
end
end
class DataHolder
attr_accessor :recipe_name
def initialize
@recipe_struct = Struct.new(:name, :ingredients)
@ingredients = []
end
def ingredient(ingredient_name)
@ingredients << ingredient_name
end
def save_recipe
begin
file = File.open('recipe_data.yml', 'a+')
data = [recipe_name, @ingredients].to_yaml
file.write(data)
rescue IOError => e
puts e
ensure
file.close
end
'Recipe save success'
end
def find
unless recipe_name.nil?
data = YAML.load_stream(File.read('./recipe_data.yml'))
data.each do |elem|
return elem if elem[0] == recipe_name.downcase
end
else
raise StandardError => e
puts "Error on name: #{e}"
end
end
def find_formula
recipe = self.find
recipe_formula = @recipe_struct.new
recipe_formula.name = recipe[0]
recipe_formula.ingredients = recipe[1]
recipe_formula
end
end
end