diff --git a/app/controllers/ingredients_controller.rb b/app/controllers/ingredients_controller.rb index 1b01e5a..0a1c0a3 100644 --- a/app/controllers/ingredients_controller.rb +++ b/app/controllers/ingredients_controller.rb @@ -223,12 +223,21 @@ class IngredientsController < ApplicationController def filter_ingredients filters = session[:filters] || {} ingredients = @project.ingredients + if filters[:name].present? ingredients = ingredients.where("name LIKE ?", "%#{filters[:name]}%") end + if filters[:visibility].present? ingredients = ingredients.where(hidden: filters[:visibility] == "1" ? false : true) end + + if filters[:nutrients].present? + formula = Formula.new(self.project, filters[:nutrients], comparison: true) + if formula.valid? + end + end + ingredients end end diff --git a/lib/body_tracking/formula.rb b/lib/body_tracking/formula.rb index 0a78452..68e0a8d 100644 --- a/lib/body_tracking/formula.rb +++ b/lib/body_tracking/formula.rb @@ -4,12 +4,13 @@ module BodyTracking QUANTITY_TTYPES = [:on_ident, :on_tstring_content, :on_const] class Formula - def initialize(project, formula) + def initialize(project, formula, options = {}) @project = project @formula = formula + @options = options end - def validate(options = {}) + def validate errors = [] # 1st: check if formula is valid Ruby code @@ -26,7 +27,10 @@ module BodyTracking identifiers << token when [:on_sp, :on_int, :on_rational, :on_float, :on_tstring_beg, :on_tstring_end, :on_lparen, :on_rparen].include?(ttype) - when :on_op == ttype && '+-*/'.include?(token) + when :on_op == ttype && ['+', '-', '*', '/', '%', '**'].include?(token) + when :on_op == ttype && @options[:comparison] && + ['==', '!=', '>', '<', '>=', '<=', '<=>', '===', '..', '...', '?:', 'and', 'or', + 'not', '&&', '||', '!'].include?(token) else errors << [:disallowed_token, {token: token, ttype: ttype, location: location}] end @@ -48,6 +52,10 @@ module BodyTracking errors end + def valid? + self.validate.empty? + end + def get_quantities q_names = Ripper.lex(@formula).map do |*, ttype, token| token if QUANTITY_TTYPES.include?(ttype) @@ -75,7 +83,7 @@ module BodyTracking end def validate_each(record, attribute, value) - Formula.new(record.project, value).validate(options).each do |message, params| + Formula.new(record.project, value, options).validate.each do |message, params| record.errors.add(attribute, message, params) end end