From 88e5cb430afc4e03d5934bb8eaff0ca9bccb846c Mon Sep 17 00:00:00 2001 From: cryptogopher Date: Wed, 6 Nov 2019 23:11:58 +0100 Subject: [PATCH] Quantity computation from formula --- app/models/ingredient.rb | 4 +++- app/models/quantity.rb | 11 ++++++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/app/models/ingredient.rb b/app/models/ingredient.rb index 5547f90..45eb478 100644 --- a/app/models/ingredient.rb +++ b/app/models/ingredient.rb @@ -71,7 +71,9 @@ class Ingredient < ActiveRecord::Base i, input_q.map do |i_q| nutrient_data = (completed_q[i_q.name] || nutrients[i_q.name])[i.id] - [i_q.name, (nutrient_data || [nil, nil])[0]] + # FIXME: result for computation with nil values (substituted with 0s) + # should be marked as not precise + [i_q.name, (nutrient_data || [0, nil])[0]] end.to_h ] end diff --git a/app/models/quantity.rb b/app/models/quantity.rb index 7ed3757..08077f8 100644 --- a/app/models/quantity.rb +++ b/app/models/quantity.rb @@ -70,6 +70,15 @@ class Quantity < ActiveRecord::Base end def calculate(inputs) - inputs.map { |i, values| [i, 1.0] } + paramed_formula = Ripper.lex(formula).map do |*, ttype, token| + QUANTITY_TTYPES.include?(ttype) ? "params['#{token}']" : token + end.join + inputs.map { |i, values| [i, get_binding(values).eval(paramed_formula)] } + end + + private + + def get_binding(params) + binding end end