Sha256: a14dba66b5edbcf41e9ab7b66945c1d516ed24185a01a8a72465d92d4bc24134

Contents?: true

Size: 1.33 KB

Versions: 6

Compression:

Stored size: 1.33 KB

Contents

class DependencyCondition < ActiveRecord::Base

  # Constants
  OPERATORS = %w(== != < > <= >=) # CONSTANT or @@class_variable when validations listed before class method

  # Associations
  belongs_to :answer
  belongs_to :dependency
  belongs_to :dependent_question, :foreign_key => :question_id, :class_name => :question
  belongs_to :question

  # Validations
  validates_numericality_of :dependency_id, :question_id, :answer_id
  validates_presence_of :operator, :rule_key
  validates_inclusion_of :operator, :in => OPERATORS
  validates_uniqueness_of :rule_key, :scope => :dependency_id

  acts_as_response # includes "as" instance method
  
  # Class methods
  def self.operators
    OPERATORS
  end

  # Instance methods
  def to_hash(response_set)
    response = response_set.responses.detect{|r| r.answer_id.to_i == self.answer_id.to_i} || false # eval("nil and false") => nil so return false if no response is found
    {rule_key.to_sym => (response and self.is_met?(response))}
  end

  # Checks to see if the response passed in meets the dependency condition
  def is_met?(response)
    klass = response.answer.response_class
    return case self.operator
    when "==", "<", ">", "<=", ">="
      response.as(klass).send(self.operator, self.as(klass))
    when "!="
      !(response.as(klass) == self.as(klass))
    else
      false
    end
  end

end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
surveyor-0.14.4 app/models/dependency_condition.rb
surveyor-0.14.3 app/models/dependency_condition.rb
surveyor-0.14.2 app/models/dependency_condition.rb
surveyor-0.14.1 app/models/dependency_condition.rb
surveyor-0.14.0 app/models/dependency_condition.rb
surveyor-0.13.0 app/models/dependency_condition.rb