1 module action_dispatch.namespace;
2 
3 import action_dispatch.all;
4 import std.array;
5 
6 class ActionNamespace {
7   private {
8     ActionRouter _router;
9     string[]     _namespaces;
10     string[]     _variables;
11   }
12 
13   this(ActionRouter router, string namespace) {
14     this(router, [namespace]);
15   }
16 
17   this(ActionRouter router, string[] namespaces) {
18     _router     = router;
19     foreach(ns; namespaces) {
20       _namespaces ~= ns;
21       _variables  ~= ":" ~ singularize(ns) ~ "_id";
22     }
23   }
24 
25   string joinPrefix() {
26     string[] prefix;
27     for (int i = 0; i < _namespaces.length; i++) {
28       prefix ~= _namespaces[i];
29       prefix ~= _variables[i];
30     }
31 
32     return join(prefix, "/");
33   }
34 
35   ActionRouter resources(string resource) {
36     _router.resources(resource, joinPrefix());
37     return _router;
38   }
39 
40   ActionRouter resources(string resource, void delegate(ActionNamespace namespace) yield) {
41     resources(resource);
42 
43     auto namespace = new ActionNamespace(_router, _namespaces ~ resource);
44     yield(namespace);
45     return _router;
46   }
47 
48   private {
49     string singularize(string input) {
50       // classes case
51       if (input[input.length - 3..input.length - 1] == "ses")
52         return input[0..input.length - 3];
53       // books case
54       else if (input[input.length - 1] == 's')
55         return input[0..input.length - 1];
56 
57       return input;
58     }
59   }
60 }