# SPDX-FileCopyrightText: 2024 Xavier Bordoy # # SPDX-License-Identifier: GPL-2.0-or-later require 'erb' # It tries to model the automatic exercise. # # For us, an automatic exercise is some kind of information, stored in a ruby Hash called `contents` which is evaluated with some substitutions. # # The exercise could have some conditions to be satisfied in order to evaluate the susbtitutions (also known as assignments). These substitutions provide different instances of the same kind of exercise. By this way, the same question or problem is posed but the concrete numbers and information within are different everytime. # # We use [ERB](ihttps://docs.ruby-lang.org/en/master/ERB.html) to make substitutions. # # ## Example # # If we want to create an exercise for students to simply asks "What is a + b?", where ``a`` and ``b`` are arbitrary positive integer numbers, then we could model as this: # # ``` # require_relative automathlib # e = automathlib.AutomaticExercise.new({:text => "Sum <%=a%>+<%=b%>", :solution => "<%=a+b%>", :conditions => "<%=a%> > 0 and <%=b%> > 0"}) # puts e.satisfied_conditions({:a => 5, :b => 3}) # # returns true # puts e.numeric_value({:a => 2, :b=>3}) # # returns 5 # ``` # class AutomaticExercise attr_accessor :info def initialize(info) @info = info end def conditions if @info.has_key?(:conditions) return @info[:conditions] else return nil end end def satisfied_conditions(assignments) return eval(ERB.new(self.conditions).result_with_hash(assignments)) end # Replace variables with assignments # # == Parameters: # assignments:: # A Hash declaring the assignments or susbtitutions to apply # # == Returns: # A Hash or nil. The variables with assignments applied. It returns nil if substitutions are not possible to apply to def numeric_value(assignments) if self.conditions != nil if self.satisfied_conditions(assignments) != true return nil end end r = Hash.new @info.keys.each do |k| r[k] = ERB.new(@info[k]).result_with_hash(assignments) end return r end end