From c71e356195bd095c50e730eb7985ad7a3fe3aa47 Mon Sep 17 00:00:00 2001 From: Dan Elbert Date: Tue, 5 Jul 2016 16:48:59 -0500 Subject: [PATCH] Fixed yield parser; fixed N+1 query issue --- app/controllers/recipes_controller.rb | 2 +- lib/yield_parser.rb | 14 +++++++++----- spec/lib/yield_parser_spec.rb | 2 ++ 3 files changed, 12 insertions(+), 6 deletions(-) diff --git a/app/controllers/recipes_controller.rb b/app/controllers/recipes_controller.rb index 1dbd94e..753ea45 100644 --- a/app/controllers/recipes_controller.rb +++ b/app/controllers/recipes_controller.rb @@ -98,7 +98,7 @@ class RecipesController < ApplicationController private # Use callbacks to share common setup or constraints between actions. def set_recipe - @recipe = Recipe.includes(recipe_ingredients: :ingredient).find(params[:id]) + @recipe = Recipe.includes(recipe_ingredients: {ingredient: :ingredient_units }).find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. diff --git a/lib/yield_parser.rb b/lib/yield_parser.rb index 3d7cb24..8c30cbc 100644 --- a/lib/yield_parser.rb +++ b/lib/yield_parser.rb @@ -4,15 +4,19 @@ class YieldParser def self.parse(yield_string) - match = /(\d+(?:\.\d*)?)\s*(\w[\w\s]*)?/.match(yield_string) + begin + vu = UnitConversion::parse(yield_string) + rescue UnparseableUnitError + vu = nil + end case - when match.nil? + when vu.nil? nil - when match[2] - Result.new(match[1].to_f, match[2].strip.singularize) + when vu.unit.nil? + Result.new(vu.raw_value.to_f, 'each') else - Result.new(match[1].to_f, 'each') + Result.new(vu.raw_value.to_f, vu.unit.to_s.singularize) end end diff --git a/spec/lib/yield_parser_spec.rb b/spec/lib/yield_parser_spec.rb index 5298251..02c90f7 100644 --- a/spec/lib/yield_parser_spec.rb +++ b/spec/lib/yield_parser_spec.rb @@ -7,6 +7,8 @@ RSpec.describe YieldParser do expect(YieldParser.parse('4 servings')).to eq YieldParser::Result.new(4.0, 'serving') expect(YieldParser.parse('3 pancakes')).to eq YieldParser::Result.new(3.0, 'pancake') expect(YieldParser.parse('13.5 large croutons')).to eq YieldParser::Result.new(13.5, 'large crouton') + + expect(YieldParser.parse('1 1/2 pints')).to eq YieldParser::Result.new(1.5, 'pint') end end \ No newline at end of file