Skip to content

Instantly share code, notes, and snippets.

@GGrassiant
Created December 23, 2021 19:38
Show Gist options
  • Save GGrassiant/e7bcf38311c4218e47540d3d760f77c2 to your computer and use it in GitHub Desktop.
Save GGrassiant/e7bcf38311c4218e47540d3d760f77c2 to your computer and use it in GitHub Desktop.
Meal Planning
class Api::V1::MealsController < ApplicationController
def weekly_meals
items_by_category = Item.all.group_by(&:category)
counter = {}
temp = {
Monday: {
lunch: [],
dinner: []
},
Tuesday: {
lunch: [],
dinner: []
},
Wednesday: {
lunch: [],
dinner: []
},
Thursday: {
lunch: [],
dinner: []
},
Friday: {
lunch: [],
dinner: []
}
}
@meals = Day.all.each_with_object(temp) do |day, acc|
acc[day.name.to_sym][:lunch] = items_by_category.values.each_with_object([]) do |meals, memo|
picked_meal = meals.sample
counter[picked_meal] = counter[picked_meal].nil? ? 1 : 2
memo.push(picked_meal)
items_by_category[picked_meal.category] -= [picked_meal] if counter[picked_meal] > 1
memo
end
acc[day.name.to_sym][:dinner] = items_by_category.values.each_with_object([]) do |meals, memo|
picked_meal = meals.sample
counter[picked_meal] = counter[picked_meal].nil? ? 1 : 2
memo.push(picked_meal)
items_by_category[picked_meal.category] -= [picked_meal] if counter[picked_meal] > 1
memo
end
acc
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment