Class: CitizenBudgetModel::Simulator
- Inherits:
-
ActiveRecord::Base
- Object
- ActiveRecord::Base
- CitizenBudgetModel::Simulator
- Defined in:
- app/models/citizen_budget_model/simulator.rb
Instance Method Summary collapse
-
#activate! ⇒ Object
Sets the simulator as active and all others as inactive.
-
#default_equation ⇒ String
Returns a default equation, where the difference between the chosen value and the default value is multiplied by the unit value for each variable.
-
#solve(variables) ⇒ Float
Solves the equation with the given variables’ values.
-
#working_equation ⇒ String
Returns the equation or a default equation if not set.
Instance Method Details
#activate! ⇒ Object
Sets the simulator as active and all others as inactive.
16 17 18 19 20 21 |
# File 'app/models/citizen_budget_model/simulator.rb', line 16 def activate! self.class.where(active: true).each do |simulator| simulator.update!(active: false) end update!(active: true) end |
#default_equation ⇒ String
Returns a default equation, where the difference between the chosen value and the default value is multiplied by the unit value for each variable.
38 39 40 41 42 43 44 45 46 |
# File 'app/models/citizen_budget_model/simulator.rb', line 38 def default_equation equation = [] sections.each do |section| section.questions.each do |question| equation << question.working_equation end end equation.reject(&:empty?).join(' + ') end |
#solve(variables) ⇒ Float
Solves the equation with the given variables’ values.
52 53 54 55 56 57 58 59 60 61 62 63 |
# File 'app/models/citizen_budget_model/simulator.rb', line 52 def solve(variables) keys = [] values = [] variables.each do |key,value| keys << key.to_sym values << Float(value) end # Struct will raise a NameError, whereas OpenStruct will not. eval(working_equation, Struct.new(*keys).new(*values).instance_eval{binding}) end |
#working_equation ⇒ String
Returns the equation or a default equation if not set.
26 27 28 29 30 31 32 |
# File 'app/models/citizen_budget_model/simulator.rb', line 26 def working_equation if equation? equation else default_equation end end |