Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Magic in Fitnext

Magic in Fitnext

the core algorithm of generating meals for fitness

Jimmy Huang

August 21, 2015
Tweet

More Decks by Jimmy Huang

Other Decks in Programming

Transcript

  1. • “detox = yes” • “cycle_index is odd” • “moment

    is breakfast” • “day_index included_in 1,3” Raw materials
  2. Manufacture #<Condition id: 6, attr: "detox", matcher: nil, value: "true">

    #<Condition id: 147, attr: "cycle_index", matcher: "odd", value: ""> operator = (matcher.nil? || matcher.eql?('=') || ['odd', 'even'].include? (matcher)) ? '==' : matcher key = case attr when 'detox': 'has_detox_readiness' when 'objective': 'objective_id' when 'cycle_index' ['odd', 'even'].include?(matcher) ? 'cycle_parity' : 'cycle_number' else attr end val = ['odd', 'even'].include?(matcher) ? "\'#{matcher}'" : value
  3. #<Condition id: 6, attr: "detox", matcher: nil, value: "true"> "#{key}

    #{operator} #{val}" "has_detox_readiness == true" #<Condition id: 147, attr: "cycle_index", matcher: "odd", value: ""> "cycle_parity == 'odd'"
  4. The object object = attr.eql?('sport_sessions_per_week') ? diagnosis : diagnosis.program #<Program

    id: 4, user_id: 26, objective_id: 5, completed: nil, started: nil, has_detox_readiness: true,…> # program.rb def cycle_number user.program_histories.count + 1 end def cycle_parity (cycle_number % 2) == 0 ? 'even' : 'odd' end
  5. Dynamic evaluation object.send(:eval, "#{key} #{operator} #{val}") — Code is data,

    data is code It is important for one to think of code as data to understand what eval is all about. The idea is that the code itself can be manifested as a primitive data type which the language can then make sense of. program.has_detox_readiness == true program.cycle_parity == 'odd' Kernel.eval()
  6. module InferenceEngine module Rule def evaluate(input_object) @evaluation_result = false if

    input_object.respond_to?(self.attribute_name) @evaluation_result = (input_object.send(self.attribute_name) == (self.value == 1)) else false end end end end # ingredient.rb include InferenceEngine::Inference # ingredient_rule.rb include InferenceEngine::Rule
  7. module InferenceEngine module Inference def infere!(input_object) @excluded = false @priority_level

    = 0 @evaluated_rules = [] rules.each do |rule| @evaluated_rules << rule if rule.evaluate(input_object) case rule.human_rule_type when :exclude @excluded = true return when :prioritize @priority_level += 1 when :penalize @priority_level -= 1 end end end end