Created
December 11, 2011 04:39
-
-
Save masom/1458380 to your computer and use it in GitHub Desktop.
This file contains 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
#TODO: compute recipe food values | |
namespace :recipe do | |
desc "Imports JSON recipes" | |
task :json_import, [:source, :basepath] => :environment do |task,args| | |
require 'rubygems' | |
require 'json' | |
def import_recipe(source, raw) | |
recipe = Recipe.new | |
recipe.name = raw['name'] | |
recipe.source_id = raw['id'] | |
recipe.notes = raw['notes'] || "" | |
recipe.source = source | |
recipe.orig_servings = raw['servings'] || "" | |
recipe.orig_duration = raw['time'] || "" | |
raw['steps'].each_index do |i| | |
step = RecipeStep.new | |
step.description = raw['steps'][i] | |
step.rank = i | |
recipe.steps << step | |
end | |
raw['ingredients'].each do |i| | |
ingredient = RecipeIngredient.new | |
ingredient.original = i | |
recipe.ingredients << ingredient | |
#Ingredient processing is done at a later stage | |
end | |
raise ActiveRecord::RecordInvalid if not recipe.save! | |
end | |
path = "#{args[:basepath]}/#{args[:source]}" | |
raise RuntimeError, "Directory #{path} does not exists." if not Dir.exist? path | |
Dir.glob("#{path}/*.json").each do |f| | |
source_file = "#{path}/#{f}" | |
begin | |
raw = JSON.parse source_file | |
next if items.include? raw['id'] | |
imported = import_recipe source, raw | |
rescue ActiveRecord::RecordInvalid => e | |
puts "An error occured while importing `#{source_file}`: #{e}" | |
end | |
puts "Recipe #{f} could not be imported." if not imported | |
items = Recipe.find(:all, :select=> "id") | |
puts items | |
abort("DER") | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment