Module: Ask::ActiveRecord::InstanceMethods

Defined in:
lib/ask/acts_as_answerer.rb

Instance Method Summary collapse

Instance Method Details

#all_questionsObject



4
5
6
7
8
9
10
# File 'lib/ask/acts_as_answerer.rb', line 4

def all_questions
  if respond_to? :asker
    @all_questions ||= asker.questions
  else
    raise NoMethodError, "You must define a #{self}#asker method that returns the related acts_as_asker model"
  end
end

#answer_to(question) ⇒ Object



41
42
43
44
45
46
47
48
# File 'lib/ask/acts_as_answerer.rb', line 41

def answer_to(question)
  return nil if question.nil?
  if question.supports_multiple_answers?
    answers_to(question)
  else
    answers.find_by_question_id(question.id)
  end
end

#answers_to(question) ⇒ Object



50
51
52
53
# File 'lib/ask/acts_as_answerer.rb', line 50

def answers_to(question)
  return nil if question.nil?
  answers.for_question(question)
end

#build_or_create_answers(questions) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/ask/acts_as_answerer.rb', line 55

def build_or_create_answers(questions)
  method = new_record? ? :build : :create

  questions.each do |question|
    if answers_to(question).empty?
      if question.supports_multiple_answers?
        question.choices.each do |choice|
          answers.send(method, :question_id=>question.id, :answer=>'', :choice_id=>choice.id)
        end
      else
        answers.send(method, :question_id=>question.id)
      end
    end
  end
end

#find_question(question) ⇒ Object



12
13
14
15
16
17
18
19
20
# File 'lib/ask/acts_as_answerer.rb', line 12

def find_question(question)
  if question.is_a? Question
    question
  elsif question.is_a? Fixnum
    all_questions.find_by_id(question)
  else
    all_questions.find_by_name(question.to_s)
  end
end

#questions_by_sectionObject



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/ask/acts_as_answerer.rb', line 22

def questions_by_section
  section = nil
  questions = {}

  asker.questions.order(:position).each do |question|
    if question.is_a? FormSection
      section = question
    end

    questions[section] ||= []

    unless question.is_a? FormSection
      questions[section] << question
    end
  end

  questions
end

#questions_with_answersObject



71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/ask/acts_as_answerer.rb', line 71

def questions_with_answers
  qa = ActiveSupport::OrderedHash.new

  # Set the correct order and make sure we have all the questions
  all_questions.each do |q|
    qa[q.id] = []
  end

  answers.each do |a|
    qa[a.question.id] << a.answer.to_s.strip unless a.answer.blank?
  end

  qa
end