Commit 47094a1f by Vasyl Nakvasiuk

modify `ConditionalDescriptor.definition_from_xml`

parent 4b148f9a
# -*- coding: utf-8 -*-
import json import json
import logging import logging
from lxml import etree
from pkg_resources import resource_string
from xmodule.x_module import XModule from xmodule.x_module import XModule
from xmodule.modulestore import Location from xmodule.modulestore import Location
from xmodule.seq_module import SequenceDescriptor from xmodule.seq_module import SequenceDescriptor
from xblock.core import List, String, Scope, Integer from xblock.core import String, Scope
from lxml import etree
from pkg_resources import resource_string
log = logging.getLogger('mitx.' + __name__) log = logging.getLogger('mitx.' + __name__)
class ConditionalModule(XModule): class ConditionalModule(XModule):
''' """
Blocks child module from showing unless certain conditions are met. Blocks child module from showing unless certain conditions are met.
Example: Example:
...@@ -19,7 +23,7 @@ class ConditionalModule(XModule): ...@@ -19,7 +23,7 @@ class ConditionalModule(XModule):
<video url_name="secret_video" /> <video url_name="secret_video" />
</conditional> </conditional>
''' """
js = {'coffee': [resource_string(__name__, 'js/src/javascript_loader.coffee'), js = {'coffee': [resource_string(__name__, 'js/src/javascript_loader.coffee'),
resource_string(__name__, 'js/src/conditional/display.coffee'), resource_string(__name__, 'js/src/conditional/display.coffee'),
...@@ -66,7 +70,7 @@ class ConditionalModule(XModule): ...@@ -66,7 +70,7 @@ class ConditionalModule(XModule):
for module in self.required_modules: for module in self.required_modules:
if not hasattr(module, 'poll_answer'): if not hasattr(module, 'poll_answer'):
raise Exception('Error in conditional module: required module %s has no poll_answer field' % module) raise Exception('Error in conditional module: required module %s has no poll_answer field' % module)
answer = self.descriptor.xml_attributes.get('answer') answer = self.descriptor.xml_attributes.get('answer')
if answer == 'unanswered' and module.poll_answer: if answer == 'unanswered' and module.poll_answer:
return False return False
if module.poll_answer != answer: if module.poll_answer != answer:
...@@ -86,7 +90,7 @@ class ConditionalModule(XModule): ...@@ -86,7 +90,7 @@ class ConditionalModule(XModule):
}) })
def _get_modules_to_show(self): def _get_modules_to_show(self):
to_show = [tuple(x.strip().split('/',1)) for x in self.show_modules.split(';')] to_show = [tuple(x.strip().split('/', 1)) for x in self.show_modules.split(';')]
self.modules_to_show = [] self.modules_to_show = []
for (tag, name) in to_show: for (tag, name) in to_show:
loc = self.location.dict() loc = self.location.dict()
...@@ -94,12 +98,10 @@ class ConditionalModule(XModule): ...@@ -94,12 +98,10 @@ class ConditionalModule(XModule):
loc['name'] = name loc['name'] = name
self.modules_to_show.append(Location(loc)) self.modules_to_show.append(Location(loc))
def handle_ajax(self, dispatch, post): def handle_ajax(self, dispatch, post):
''' '''
This is called by courseware.moduleodule_render, to handle an AJAX call. This is called by courseware.moduleodule_render, to handle an AJAX call.
''' '''
# import ipdb; ipdb.set_trace()
#log.debug('conditional_module handle_ajax: dispatch=%s' % dispatch) #log.debug('conditional_module handle_ajax: dispatch=%s' % dispatch)
if not self.is_condition_satisfied(): if not self.is_condition_satisfied():
context = {'module': self} context = {'module': self}
...@@ -107,19 +109,18 @@ class ConditionalModule(XModule): ...@@ -107,19 +109,18 @@ class ConditionalModule(XModule):
return json.dumps({'html': [html]}) return json.dumps({'html': [html]})
if self.contents is None: if self.contents is None:
import ipdb; ipdb.set_trace()
# self.contents = [child.get_html() for child in self.get_display_items()] # self.contents = [child.get_html() for child in self.get_display_items()]
self.contents = [self.system.get_module(x).get_html() for x in self.modules_to_show] self.contents = [self.system.get_module(x).get_html() for x in self.modules_to_show]
self.contents += [self.system.get_module(child_descriptor.location).get_html() self.contents += [self.system.get_module(child_descriptor.location).get_html()
for child_descriptor in self.descriptor.get_children()] for child_descriptor in self.descriptor.get_children()]
html = self.contents html = self.contents
#log.debug('rendered conditional module %s' % str(self.location)) #log.debug('rendered conditional module %s' % str(self.location))
return json.dumps({'html': html}) return json.dumps({'html': html})
class ConditionalDescriptor(SequenceDescriptor): class ConditionalDescriptor(SequenceDescriptor):
''' TODO check exports''' """TODO: add docs."""
module_class = ConditionalModule module_class = ConditionalModule
filename_extension = "xml" filename_extension = "xml"
...@@ -131,8 +132,8 @@ class ConditionalDescriptor(SequenceDescriptor): ...@@ -131,8 +132,8 @@ class ConditionalDescriptor(SequenceDescriptor):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(ConditionalDescriptor, self).__init__(*args, **kwargs) super(ConditionalDescriptor, self).__init__(*args, **kwargs)
# import ipdb; ipdb.set_trace() required_module_list = [(x.strip().split('/', 5)[4:6]) for x in
required_module_list = [(x.strip().split('/',5)[4:6]) for x in self.xml_attributes.get('source','').split(';')] self.xml_attributes.get('source', '').split(';')]
self.required_module_locations = [] self.required_module_locations = []
for (tag, name) in required_module_list: for (tag, name) in required_module_list:
loc = self.location.dict() loc = self.location.dict()
...@@ -149,19 +150,31 @@ class ConditionalDescriptor(SequenceDescriptor): ...@@ -149,19 +150,31 @@ class ConditionalDescriptor(SequenceDescriptor):
@classmethod @classmethod
def definition_from_xml(cls, xml_object, system): def definition_from_xml(cls, xml_object, system):
def parse_show_tag(child):
"""Return list of valid module urls from <show> tag."""
urls = []
sources = child.get('sources')
if sources:
for url in [url.strip() for url in sources.split(';')]:
try:
Location(url)
urls.append(url)
except:
log.exception("Bad location url - {0}".format(url))
return urls
children = [] children = []
for child in xml_object: for child in xml_object:
if child.tag != 'show': if child.tag == 'show':
try: children.extend(parse_show_tag(child))
children.append(system.process_xml(etree.tostring(child)).location.url())
except Exception, e:
log.exception("Unable to load child when parsing Conditional. Continuing...")
if system.error_tracker is not None:
system.error_tracker("ERROR: " + str(e))
continue
else: else:
cls.show_modules = child.get('source') try:
return {'show_modules':''}, children descriptor = system.process_xml(etree.tostring(child))
module_url = descriptor.location.url()
children.append(module_url)
except:
log.exception("Unable to load child when parsing Conditional.")
return {}, children
def definition_to_xml(self, resource_fs): def definition_to_xml(self, resource_fs):
xml_object = etree.Element('sequential') xml_object = etree.Element('sequential')
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment