42 lines
999 B
Ruby
42 lines
999 B
Ruby
class CalculatorController < ApplicationController
|
|
|
|
def index
|
|
|
|
end
|
|
|
|
def calculate
|
|
input = params[:input]
|
|
output_unit = params[:output_unit]
|
|
ingredient_id = params[:ingredient_id]
|
|
ingredient = nil
|
|
density = params[:density]
|
|
density = nil unless density.present?
|
|
|
|
if ingredient_id.present?
|
|
ingredient = Ingredient.find_by_ingredient_id(ingredient_id)
|
|
end
|
|
|
|
data = {errors: [], output: ''}
|
|
|
|
begin
|
|
UnitConversion::with_custom_units(ingredient ? ingredient.custom_units : []) do
|
|
unit = UnitConversion.parse(input)
|
|
if output_unit.present?
|
|
unit = unit.convert(output_unit, density)
|
|
data[:output] = unit.to_s
|
|
else
|
|
data[:output] = unit.auto_unit.to_s
|
|
end
|
|
end
|
|
rescue UnitConversion::UnparseableUnitError => e
|
|
data[:errors] << e.message
|
|
end
|
|
|
|
render json: data
|
|
end
|
|
|
|
def ingredient_search
|
|
@foods = Food.has_density.search(params[:query]).order(:name)
|
|
end
|
|
|
|
end |