1
0

Displaying errors for uncomputable formulas in nutrients view

This commit is contained in:
cryptogopher 2020-03-21 00:38:39 +01:00
parent 9a79e8fa55
commit c3b783e942
5 changed files with 22 additions and 7 deletions

View File

@ -1,6 +1,13 @@
module BodyTrackersHelper
def format_value(value)
amount, unitname = value
amount.nil? ? '-' : "#{amount} [#{unitname || '-'}]"
case
when amount.nil?
'-'
when amount.nan?
'?'
else
"#{amount} [#{unitname || '-'}]"
end
end
end

View File

@ -30,9 +30,6 @@ class Formula < ActiveRecord::Base
args << get_binding(quantities, args, length).eval(code)
end
args.last.map { |v| [v, nil] }
rescue Exception => e
puts e.message
[[nil, nil]] * length
end
private

View File

@ -4,6 +4,8 @@
<% if @ingredients.any? %>
<%= render partial: 'ingredients/options' %>
<%= error_messages_for *@quantities.map { |q| q.formula } %>
<table class="nutrients list odd-even">
<thead>
<tr>

View File

@ -42,6 +42,8 @@ en:
disallowed_keyword: 'includes disallowed keyword: "%{keyword}"'
disallowed_method: 'includes disallowed method call: "%{method}"'
unknown_quantity: 'contains undefined quantity: %{quantity}'
computation_failed: 'computation failed for "%{quantity}": %{description}
(%{count} values missing)'
body_trackers:
index:
heading: 'Summary'

View File

@ -67,7 +67,8 @@ module BodyTracking
q, deps = unchecked_q.shift
# quantity not computable (no formula) or not requiring calculation/computed
if !q.formula || !q.formula.valid? || (subitems[q.name].length == items.count)
if !q.formula || q.formula.errors.any? || !q.formula.valid? ||
(subitems[q.name].length == items.count)
completed_q[q.name] = subitems.delete(q.name) { {} }
completed_q[q.name].default = [nil, nil]
next
@ -85,8 +86,14 @@ module BodyTracking
output_ids = items.select { |i| subitems[q.name][i.id].nil? }.map(&:id)
input_q = q.formula.quantities
inputs = input_q.map { |i_q| [i_q, completed_q[i_q.name].values_at(*output_ids)] }
q.formula.calculate(inputs.to_h).each_with_index do |result, index|
subitems[q.name][output_ids[index]] = result
begin
calculated = q.formula.calculate(inputs.to_h)
rescue Exception => e
output_ids.each { |oid| subitems[q.name][oid] = BigDecimal::NAN }
q.formula.errors.add(:code, :computation_failed,
{quantity: q.name, description: e.message, count: output_ids.size})
else
output_ids.each_with_index { |oid, idx| subitems[q.name][oid] = calculated[idx] }
end
unchecked_q.unshift([q, deps])
next