Module: Surveyor::Models::DependencyMethods

Included in:
Dependency
Defined in:
lib/surveyor/models/dependency_methods.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/surveyor/models/dependency_methods.rb', line 4

def self.included(base)
  # Associations
  base.send :belongs_to, :question
  base.send :belongs_to, :question_group
  base.send :has_many, :dependency_conditions, :dependent => :destroy
  
  @@validations_already_included ||= nil
  unless @@validations_already_included
    # Validations
    base.send :validates_presence_of, :rule
    base.send :validates_format_of, :rule, :with => /^(?:and|or|\)|\(|[A-Z]|\s)+$/ #TODO properly formed parenthesis etc.
    base.send :validates_numericality_of, :question_id, :if => Proc.new { |d| d.question_group_id.nil? }
    base.send :validates_numericality_of, :question_group_id, :if => Proc.new { |d| d.question_id.nil? }
    
    @@validations_already_included = true
  end
  
  # Whitelisting attributes
  base.send :attr_accessible, :question, :question_group, :question_id, :question_group_id, :rule
  
  # Attribute aliases
  base.send :alias_attribute, :dependent_question_id, :question_id
end

Instance Method Details

#conditions_hash(response_set) ⇒ Object

A hash of the conditions (keyed by rule_key) and their evaluation (boolean) in the context of response_set



53
54
55
56
57
# File 'lib/surveyor/models/dependency_methods.rb', line 53

def conditions_hash(response_set)
  hash = {}
  self.dependency_conditions.each{|dc| hash.merge!(dc.to_hash(response_set))}
  return hash
end

#is_met?(response_set) ⇒ Boolean

Has this dependency has been met in the context of response_set? Substitutes the conditions hash into the rule and evaluates it

Returns:

  • (Boolean)


41
42
43
44
45
46
47
48
49
50
# File 'lib/surveyor/models/dependency_methods.rb', line 41

def is_met?(response_set)
  ch = conditions_hash(response_set)
  return false if ch.blank?
  # logger.debug "rule: #{self.rule.inspect}"
  # logger.debug "rexp: #{rgx.inspect}"
  # logger.debug "keyp: #{ch.inspect}"
  # logger.debug "subd: #{self.rule.gsub(rgx){|m| ch[m.to_sym]}}"
  rgx = Regexp.new(self.dependency_conditions.map{|dc| ["a","o"].include?(dc.rule_key) ? "\\b#{dc.rule_key}(?!nd|r)\\b" : "\\b#{dc.rule_key}\\b"}.join("|")) # exclude and, or
  eval(self.rule.gsub(rgx){|m| ch[m.to_sym]})
end

#question_group_id=(i) ⇒ Object

Instance Methods



29
30
31
32
# File 'lib/surveyor/models/dependency_methods.rb', line 29

def question_group_id=(i)
  write_attribute(:question_id, nil) unless i.nil?
  write_attribute(:question_group_id, i)
end

#question_id=(i) ⇒ Object



34
35
36
37
# File 'lib/surveyor/models/dependency_methods.rb', line 34

def question_id=(i)
  write_attribute(:question_group_id, nil) unless i.nil?
  write_attribute(:question_id, i) 
end