def __init__(self, debug=True): self.resources = OrderedDict() self.debug = debug
class ResourceRegistry(object): """ The resource registry is used to register javascript and css that is used by rctk. It allows the main page to be built dynamically and allows certain optimizations such as - merging - compression - caching - keep resources local to the code - possibility to render inline Currently, the ResourceRegistry can't properly handle @import in css. It would probably need to load and merge these imports itself, or load the imported css into the registry itself, possibly renaming the css in the process. At this point, this is only an issue with jqueryui, which we'll keep as a static dependency for now. """ def __init__(self, debug=True): self.resources = OrderedDict() self.debug = debug def add(self, resource): ## avoid duplicates ## XXX optimze if resource in self.resources.values(): ## return its name nonetheless for k, v in self.resources.iteritems(): if v == resource: return k assert "This can't happen" name = resource.name counter = 1 while name in self.resources: name = "%s%d" % (resource.name, counter) counter += 1 self.resources[name] = resource return name ## ## (also) provide a way to filter on mimetype, allow matching against ## image/* as well. def names(self): return self.resources.keys() def css_resources(self): """ return references to css resources. They may be merged so it may be just a single resource """ return [k for (k,v) in self.resources.items() if isinstance(v, (CSSFileResource, CSSResource))] def js_resources(self): """ return references to css resources. They may be merged so it may be just a single resource """ return [k for (k,v) in self.resources.items() if isinstance(v, (JSFileResource, JSResource))] def get_resource(self, name, elements=[]): """ return a (type, data) tuple containing the mimetype and resource data """ r = self.resources[name] ## XXX this is rather ugly way of passing the RR's debug setting r.debug = self.debug if isinstance(r, DynamicResource): r = r(elements) return r def header(self): """ return html usable for injection into <head></head> """ res = [] for css in self.css_resources(): o = self.resources[css] if self.debug: timestamp = "?%d" % o.timestamp() res.append('<link type="text/css" href="resources/%s%s"' 'rel="stylesheet" />' % (css, timestamp)) for js in self.js_resources(): o = self.resources[js] if self.debug: timestamp = "?%d" % o.timestamp() res.append('<script type="text/javascript"' 'src="resources/%s%s"></script>' % (js, timestamp)) return '<!-- dynamic resources -->\n%s\n<!-- end dynamic resources -->' % '\n'.join(res)