Class: Ruby_Ab101

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby_qb101.rb

Instance Method Summary collapse

Constructor Details

#initialize(qb_txt, ab_xml = nil, filepath: '.', debug: false) ⇒ Ruby_Ab101

note: the ab_xml file can be in CGRecorder log XML format



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'lib/ruby_qb101.rb', line 85

def initialize(qb_txt, ab_xml=nil, filepath: '.', debug: false)
  
  @debug = debug
  
  @qb = Ruby_Qb101.new(qb_txt)
  
  @dx = Dynarex.new('book[title, tags]/item(question, answer)')
  @dx.title = @qb.title
  @dx.tags = @qb.tags
  
  @qb.questions.each {|q| @dx.create({question: q}) }
  
  if ab_xml and File.exist?(ab_xml) then
    
    dx = Dynarex.new(ab_xml)
    
    # using each question, find the associated answer and 
    # add it the main record
    
    @qb.questions.each do |q|
      
      puts 'q: ' + q.inspect if @debug

      # note: the find_by ... method is passing in a regex because passing 
      #       in a String causes the xpath to execute which is known to have 
      #       a serious bug when the value contains *and*.
      if dx.schema =~ /question, answer/ then

        found = dx.find_by_question /#{q}/
        
        if found then
          rx = @dx.find_by_question /#{q}/
          rx.answer = found.answer 
        end
        
      else
        
        #puts 'dx: ' + dx.to_xml(pretty: true) if @debug
        found = dx.find_by_prompt /#{q}/
        puts 'found: ' + found.inspect if @debug
        
        if found then
          rx = @dx.find_by_question /#{q}/
          rx.answer = found.result 
        end
        
      end
      
    end
    
    #@dx.save ab_xml
    
  end
  
end

Instance Method Details

#save(filename) ⇒ Object



141
142
143
# File 'lib/ruby_qb101.rb', line 141

def save(filename)
  @dx.save filename
end

#to_htmlObject



145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/ruby_qb101.rb', line 145

def to_html()

  doc = Rexle.new('<body>' + @qb.to_html.gsub(/<p>[^>]+>/,'<div>\0</div>') \
                  + '</body>')
  answers = @dx.all.map(&:answer)
  
  puts 'answers: ' + answers.inspect if @debug
  
  doc.root.xpath('//p').each.with_index do |para, i|
    
    e = Rexle::Element.new('p', attributes: {class: 'answer'})\
        .add_text answers[i]
    para.insert_after e
    
  end
  
  doc.root.xml pretty: true
end

#to_xmlObject



164
165
166
# File 'lib/ruby_qb101.rb', line 164

def to_xml()
  @dx.to_xml(pretty: true)
end