2016-01-31 00:00:32 -06:00
|
|
|
class CalculatorController < ApplicationController
|
|
|
|
|
|
|
|
def index
|
|
|
|
|
|
|
|
end
|
|
|
|
|
|
|
|
def calculate
|
|
|
|
input = params[:input]
|
|
|
|
output_unit = params[:output_unit]
|
2018-09-12 17:17:15 -05:00
|
|
|
ingredient_id = params[:ingredient_id]
|
|
|
|
ingredient = nil
|
2016-03-03 13:12:42 -06:00
|
|
|
density = params[:density]
|
|
|
|
density = nil unless density.present?
|
2016-01-31 00:00:32 -06:00
|
|
|
|
2018-09-12 17:17:15 -05:00
|
|
|
if ingredient_id.present?
|
|
|
|
ingredient = Ingredient.find_by_ingredient_id(ingredient_id)
|
|
|
|
end
|
|
|
|
|
2018-09-13 14:51:41 -05:00
|
|
|
data = {errors: Hash.new { |h, k| h[k] = [] }, output: ''}
|
2016-01-31 00:00:32 -06:00
|
|
|
|
2018-09-13 14:51:41 -05:00
|
|
|
UnitConversion::with_custom_units(ingredient ? ingredient.custom_units : []) do
|
|
|
|
density_unit = nil
|
|
|
|
begin
|
|
|
|
if density
|
|
|
|
density_unit = UnitConversion.parse(density)
|
|
|
|
unless density_unit.density?
|
|
|
|
data[:errors][:density] << 'not a density unit'
|
|
|
|
density_unit = nil
|
|
|
|
end
|
|
|
|
end
|
|
|
|
rescue UnitConversion::UnparseableUnitError => e
|
|
|
|
data[:errors][:density] << 'invalid string'
|
|
|
|
end
|
|
|
|
|
|
|
|
begin
|
|
|
|
input_unit = UnitConversion.parse(input)
|
2024-10-02 14:34:50 -05:00
|
|
|
input_unit.unitwise
|
2018-09-13 14:51:41 -05:00
|
|
|
rescue UnitConversion::UnparseableUnitError => e
|
2024-10-02 14:34:50 -05:00
|
|
|
data[:errors][:input] << e.message
|
|
|
|
input_unit = nil
|
2018-09-13 14:51:41 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
if !input_unit.nil?
|
2018-09-12 17:17:15 -05:00
|
|
|
if output_unit.present?
|
2018-09-13 14:51:41 -05:00
|
|
|
begin
|
|
|
|
input_unit = input_unit.convert(output_unit, density_unit)
|
|
|
|
rescue UnitConversion::UnparseableUnitError => e
|
|
|
|
data[:errors][:output_unit] << e.message
|
|
|
|
end
|
2018-09-12 17:17:15 -05:00
|
|
|
else
|
2018-09-13 14:51:41 -05:00
|
|
|
input_unit = input_unit.auto_unit
|
2018-09-12 17:17:15 -05:00
|
|
|
end
|
2016-01-31 00:00:32 -06:00
|
|
|
end
|
2018-09-13 14:51:41 -05:00
|
|
|
|
|
|
|
if data[:errors].empty?
|
|
|
|
data[:output] = input_unit.to_s
|
|
|
|
end
|
2016-01-31 00:00:32 -06:00
|
|
|
end
|
|
|
|
|
|
|
|
render json: data
|
|
|
|
end
|
|
|
|
|
2016-03-03 13:12:42 -06:00
|
|
|
def ingredient_search
|
2018-09-11 10:38:07 -05:00
|
|
|
@foods = Food.has_density.search(params[:query]).order(:name)
|
2020-08-07 12:33:06 -05:00
|
|
|
render json: @foods.map { |f| {id: f.id, name: f.name, density: f.density} }
|
2016-03-03 13:12:42 -06:00
|
|
|
end
|
|
|
|
|
2016-01-31 00:00:32 -06:00
|
|
|
end
|