Class: Ab101

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

Instance Method Summary collapse

Constructor Details

#initialize(qb, ab_xml = nil, filepath: '.', debug: false) ⇒ Ab101

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



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
140
141
142
143
144
145
146
# File 'lib/qb101.rb', line 88

def initialize(qb, ab_xml=nil, filepath: '.', debug: false)
  
  @debug = debug
  
  @qb = if qb.is_a?(String) and qb.lines.length < 2 then
    Qb101.new(qb)
  elsif qb.kind_of?(Qb101)
    qb
  end
  
  @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



148
149
150
# File 'lib/qb101.rb', line 148

def save(filename)
  @dx.save filename
end

#to_htmlObject



152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
# File 'lib/qb101.rb', line 152

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|


    s = answers[i].strip
    
    e = if s.lines.length > 1 then
    
      html = "<span>%s</span>" % Kramdown::Document.new(s).to_html      
      Rexle.new(html).root
      
    else
      
      Rexle::Element.new('p', attributes: {class: 'answer'})\
          .add_text s
      
    end
    para.insert_after e
    
  end
  
  doc.root.xml pretty: true
end

#to_xmlObject



183
184
185
# File 'lib/qb101.rb', line 183

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