在MVC模型中,Cookbook类应该被视为模型,用于管理与食谱相关的数据。因此,您可以创建一个Cookbook模型类,并在其中定义各种方法来管理与食谱相关的数据。在控制器中,您可以将这些方法用于呈现视图和处理用户输入。这样,您可以将视图从模型中解耦,并提高应用程序的可维护性。
以下是一个简单的基于MVC模型的Ruby Cookbook类设置示例:
cookbook.rb (模型类)
class Cookbook
attr_accessor :recipes
def initialize
@recipes = []
end
def add_recipe(recipe)
@recipes << recipe
end
def remove_recipe(recipe)
@recipes.delete(recipe)
end
def find_recipe(query)
@recipes.select { |recipe| recipe.include?(query) }
end
end
recipes_controller.rb (控制器类)
class RecipesController
def initialize(cookbook)
@cookbook = cookbook
end
def list
@recipes = @cookbook.recipes
end
def add(name, ingredients, instructions)
recipe = Recipe.new(name, ingredients, instructions)
@cookbook.add_recipe(recipe)
end
def remove(name)
recipe = @cookbook.find_recipe(name)
@cookbook.remove_recipe(recipe)
end
def search(query)
@recipes = @cookbook.find_recipe(query)
end
end
views.rb (视图类)
class Views
def list(recipes)
recipes.each do |recipe|
puts recipe.name
puts recipe.ingredients
puts recipe.instructions
end
end
def add
# 显示添加新食谱的窗口
end
def remove
# 显示删除指定食谱的窗口
end
def search
# 显示搜索食谱的窗口
end
end
在这个设置中,Cookbook类用于管理所有与食谱相关的数据。RecipesController类用于处理来自用户的请求,并在需要时使用Cookbook类中定义的方法。Views类用于呈现视图和与用户交互。这种设置有助于简化代码,并提高应用程序的可维护性。