namespace.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. var Namespace = function (name, parentNamespace) {
  2. this.name = name;
  3. this.parentNamespace = parentNamespace;
  4. this.childNamespaces = {};
  5. this.tasks = {};
  6. this.rules = {};
  7. this.path = this.getPath();
  8. };
  9. Namespace.prototype = new (function () {
  10. this.resolveTask = function(relativeName) {
  11. var parts = relativeName.split(':')
  12. , name = parts.pop()
  13. , ns = this.resolveNamespace(parts.join(':'));
  14. return (ns && ns.tasks[name]) ||
  15. (this.parentNamespace &&
  16. this.parentNamespace.resolveTask(relativeName));
  17. };
  18. this.resolveNamespace = function(relativeName) {
  19. var parts = relativeName.split(':')
  20. , ns;
  21. if (!relativeName) {
  22. return this;
  23. }
  24. ns = this;
  25. for (var i = 0, ii = parts.length; ns && i < ii; i++) {
  26. ns = ns.childNamespaces[parts[i]];
  27. }
  28. return (ns || (this.parentNamespace &&
  29. this.parentNamespace.resolveNamespace(relativeName)));
  30. };
  31. this.matchRule = function(relativeName) {
  32. var parts = relativeName.split(':')
  33. , name = parts.pop()
  34. , ns = this.resolveNamespace(parts.join(':'))
  35. , rules = ns ? ns.rules : []
  36. , r
  37. , match;
  38. for (var p in rules) {
  39. r = rules[p];
  40. if (r.match(relativeName)) {
  41. match = r;
  42. }
  43. }
  44. return (ns && match) ||
  45. (this.parentNamespace &&
  46. this.parentNamespace.matchRule(relativeName));
  47. };
  48. this.getPath = function () {
  49. var parts = []
  50. , next = this;
  51. while (!!next) {
  52. parts.push(next.name);
  53. next = next.parentNamespace;
  54. }
  55. parts.pop(); // Remove 'default'
  56. return parts.reverse().join(':');
  57. };
  58. })();
  59. module.exports.Namespace = Namespace;