pcapr-local 0.1.10

Sign up to get free protection for your applications and to get access to all the features.
Files changed (203) hide show
  1. data/.document +5 -0
  2. data/LICENSE.txt +20 -0
  3. data/README.md +64 -0
  4. data/Rakefile +57 -0
  5. data/VERSION +1 -0
  6. data/bin/pcap2par +49 -0
  7. data/bin/startpcapr +40 -0
  8. data/bin/stoppcapr +33 -0
  9. data/bin/xtractr +5 -0
  10. data/lib/environment.rb +106 -0
  11. data/lib/exe/xtractr +0 -0
  12. data/lib/mu/pcap.rb +110 -0
  13. data/lib/mu/pcap/ethernet.rb +148 -0
  14. data/lib/mu/pcap/header.rb +75 -0
  15. data/lib/mu/pcap/io_pair.rb +67 -0
  16. data/lib/mu/pcap/io_wrapper.rb +76 -0
  17. data/lib/mu/pcap/ip.rb +61 -0
  18. data/lib/mu/pcap/ipv4.rb +257 -0
  19. data/lib/mu/pcap/ipv6.rb +148 -0
  20. data/lib/mu/pcap/packet.rb +104 -0
  21. data/lib/mu/pcap/pkthdr.rb +155 -0
  22. data/lib/mu/pcap/reader.rb +61 -0
  23. data/lib/mu/pcap/reader/http_family.rb +170 -0
  24. data/lib/mu/pcap/sctp.rb +367 -0
  25. data/lib/mu/pcap/sctp/chunk.rb +123 -0
  26. data/lib/mu/pcap/sctp/chunk/data.rb +134 -0
  27. data/lib/mu/pcap/sctp/chunk/init.rb +100 -0
  28. data/lib/mu/pcap/sctp/chunk/init_ack.rb +68 -0
  29. data/lib/mu/pcap/sctp/parameter.rb +110 -0
  30. data/lib/mu/pcap/sctp/parameter/ip_address.rb +48 -0
  31. data/lib/mu/pcap/stream_packetizer.rb +72 -0
  32. data/lib/mu/pcap/tcp.rb +505 -0
  33. data/lib/mu/pcap/udp.rb +69 -0
  34. data/lib/mu/scenario/pcap.rb +164 -0
  35. data/lib/mu/scenario/pcap/fields.rb +50 -0
  36. data/lib/mu/scenario/pcap/rtp.rb +71 -0
  37. data/lib/pcapr_local.rb +159 -0
  38. data/lib/pcapr_local/config.rb +336 -0
  39. data/lib/pcapr_local/db.rb +197 -0
  40. data/lib/pcapr_local/scanner.rb +250 -0
  41. data/lib/pcapr_local/server.rb +178 -0
  42. data/lib/pcapr_local/www/favicon.ico +0 -0
  43. data/lib/pcapr_local/www/favicon.png +0 -0
  44. data/lib/pcapr_local/www/home/index.html +138 -0
  45. data/lib/pcapr_local/www/static/image/16x16/Cancel.png +0 -0
  46. data/lib/pcapr_local/www/static/image/16x16/Cancel.png.1 +0 -0
  47. data/lib/pcapr_local/www/static/image/16x16/Download.png +0 -0
  48. data/lib/pcapr_local/www/static/image/16x16/Folder3.png +0 -0
  49. data/lib/pcapr_local/www/static/image/16x16/Full Size.png +0 -0
  50. data/lib/pcapr_local/www/static/image/16x16/Minus.png +0 -0
  51. data/lib/pcapr_local/www/static/image/16x16/Plus.png +0 -0
  52. data/lib/pcapr_local/www/static/image/16x16/Search.png +0 -0
  53. data/lib/pcapr_local/www/static/image/16x16/User.png +0 -0
  54. data/lib/pcapr_local/www/static/image/48x48/Phone.png +0 -0
  55. data/lib/pcapr_local/www/static/image/48x48/Video.png +0 -0
  56. data/lib/pcapr_local/www/static/image/bar-orange.gif +0 -0
  57. data/lib/pcapr_local/www/static/image/beta.png +0 -0
  58. data/lib/pcapr_local/www/static/image/bg.png +0 -0
  59. data/lib/pcapr_local/www/static/image/blockquote.png +0 -0
  60. data/lib/pcapr_local/www/static/image/body-bg.png +0 -0
  61. data/lib/pcapr_local/www/static/image/body-h3.png +0 -0
  62. data/lib/pcapr_local/www/static/image/body-hl1-bg.png +0 -0
  63. data/lib/pcapr_local/www/static/image/body-hl1-h3.png +0 -0
  64. data/lib/pcapr_local/www/static/image/body-hl1-readmore.png +0 -0
  65. data/lib/pcapr_local/www/static/image/body-hl2-bg.png +0 -0
  66. data/lib/pcapr_local/www/static/image/body-hl2-h3.png +0 -0
  67. data/lib/pcapr_local/www/static/image/body-hl2-readmore.png +0 -0
  68. data/lib/pcapr_local/www/static/image/body-hl3-bg.png +0 -0
  69. data/lib/pcapr_local/www/static/image/body-hl3-h3.png +0 -0
  70. data/lib/pcapr_local/www/static/image/body-hl3-readmore.png +0 -0
  71. data/lib/pcapr_local/www/static/image/body-hl4-bg.png +0 -0
  72. data/lib/pcapr_local/www/static/image/body-hl4-h3.png +0 -0
  73. data/lib/pcapr_local/www/static/image/body-hl4-readmore.png +0 -0
  74. data/lib/pcapr_local/www/static/image/body-hl5-h3.png +0 -0
  75. data/lib/pcapr_local/www/static/image/body-hl6-h3.png +0 -0
  76. data/lib/pcapr_local/www/static/image/body-hl7-h3.png +0 -0
  77. data/lib/pcapr_local/www/static/image/body-hl8-h3.png +0 -0
  78. data/lib/pcapr_local/www/static/image/body-readmore.png +0 -0
  79. data/lib/pcapr_local/www/static/image/bottom-bg.png +0 -0
  80. data/lib/pcapr_local/www/static/image/bottom-l.png +0 -0
  81. data/lib/pcapr_local/www/static/image/bottom-r.png +0 -0
  82. data/lib/pcapr_local/www/static/image/btn-search.png +0 -0
  83. data/lib/pcapr_local/www/static/image/bullet-1.png +0 -0
  84. data/lib/pcapr_local/www/static/image/bullet-2.png +0 -0
  85. data/lib/pcapr_local/www/static/image/bullet-3.png +0 -0
  86. data/lib/pcapr_local/www/static/image/bullet-4.png +0 -0
  87. data/lib/pcapr_local/www/static/image/bullet-5.png +0 -0
  88. data/lib/pcapr_local/www/static/image/bullet-6.png +0 -0
  89. data/lib/pcapr_local/www/static/image/bullet-7.png +0 -0
  90. data/lib/pcapr_local/www/static/image/bullet-hl1.png +0 -0
  91. data/lib/pcapr_local/www/static/image/bullet-hl2.png +0 -0
  92. data/lib/pcapr_local/www/static/image/bullet-hl3.png +0 -0
  93. data/lib/pcapr_local/www/static/image/bullet-hl4.png +0 -0
  94. data/lib/pcapr_local/www/static/image/bullet-pathway.png +0 -0
  95. data/lib/pcapr_local/www/static/image/bullet-section1.png +0 -0
  96. data/lib/pcapr_local/www/static/image/bullet-section2.png +0 -0
  97. data/lib/pcapr_local/www/static/image/collapsed.gif +0 -0
  98. data/lib/pcapr_local/www/static/image/crosslink.png +0 -0
  99. data/lib/pcapr_local/www/static/image/expanded.gif +0 -0
  100. data/lib/pcapr_local/www/static/image/favicon.ico +0 -0
  101. data/lib/pcapr_local/www/static/image/favicon.png +0 -0
  102. data/lib/pcapr_local/www/static/image/icon-author.png +0 -0
  103. data/lib/pcapr_local/www/static/image/icon-created.png +0 -0
  104. data/lib/pcapr_local/www/static/image/p-expand.gif +0 -0
  105. data/lib/pcapr_local/www/static/image/pcapr-logo.png +0 -0
  106. data/lib/pcapr_local/www/static/image/powered-by.png +0 -0
  107. data/lib/pcapr_local/www/static/image/section1-bg.png +0 -0
  108. data/lib/pcapr_local/www/static/image/section1-h3.png +0 -0
  109. data/lib/pcapr_local/www/static/image/section1-readmore.png +0 -0
  110. data/lib/pcapr_local/www/static/image/section2-bg.png +0 -0
  111. data/lib/pcapr_local/www/static/image/section2-h3.png +0 -0
  112. data/lib/pcapr_local/www/static/image/section2-readmore.png +0 -0
  113. data/lib/pcapr_local/www/static/image/status-alert.png +0 -0
  114. data/lib/pcapr_local/www/static/image/status-download.png +0 -0
  115. data/lib/pcapr_local/www/static/image/status-info.png +0 -0
  116. data/lib/pcapr_local/www/static/image/status-note.png +0 -0
  117. data/lib/pcapr_local/www/static/image/tab-round.png +0 -0
  118. data/lib/pcapr_local/www/static/image/throbber.gif +0 -0
  119. data/lib/pcapr_local/www/static/image/user.jpg +0 -0
  120. data/lib/pcapr_local/www/static/script/closet/async.js +421 -0
  121. data/lib/pcapr_local/www/static/script/closet/closet.api.js +241 -0
  122. data/lib/pcapr_local/www/static/script/closet/closet.folders.js +94 -0
  123. data/lib/pcapr_local/www/static/script/closet/closet.js +187 -0
  124. data/lib/pcapr_local/www/static/script/closet/closet.mr.js +219 -0
  125. data/lib/pcapr_local/www/static/script/closet/closet.options.js +359 -0
  126. data/lib/pcapr_local/www/static/script/closet/closet.quantity.js +73 -0
  127. data/lib/pcapr_local/www/static/script/closet/closet.render.js +205 -0
  128. data/lib/pcapr_local/www/static/script/closet/closet.report.js +86 -0
  129. data/lib/pcapr_local/www/static/script/closet/closet.reports.http.js +135 -0
  130. data/lib/pcapr_local/www/static/script/closet/closet.reports.overview.js +163 -0
  131. data/lib/pcapr_local/www/static/script/closet/closet.reports.sip.js +159 -0
  132. data/lib/pcapr_local/www/static/script/closet/closet.reports.tcp.js +72 -0
  133. data/lib/pcapr_local/www/static/script/closet/closet.reports.visualize.js +263 -0
  134. data/lib/pcapr_local/www/static/script/closet/closet.util.js +40 -0
  135. data/lib/pcapr_local/www/static/script/jquery/jquery-1.4.2.min.js +154 -0
  136. data/lib/pcapr_local/www/static/script/jquery/jquery-ui.js +10921 -0
  137. data/lib/pcapr_local/www/static/script/jquery/jquery.flot.js +2123 -0
  138. data/lib/pcapr_local/www/static/script/jquery/jquery.flot.selection.js +184 -0
  139. data/lib/pcapr_local/www/static/script/jquery/jquery.flot.stack.js +184 -0
  140. data/lib/pcapr_local/www/static/script/jquery/jquery.form.js +643 -0
  141. data/lib/pcapr_local/www/static/script/jquery/jquery.jsonp.min.js +3 -0
  142. data/lib/pcapr_local/www/static/script/jquery/jquery.menu.js +142 -0
  143. data/lib/pcapr_local/www/static/script/jquery/jquery.suggest.js +308 -0
  144. data/lib/pcapr_local/www/static/script/jquery/jquery.ui.core.js +203 -0
  145. data/lib/pcapr_local/www/static/script/jquery/jquery.ui.slider.js +629 -0
  146. data/lib/pcapr_local/www/static/script/jquery/jquery.ui.sortable.js +1055 -0
  147. data/lib/pcapr_local/www/static/script/jquery/jquery.ui.widget.js +236 -0
  148. data/lib/pcapr_local/www/static/script/json2.js +481 -0
  149. data/lib/pcapr_local/www/static/script/sammy/plugins/sammy.cache.js +115 -0
  150. data/lib/pcapr_local/www/static/script/sammy/plugins/sammy.template.js +117 -0
  151. data/lib/pcapr_local/www/static/script/sammy/sammy.js +1696 -0
  152. data/lib/pcapr_local/www/static/script/tipsy/jquery.tipsy.js +104 -0
  153. data/lib/pcapr_local/www/static/style/c3p0.css +116 -0
  154. data/lib/pcapr_local/www/static/style/jquery.suggest.css +27 -0
  155. data/lib/pcapr_local/www/static/style/page.css +1113 -0
  156. data/lib/pcapr_local/www/static/style/tipsy.css +7 -0
  157. data/lib/pcapr_local/www/templates/browse.services.template +10 -0
  158. data/lib/pcapr_local/www/templates/browse.template +77 -0
  159. data/lib/pcapr_local/www/templates/flows.template +38 -0
  160. data/lib/pcapr_local/www/templates/pcap.template +63 -0
  161. data/lib/pcapr_local/www/templates/sip.calls.template +35 -0
  162. data/lib/pcapr_local/www/templates/statistics.template +6 -0
  163. data/lib/pcapr_local/xtractr.rb +179 -0
  164. data/lib/pcapr_local/xtractr/instance.rb +172 -0
  165. data/pcapr-local.gemspec +297 -0
  166. data/test/mu/pcap/reader/tc_http_family.rb +251 -0
  167. data/test/mu/pcap/tc_ethernet.rb +71 -0
  168. data/test/mu/pcap/tc_header.rb +56 -0
  169. data/test/mu/pcap/tc_ipv4.rb +103 -0
  170. data/test/mu/pcap/tc_ipv6.rb +83 -0
  171. data/test/mu/pcap/tc_packet.rb +44 -0
  172. data/test/mu/pcap/tc_pair.rb +58 -0
  173. data/test/mu/pcap/tc_pkthdr.rb +33 -0
  174. data/test/mu/pcap/tc_reader.rb +76 -0
  175. data/test/mu/pcap/tc_tcp.rb +426 -0
  176. data/test/mu/pcap/tc_udp.rb +33 -0
  177. data/test/mu/pcap/tc_wrapper.rb +80 -0
  178. data/test/mu/scenario/pcap/tc_fields.rb +67 -0
  179. data/test/mu/scenario/pcap/tc_rtp.rb +135 -0
  180. data/test/mu/scenario/sip_signalled_call_1.pcap +0 -0
  181. data/test/mu/scenario/tc_pcap.rb +190 -0
  182. data/test/mu/scenario/test_data/arp.pcap +0 -0
  183. data/test/mu/scenario/test_data/dns.pcap +0 -0
  184. data/test/mu/scenario/test_data/http-v6.pcap +0 -0
  185. data/test/mu/scenario/test_data/http.pcap +0 -0
  186. data/test/mu/scenario/test_data/http_chunked.pcap +0 -0
  187. data/test/mu/scenario/test_data/http_deflate.pcap +0 -0
  188. data/test/mu/scenario/test_data/httpauth3.pcap +0 -0
  189. data/test/mu/scenario/test_data/icmp.pcap +0 -0
  190. data/test/mu/scenario/test_data/sip_signalled_call_1.pcap +0 -0
  191. data/test/mu/tc_pcap.rb +39 -0
  192. data/test/mu/testcase.rb +86 -0
  193. data/test/pcapr_local/arp.pcap +0 -0
  194. data/test/pcapr_local/data.js +3 -0
  195. data/test/pcapr_local/http_chunked.pcap +0 -0
  196. data/test/pcapr_local/tc_api.rb +181 -0
  197. data/test/pcapr_local/test.tgz +0 -0
  198. data/test/pcapr_local/test_scanner.rb +241 -0
  199. data/test/pcapr_local/test_xtractr.rb +219 -0
  200. data/test/pcapr_local/testcase.rb +107 -0
  201. data/test/test_export_to_scenario.sh +25 -0
  202. data/test/test_pcapr_local.rb +29 -0
  203. metadata +450 -0
@@ -0,0 +1,115 @@
1
+ // deprecated
2
+ (function($) {
3
+
4
+ Sammy = Sammy || {};
5
+
6
+ // A simple cache strategy that stores key/values in memory.
7
+ Sammy.MemoryCacheProxy = function(initial) {
8
+ this._cache = initial || {};
9
+ };
10
+
11
+ $.extend(Sammy.MemoryCacheProxy.prototype, {
12
+ exists: function(name) {
13
+ return (typeof this._cache[name] != "undefined");
14
+ },
15
+ set: function(name, value) {
16
+ return this._cache[name] = value;
17
+ },
18
+ get: function(name) {
19
+ return this._cache[name];
20
+ },
21
+ clear: function(name) {
22
+ delete this._cache[name];
23
+ }
24
+ });
25
+
26
+ // A simple cache strategy that stores key/values <tt>$element.data()</tt> with a <tt>cache.</tt> prefix
27
+ Sammy.DataCacheProxy = function(initial, $element) {
28
+ initial = initial || {};
29
+ this.$element = $element;
30
+ $.each(initial, function(key, value) {
31
+ $element.data('cache.' + key, value);
32
+ });
33
+ };
34
+
35
+ $.extend(Sammy.DataCacheProxy.prototype, {
36
+ exists: function(name) {
37
+ return (typeof this.$element.data('cache.' + name) != "undefined");
38
+ },
39
+ set: function(name, value) {
40
+ return this.$element.data('cache.' + name, value);
41
+ },
42
+ get: function(name) {
43
+ return this.$element.data('cache.' + name);
44
+ },
45
+ clear: function(name) {
46
+ this.$element.removeData('cache.' + name);
47
+ }
48
+ });
49
+
50
+ // Sammy.Cache provides helpers for caching data within the lifecycle of a
51
+ // Sammy app. The plugin provides two main methods on <tt>Sammy.Application<tt>,
52
+ // <tt>cache</tt> and <tt>clearCache</tt>. Each app has its own cache store so that
53
+ // you dont have to worry about collisions. There are currently two different 'cache proxies'
54
+ // that share the same API but store the data in different ways.
55
+ //
56
+ // ### Arguments
57
+ //
58
+ // * `proxy` decides which caching proxy to use, either 'memory'(default) or 'data'
59
+ //
60
+ Sammy.Cache = function(app, proxy) {
61
+
62
+ app.log('**WARNING:** This version of Sammy.Cache has been deprecated in favor of using the version in Sammy.Storage and will be removed in 1.0')
63
+
64
+ if (proxy == 'data') {
65
+ this.cache_proxy = new Sammy.DataCacheProxy({}, this.$element());
66
+ } else {
67
+ this.cache_proxy = new Sammy.MemoryCacheProxy({});
68
+ }
69
+
70
+ app.cache_partials = true;
71
+
72
+ $.extend(app, {
73
+ // cache is the main method for interacting with the cache store. The same
74
+ // method is used for both setting and getting the value. The API is similar
75
+ // to jQuery.fn.attr()
76
+ //
77
+ // ### Examples
78
+ //
79
+ // // setting a value
80
+ // cache('key', 'value');
81
+ //
82
+ // // getting a value
83
+ // cache('key'); //=> 'value'
84
+ //
85
+ // // setting a value with a callback
86
+ // cache('key', function() {
87
+ // // this is the app
88
+ // return app.element_selector;
89
+ // });
90
+ //
91
+ cache: function(name, value) {
92
+ if (typeof value == 'undefined') {
93
+ return this.cache_proxy.get(name);
94
+ } else if ($.isFunction(value) && !this.cache_proxy.exists(name)) {
95
+ return this.cache_proxy.set(name, value.apply(this));
96
+ } else {
97
+ return this.cache_proxy.set(name, value)
98
+ }
99
+ },
100
+
101
+ // clears the cached value for <tt>name</tt>
102
+ clearCache: function(name) {
103
+ return this.cache_proxy.clear(name);
104
+ }
105
+ });
106
+
107
+ app.helpers({
108
+ // a helper shortcut for use in <tt>Sammy.EventContext</tt>
109
+ cache: function(name, value) {
110
+ return this.app.cache(name, value);
111
+ }
112
+ });
113
+ };
114
+
115
+ })(jQuery);
@@ -0,0 +1,117 @@
1
+ (function($) {
2
+
3
+ // Simple JavaScript Templating
4
+ // John Resig - http://ejohn.org/ - MIT Licensed
5
+ // adapted from: http://ejohn.org/blog/javascript-micro-templating/
6
+ // originally $.srender by Greg Borenstein http://ideasfordozens.com in Feb 2009
7
+ // modified for Sammy by Aaron Quint for caching templates by name
8
+ var srender_cache = {};
9
+ var srender = function(name, template, data) {
10
+ // target is an optional element; if provided, the result will be inserted into it
11
+ // otherwise the result will simply be returned to the caller
12
+ if (srender_cache[name]) {
13
+ fn = srender_cache[name];
14
+ } else {
15
+ if (typeof template == 'undefined') {
16
+ // was a cache check, return false
17
+ return false;
18
+ }
19
+ // Generate a reusable function that will serve as a template
20
+ // generator (and which will be cached).
21
+ fn = srender_cache[name] = new Function("obj",
22
+ "var p=[],print=function(){p.push.apply(p,arguments);};" +
23
+
24
+ // Introduce the data as local variables using with(){}
25
+ "with(obj){p.push(\"" +
26
+
27
+ // Convert the template into pure JavaScript
28
+ template
29
+ .replace(/[\r\t\n]/g, " ")
30
+ .replace(/\"/g, '\\"')
31
+ .split("<%").join("\t")
32
+ .replace(/((^|%>)[^\t]*)/g, "$1\r")
33
+ .replace(/\t=(.*?)%>/g, "\",$1,\"")
34
+ .split("\t").join("\");")
35
+ .split("%>").join("p.push(\"")
36
+ .split("\r").join("")
37
+ + "\");}return p.join('');");
38
+ }
39
+
40
+ if (typeof data != 'undefined') {
41
+ return fn(data);
42
+ } else {
43
+ return fn;
44
+ }
45
+ };
46
+
47
+ Sammy = Sammy || {};
48
+
49
+ // <tt>Sammy.Template</tt> is a simple plugin that provides a way to create
50
+ // and render client side templates. The rendering code is based on John Resig's
51
+ // quick templates and Greg Borenstien's srender plugin.
52
+ // This is also a great template/boilerplate for Sammy plugins.
53
+ //
54
+ // Templates use <% %> tags to denote embedded javascript.
55
+ //
56
+ // ### Examples
57
+ //
58
+ // Here is an example template (user.template):
59
+ //
60
+ // <div class="user">
61
+ // <div class="user-name"><%= user.name %></div>
62
+ // <% if (user.photo_url) { %>
63
+ // <div class="photo"><img src="<%= user.photo_url %>" /></div>
64
+ // <% } %>
65
+ // </div>
66
+ //
67
+ // Given that is a publicly accesible file, you would render it like:
68
+ //
69
+ // $.sammy(function() {
70
+ // // include the plugin
71
+ // this.use(Sammy.Template);
72
+ //
73
+ // this.get('#/', function() {
74
+ // // the template is rendered in the current context.
75
+ // this.user = {name: 'Aaron Quint'};
76
+ // // partial calls template() because of the file extension
77
+ // this.partial('user.template');
78
+ // })
79
+ // });
80
+ //
81
+ // You can also pass a second argument to use() that will alias the template
82
+ // method and therefore allow you to use a different extension for template files
83
+ // in <tt>partial()</tt>
84
+ //
85
+ // // alias to 'tpl'
86
+ // this.use(Sammy.Template, 'tpl');
87
+ //
88
+ // // now .tpl files will be run through srender
89
+ // this.get('#/', function() {
90
+ // this.partial('myfile.tpl');
91
+ // });
92
+ //
93
+ Sammy.Template = function(app, method_alias) {
94
+
95
+ // *Helper:* Uses simple templating to parse ERB like templates.
96
+ //
97
+ // ### Arguments
98
+ //
99
+ // * `template` A String template. '<% %>' tags are evaluated as Javascript and replaced with the elements in data.
100
+ // * `data` An Object containing the replacement values for the template.
101
+ // data is extended with the <tt>EventContext</tt> allowing you to call its methods within the template.
102
+ // * `name` An optional String name to cache the template.
103
+ //
104
+ var template = function(template, data, name) {
105
+ // use name for caching
106
+ if (typeof name == 'undefined') name = template;
107
+ return srender(name, template, $.extend({}, this, data));
108
+ };
109
+
110
+ // set the default method name/extension
111
+ if (!method_alias) method_alias = 'template';
112
+ // create the helper at the method alias
113
+ app.helper(method_alias, template);
114
+
115
+ };
116
+
117
+ })(jQuery);
@@ -0,0 +1,1696 @@
1
+ // name: sammy
2
+ // version: 0.6.0pre
3
+
4
+ (function($) {
5
+
6
+ var Sammy,
7
+ PATH_REPLACER = "([^\/]+)",
8
+ PATH_NAME_MATCHER = /:([\w\d]+)/g,
9
+ QUERY_STRING_MATCHER = /\?([^#]*)$/,
10
+ // mainly for making `arguments` an Array
11
+ _makeArray = function(nonarray) { return Array.prototype.slice.call(nonarray); },
12
+ // borrowed from jQuery
13
+ _isFunction = function( obj ) { return Object.prototype.toString.call(obj) === "[object Function]"; },
14
+ _isArray = function( obj ) { return Object.prototype.toString.call(obj) === "[object Array]"; },
15
+ _decode = decodeURIComponent,
16
+ _escapeHTML = function(s) {
17
+ return s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
18
+ },
19
+ _routeWrapper = function(verb) {
20
+ return function(path, callback) { return this.route.apply(this, [verb, path, callback]); };
21
+ },
22
+ _template_cache = {},
23
+ loggers = [];
24
+
25
+
26
+ // `Sammy` (also aliased as $.sammy) is not only the namespace for a
27
+ // number of prototypes, its also a top level method that allows for easy
28
+ // creation/management of `Sammy.Application` instances. There are a
29
+ // number of different forms for `Sammy()` but each returns an instance
30
+ // of `Sammy.Application`. When a new instance is created using
31
+ // `Sammy` it is added to an Object called `Sammy.apps`. This
32
+ // provides for an easy way to get at existing Sammy applications. Only one
33
+ // instance is allowed per `element_selector` so when calling
34
+ // `Sammy('selector')` multiple times, the first time will create
35
+ // the application and the following times will extend the application
36
+ // already added to that selector.
37
+ //
38
+ // ### Example
39
+ //
40
+ // // returns the app at #main or a new app
41
+ // Sammy('#main')
42
+ //
43
+ // // equivilent to "new Sammy.Application", except appends to apps
44
+ // Sammy();
45
+ // Sammy(function() { ... });
46
+ //
47
+ // // extends the app at '#main' with function.
48
+ // Sammy('#main', function() { ... });
49
+ //
50
+ Sammy = function() {
51
+ var args = _makeArray(arguments),
52
+ app, selector;
53
+ Sammy.apps = Sammy.apps || {};
54
+ if (args.length === 0 || args[0] && _isFunction(args[0])) { // Sammy()
55
+ return Sammy.apply(Sammy, ['body'].concat(args));
56
+ } else if (typeof (selector = args.shift()) == 'string') { // Sammy('#main')
57
+ app = Sammy.apps[selector] || new Sammy.Application();
58
+ app.element_selector = selector;
59
+ if (args.length > 0) {
60
+ $.each(args, function(i, plugin) {
61
+ app.use(plugin);
62
+ });
63
+ }
64
+ // if the selector changes make sure the refrence in Sammy.apps changes
65
+ if (app.element_selector != selector) {
66
+ delete Sammy.apps[selector];
67
+ }
68
+ Sammy.apps[app.element_selector] = app;
69
+ return app;
70
+ }
71
+ };
72
+
73
+ Sammy.VERSION = '0.6.0';
74
+
75
+ // Add to the global logger pool. Takes a function that accepts an
76
+ // unknown number of arguments and should print them or send them somewhere
77
+ // The first argument is always a timestamp.
78
+ Sammy.addLogger = function(logger) {
79
+ loggers.push(logger);
80
+ };
81
+
82
+ // Sends a log message to each logger listed in the global
83
+ // loggers pool. Can take any number of arguments.
84
+ // Also prefixes the arguments with a timestamp.
85
+ Sammy.log = function() {
86
+ var args = _makeArray(arguments);
87
+ args.unshift("[" + Date() + "]");
88
+ $.each(loggers, function(i, logger) {
89
+ logger.apply(Sammy, args);
90
+ });
91
+ };
92
+
93
+ if (typeof window.console != 'undefined') {
94
+ if (_isFunction(console.log.apply)) {
95
+ Sammy.addLogger(function() {
96
+ window.console.log.apply(console, arguments);
97
+ });
98
+ } else {
99
+ Sammy.addLogger(function() {
100
+ window.console.log(arguments);
101
+ });
102
+ }
103
+ } else if (typeof console != 'undefined') {
104
+ Sammy.addLogger(function() {
105
+ console.log.apply(console, arguments);
106
+ });
107
+ }
108
+
109
+ $.extend(Sammy, {
110
+ makeArray: _makeArray,
111
+ isFunction: _isFunction,
112
+ isArray: _isArray
113
+ })
114
+
115
+ // Sammy.Object is the base for all other Sammy classes. It provides some useful
116
+ // functionality, including cloning, iterating, etc.
117
+ Sammy.Object = function(obj) { // constructor
118
+ return $.extend(this, obj || {});
119
+ };
120
+
121
+ $.extend(Sammy.Object.prototype, {
122
+
123
+ // Escape HTML in string, use in templates to prevent script injection.
124
+ // Also aliased as `h()`
125
+ escapeHTML: _escapeHTML,
126
+ h: _escapeHTML,
127
+
128
+ // Returns a copy of the object with Functions removed.
129
+ toHash: function() {
130
+ var json = {};
131
+ $.each(this, function(k,v) {
132
+ if (!_isFunction(v)) {
133
+ json[k] = v;
134
+ }
135
+ });
136
+ return json;
137
+ },
138
+
139
+ // Renders a simple HTML version of this Objects attributes.
140
+ // Does not render functions.
141
+ // For example. Given this Sammy.Object:
142
+ //
143
+ // var s = new Sammy.Object({first_name: 'Sammy', last_name: 'Davis Jr.'});
144
+ // s.toHTML() //=> '<strong>first_name</strong> Sammy<br /><strong>last_name</strong> Davis Jr.<br />'
145
+ //
146
+ toHTML: function() {
147
+ var display = "";
148
+ $.each(this, function(k, v) {
149
+ if (!_isFunction(v)) {
150
+ display += "<strong>" + k + "</strong> " + v + "<br />";
151
+ }
152
+ });
153
+ return display;
154
+ },
155
+
156
+ // Returns an array of keys for this object. If `attributes_only`
157
+ // is true will not return keys that map to a `function()`
158
+ keys: function(attributes_only) {
159
+ var keys = [];
160
+ for (var property in this) {
161
+ if (!_isFunction(this[property]) || !attributes_only) {
162
+ keys.push(property);
163
+ }
164
+ }
165
+ return keys;
166
+ },
167
+
168
+ // Checks if the object has a value at `key` and that the value is not empty
169
+ has: function(key) {
170
+ return this[key] && $.trim(this[key].toString()) != '';
171
+ },
172
+
173
+ // convenience method to join as many arguments as you want
174
+ // by the first argument - useful for making paths
175
+ join: function() {
176
+ var args = _makeArray(arguments);
177
+ var delimiter = args.shift();
178
+ return args.join(delimiter);
179
+ },
180
+
181
+ // Shortcut to Sammy.log
182
+ log: function() {
183
+ Sammy.log.apply(Sammy, arguments);
184
+ },
185
+
186
+ // Returns a string representation of this object.
187
+ // if `include_functions` is true, it will also toString() the
188
+ // methods of this object. By default only prints the attributes.
189
+ toString: function(include_functions) {
190
+ var s = [];
191
+ $.each(this, function(k, v) {
192
+ if (!_isFunction(v) || include_functions) {
193
+ s.push('"' + k + '": ' + v.toString());
194
+ }
195
+ });
196
+ return "Sammy.Object: {" + s.join(',') + "}";
197
+ }
198
+ });
199
+
200
+ // The HashLocationProxy is the default location proxy for all Sammy applications.
201
+ // A location proxy is a prototype that conforms to a simple interface. The purpose
202
+ // of a location proxy is to notify the Sammy.Application its bound to when the location
203
+ // or 'external state' changes. The HashLocationProxy considers the state to be
204
+ // changed when the 'hash' (window.location.hash / '#') changes. It does this in two
205
+ // different ways depending on what browser you are using. The newest browsers
206
+ // (IE, Safari > 4, FF >= 3.6) support a 'onhashchange' DOM event, thats fired whenever
207
+ // the location.hash changes. In this situation the HashLocationProxy just binds
208
+ // to this event and delegates it to the application. In the case of older browsers
209
+ // a poller is set up to track changes to the hash. Unlike Sammy 0.3 or earlier,
210
+ // the HashLocationProxy allows the poller to be a global object, eliminating the
211
+ // need for multiple pollers even when thier are multiple apps on the page.
212
+ Sammy.HashLocationProxy = function(app, run_interval_every) {
213
+ this.app = app;
214
+ // set is native to false and start the poller immediately
215
+ this.is_native = false;
216
+ this._startPolling(run_interval_every);
217
+ };
218
+
219
+ Sammy.HashLocationProxy.prototype = {
220
+
221
+ // bind the proxy events to the current app.
222
+ bind: function() {
223
+ var proxy = this, app = this.app;
224
+ $(window).bind('hashchange.' + this.app.eventNamespace(), function(e, non_native) {
225
+ // if we receive a native hash change event, set the proxy accordingly
226
+ // and stop polling
227
+ if (proxy.is_native === false && !non_native) {
228
+ Sammy.log('native hash change exists, using');
229
+ proxy.is_native = true;
230
+ clearInterval(Sammy.HashLocationProxy._interval);
231
+ }
232
+ app.trigger('location-changed');
233
+ });
234
+ if (!Sammy.HashLocationProxy._bindings) {
235
+ Sammy.HashLocationProxy._bindings = 0;
236
+ }
237
+ Sammy.HashLocationProxy._bindings++;
238
+ },
239
+
240
+ // unbind the proxy events from the current app
241
+ unbind: function() {
242
+ $(window).unbind('hashchange.' + this.app.eventNamespace());
243
+ Sammy.HashLocationProxy._bindings--;
244
+ if (Sammy.HashLocationProxy._bindings <= 0) {
245
+ clearInterval(Sammy.HashLocationProxy._interval);
246
+ }
247
+ },
248
+
249
+ // get the current location from the hash.
250
+ getLocation: function() {
251
+ // Bypass the `window.location.hash` attribute. If a question mark
252
+ // appears in the hash IE6 will strip it and all of the following
253
+ // characters from `window.location.hash`.
254
+ var matches = window.location.toString().match(/^[^#]*(#.+)$/);
255
+ return matches ? matches[1] : '';
256
+ },
257
+
258
+ // set the current location to `new_location`
259
+ setLocation: function(new_location) {
260
+ return (window.location = new_location);
261
+ },
262
+
263
+ _startPolling: function(every) {
264
+ // set up interval
265
+ var proxy = this;
266
+ if (!Sammy.HashLocationProxy._interval) {
267
+ if (!every) { every = 10; }
268
+ var hashCheck = function() {
269
+ current_location = proxy.getLocation();
270
+ if (!Sammy.HashLocationProxy._last_location ||
271
+ current_location != Sammy.HashLocationProxy._last_location) {
272
+ setTimeout(function() {
273
+ $(window).trigger('hashchange', [true]);
274
+ }, 13);
275
+ }
276
+ Sammy.HashLocationProxy._last_location = current_location;
277
+ };
278
+ hashCheck();
279
+ Sammy.HashLocationProxy._interval = setInterval(hashCheck, every);
280
+ }
281
+ }
282
+ };
283
+
284
+
285
+ // Sammy.Application is the Base prototype for defining 'applications'.
286
+ // An 'application' is a collection of 'routes' and bound events that is
287
+ // attached to an element when `run()` is called.
288
+ // The only argument an 'app_function' is evaluated within the context of the application.
289
+ Sammy.Application = function(app_function) {
290
+ var app = this;
291
+ this.routes = {};
292
+ this.listeners = new Sammy.Object({});
293
+ this.arounds = [];
294
+ this.befores = [];
295
+ // generate a unique namespace
296
+ this.namespace = (new Date()).getTime() + '-' + parseInt(Math.random() * 1000, 10);
297
+ this.context_prototype = function() { Sammy.EventContext.apply(this, arguments); };
298
+ this.context_prototype.prototype = new Sammy.EventContext();
299
+
300
+ if (_isFunction(app_function)) {
301
+ app_function.apply(this, [this]);
302
+ }
303
+ // set the location proxy if not defined to the default (HashLocationProxy)
304
+ if (!this._location_proxy) {
305
+ this.setLocationProxy(new Sammy.HashLocationProxy(this, this.run_interval_every));
306
+ }
307
+ if (this.debug) {
308
+ this.bindToAllEvents(function(e, data) {
309
+ app.log(app.toString(), e.cleaned_type, data || {});
310
+ });
311
+ }
312
+ };
313
+
314
+ Sammy.Application.prototype = $.extend({}, Sammy.Object.prototype, {
315
+
316
+ // the four route verbs
317
+ ROUTE_VERBS: ['get','post','put','delete'],
318
+
319
+ // An array of the default events triggered by the
320
+ // application during its lifecycle
321
+ APP_EVENTS: ['run','unload','lookup-route','run-route','route-found','event-context-before','event-context-after','changed','error','check-form-submission','redirect'],
322
+
323
+ _last_route: null,
324
+ _location_proxy: null,
325
+ _running: false,
326
+
327
+ // Defines what element the application is bound to. Provide a selector
328
+ // (parseable by `jQuery()`) and this will be used by `$element()`
329
+ element_selector: 'body',
330
+
331
+ // When set to true, logs all of the default events using `log()`
332
+ debug: false,
333
+
334
+ // When set to true, and the error() handler is not overriden, will actually
335
+ // raise JS errors in routes (500) and when routes can't be found (404)
336
+ raise_errors: false,
337
+
338
+ // The time in milliseconds that the URL is queried for changes
339
+ run_interval_every: 50,
340
+
341
+ // The default template engine to use when using `partial()` in an
342
+ // `EventContext`. `template_engine` can either be a string that
343
+ // corresponds to the name of a method/helper on EventContext or it can be a function
344
+ // that takes two arguments, the content of the unrendered partial and an optional
345
+ // JS object that contains interpolation data. Template engine is only called/refered
346
+ // to if the extension of the partial is null or unknown. See `partial()`
347
+ // for more information
348
+ template_engine: null,
349
+
350
+ // //=> Sammy.Application: body
351
+ toString: function() {
352
+ return 'Sammy.Application:' + this.element_selector;
353
+ },
354
+
355
+ // returns a jQuery object of the Applications bound element.
356
+ $element: function() {
357
+ return $(this.element_selector);
358
+ },
359
+
360
+ // `use()` is the entry point for including Sammy plugins.
361
+ // The first argument to use should be a function() that is evaluated
362
+ // in the context of the current application, just like the `app_function`
363
+ // argument to the `Sammy.Application` constructor.
364
+ //
365
+ // Any additional arguments are passed to the app function sequentially.
366
+ //
367
+ // For much more detail about plugins, check out:
368
+ // http://code.quirkey.com/sammy/doc/plugins.html
369
+ //
370
+ // ### Example
371
+ //
372
+ // var MyPlugin = function(app, prepend) {
373
+ //
374
+ // this.helpers({
375
+ // myhelper: function(text) {
376
+ // alert(prepend + " " + text);
377
+ // }
378
+ // });
379
+ //
380
+ // };
381
+ //
382
+ // var app = $.sammy(function() {
383
+ //
384
+ // this.use(MyPlugin, 'This is my plugin');
385
+ //
386
+ // this.get('#/', function() {
387
+ // this.myhelper('and dont you forget it!');
388
+ // //=> Alerts: This is my plugin and dont you forget it!
389
+ // });
390
+ //
391
+ // });
392
+ //
393
+ // If plugin is passed as a string it assumes your are trying to load
394
+ // Sammy."Plugin". This is the prefered way of loading core Sammy plugins
395
+ // as it allows for better error-messaging.
396
+ //
397
+ // ### Example
398
+ //
399
+ // $.sammy(function() {
400
+ // this.use('Mustache'); //=> Sammy.Mustache
401
+ // this.use('Storage'); //=> Sammy.Storage
402
+ // });
403
+ //
404
+ use: function() {
405
+ // flatten the arguments
406
+ var args = _makeArray(arguments),
407
+ plugin = args.shift(),
408
+ plugin_name = plugin || '';
409
+ try {
410
+ args.unshift(this);
411
+ if (typeof plugin == 'string') {
412
+ plugin_name = 'Sammy.' + plugin;
413
+ plugin = Sammy[plugin];
414
+ }
415
+ plugin.apply(this, args);
416
+ } catch(e) {
417
+ if (typeof plugin === 'undefined') {
418
+ this.error("Plugin Error: called use() but plugin (" + plugin_name.toString() + ") is not defined", e);
419
+ } else if (!_isFunction(plugin)) {
420
+ this.error("Plugin Error: called use() but '" + plugin_name.toString() + "' is not a function", e);
421
+ } else {
422
+ this.error("Plugin Error", e);
423
+ }
424
+ }
425
+ return this;
426
+ },
427
+
428
+ // Sets the location proxy for the current app. By default this is set to
429
+ // a new `Sammy.HashLocationProxy` on initialization. However, you can set
430
+ // the location_proxy inside you're app function to give your app a custom
431
+ // location mechanism. See `Sammy.HashLocationProxy` and `Sammy.DataLocationProxy`
432
+ // for examples.
433
+ //
434
+ // `setLocationProxy()` takes an initialized location proxy.
435
+ //
436
+ // ### Example
437
+ //
438
+ // // to bind to data instead of the default hash;
439
+ // var app = $.sammy(function() {
440
+ // this.setLocationProxy(new Sammy.DataLocationProxy(this));
441
+ // });
442
+ //
443
+ setLocationProxy: function(new_proxy) {
444
+ var original_proxy = this._location_proxy;
445
+ this._location_proxy = new_proxy;
446
+ if (this.isRunning()) {
447
+ if (original_proxy) {
448
+ // if there is already a location proxy, unbind it.
449
+ original_proxy.unbind();
450
+ }
451
+ this._location_proxy.bind();
452
+ }
453
+ },
454
+
455
+ // `route()` is the main method for defining routes within an application.
456
+ // For great detail on routes, check out: http://code.quirkey.com/sammy/doc/routes.html
457
+ //
458
+ // This method also has aliases for each of the different verbs (eg. `get()`, `post()`, etc.)
459
+ //
460
+ // ### Arguments
461
+ //
462
+ // * `verb` A String in the set of ROUTE_VERBS or 'any'. 'any' will add routes for each
463
+ // of the ROUTE_VERBS. If only two arguments are passed,
464
+ // the first argument is the path, the second is the callback and the verb
465
+ // is assumed to be 'any'.
466
+ // * `path` A Regexp or a String representing the path to match to invoke this verb.
467
+ // * `callback` A Function that is called/evaluated whent the route is run see: `runRoute()`.
468
+ // It is also possible to pass a string as the callback, which is looked up as the name
469
+ // of a method on the application.
470
+ //
471
+ route: function(verb, path, callback) {
472
+ var app = this, param_names = [], add_route;
473
+
474
+ // if the method signature is just (path, callback)
475
+ // assume the verb is 'any'
476
+ if (!callback && _isFunction(path)) {
477
+ path = verb;
478
+ callback = path;
479
+ verb = 'any';
480
+ }
481
+
482
+ verb = verb.toLowerCase(); // ensure verb is lower case
483
+
484
+ // if path is a string turn it into a regex
485
+ if (path.constructor == String) {
486
+
487
+ // Needs to be explicitly set because IE will maintain the index unless NULL is returned,
488
+ // which means that with two consecutive routes that contain params, the second set of params will not be found and end up in splat instead of params
489
+ // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/RegExp/lastIndex
490
+ PATH_NAME_MATCHER.lastIndex = 0;
491
+
492
+ // find the names
493
+ while ((path_match = PATH_NAME_MATCHER.exec(path)) !== null) {
494
+ param_names.push(path_match[1]);
495
+ }
496
+ // replace with the path replacement
497
+ path = new RegExp("^" + path.replace(PATH_NAME_MATCHER, PATH_REPLACER) + "$");
498
+ }
499
+ // lookup callback
500
+ if (typeof callback == 'string') {
501
+ callback = app[callback];
502
+ }
503
+
504
+ add_route = function(with_verb) {
505
+ var r = {verb: with_verb, path: path, callback: callback, param_names: param_names};
506
+ // add route to routes array
507
+ app.routes[with_verb] = app.routes[with_verb] || [];
508
+ // place routes in order of definition
509
+ app.routes[with_verb].push(r);
510
+ };
511
+
512
+ if (verb === 'any') {
513
+ $.each(this.ROUTE_VERBS, function(i, v) { add_route(v); });
514
+ } else {
515
+ add_route(verb);
516
+ }
517
+
518
+ // return the app
519
+ return this;
520
+ },
521
+
522
+ // Alias for route('get', ...)
523
+ get: _routeWrapper('get'),
524
+
525
+ // Alias for route('post', ...)
526
+ post: _routeWrapper('post'),
527
+
528
+ // Alias for route('put', ...)
529
+ put: _routeWrapper('put'),
530
+
531
+ // Alias for route('delete', ...)
532
+ del: _routeWrapper('delete'),
533
+
534
+ // Alias for route('any', ...)
535
+ any: _routeWrapper('any'),
536
+
537
+ // `mapRoutes` takes an array of arrays, each array being passed to route()
538
+ // as arguments, this allows for mass definition of routes. Another benefit is
539
+ // this makes it possible/easier to load routes via remote JSON.
540
+ //
541
+ // ### Example
542
+ //
543
+ // var app = $.sammy(function() {
544
+ //
545
+ // this.mapRoutes([
546
+ // ['get', '#/', function() { this.log('index'); }],
547
+ // // strings in callbacks are looked up as methods on the app
548
+ // ['post', '#/create', 'addUser'],
549
+ // // No verb assumes 'any' as the verb
550
+ // [/dowhatever/, function() { this.log(this.verb, this.path)}];
551
+ // ]);
552
+ // })
553
+ //
554
+ mapRoutes: function(route_array) {
555
+ var app = this;
556
+ $.each(route_array, function(i, route_args) {
557
+ app.route.apply(app, route_args);
558
+ });
559
+ return this;
560
+ },
561
+
562
+ // A unique event namespace defined per application.
563
+ // All events bound with `bind()` are automatically bound within this space.
564
+ eventNamespace: function() {
565
+ return ['sammy-app', this.namespace].join('-');
566
+ },
567
+
568
+ // Works just like `jQuery.fn.bind()` with a couple noteable differences.
569
+ //
570
+ // * It binds all events to the application element
571
+ // * All events are bound within the `eventNamespace()`
572
+ // * Events are not actually bound until the application is started with `run()`
573
+ // * callbacks are evaluated within the context of a Sammy.EventContext
574
+ //
575
+ // See http://code.quirkey.com/sammy/docs/events.html for more info.
576
+ //
577
+ bind: function(name, data, callback) {
578
+ var app = this;
579
+ // build the callback
580
+ // if the arity is 2, callback is the second argument
581
+ if (typeof callback == 'undefined') { callback = data; }
582
+ var listener_callback = function() {
583
+ // pull off the context from the arguments to the callback
584
+ var e, context, data;
585
+ e = arguments[0];
586
+ data = arguments[1];
587
+ if (data && data.context) {
588
+ context = data.context;
589
+ delete data.context;
590
+ } else {
591
+ context = new app.context_prototype(app, 'bind', e.type, data, e.target);
592
+ }
593
+ e.cleaned_type = e.type.replace(app.eventNamespace(), '');
594
+ callback.apply(context, [e, data]);
595
+ };
596
+
597
+ // it could be that the app element doesnt exist yet
598
+ // so attach to the listeners array and then run()
599
+ // will actually bind the event.
600
+ if (!this.listeners[name]) { this.listeners[name] = []; }
601
+ this.listeners[name].push(listener_callback);
602
+ if (this.isRunning()) {
603
+ // if the app is running
604
+ // *actually* bind the event to the app element
605
+ this._listen(name, listener_callback);
606
+ }
607
+ return this;
608
+ },
609
+
610
+ // Triggers custom events defined with `bind()`
611
+ //
612
+ // ### Arguments
613
+ //
614
+ // * `name` The name of the event. Automatically prefixed with the `eventNamespace()`
615
+ // * `data` An optional Object that can be passed to the bound callback.
616
+ // * `context` An optional context/Object in which to execute the bound callback.
617
+ // If no context is supplied a the context is a new `Sammy.EventContext`
618
+ //
619
+ trigger: function(name, data) {
620
+ this.$element().trigger([name, this.eventNamespace()].join('.'), [data]);
621
+ return this;
622
+ },
623
+
624
+ // Reruns the current route
625
+ refresh: function() {
626
+ this.last_location = null;
627
+ this.trigger('location-changed');
628
+ return this;
629
+ },
630
+
631
+ // Takes a single callback that is pushed on to a stack.
632
+ // Before any route is run, the callbacks are evaluated in order within
633
+ // the current `Sammy.EventContext`
634
+ //
635
+ // If any of the callbacks explicitly return false, execution of any
636
+ // further callbacks and the route itself is halted.
637
+ //
638
+ // You can also provide a set of options that will define when to run this
639
+ // before based on the route it proceeds.
640
+ //
641
+ // ### Example
642
+ //
643
+ // var app = $.sammy(function() {
644
+ //
645
+ // // will run at #/route but not at #/
646
+ // this.before('#/route', function() {
647
+ // //...
648
+ // });
649
+ //
650
+ // // will run at #/ but not at #/route
651
+ // this.before({except: {path: '#/route'}}, function() {
652
+ // this.log('not before #/route');
653
+ // });
654
+ //
655
+ // this.get('#/', function() {});
656
+ //
657
+ // this.get('#/route', function() {});
658
+ //
659
+ // });
660
+ //
661
+ // See `contextMatchesOptions()` for a full list of supported options
662
+ //
663
+ before: function(options, callback) {
664
+ if (_isFunction(options)) {
665
+ callback = options;
666
+ options = {};
667
+ }
668
+ this.befores.push([options, callback]);
669
+ return this;
670
+ },
671
+
672
+ // A shortcut for binding a callback to be run after a route is executed.
673
+ // After callbacks have no guarunteed order.
674
+ after: function(callback) {
675
+ return this.bind('event-context-after', callback);
676
+ },
677
+
678
+
679
+ // Adds an around filter to the application. around filters are functions
680
+ // that take a single argument `callback` which is the entire route
681
+ // execution path wrapped up in a closure. This means you can decide whether
682
+ // or not to proceed with execution by not invoking `callback` or,
683
+ // more usefuly wrapping callback inside the result of an asynchronous execution.
684
+ //
685
+ // ### Example
686
+ //
687
+ // The most common use case for around() is calling a _possibly_ async function
688
+ // and executing the route within the functions callback:
689
+ //
690
+ // var app = $.sammy(function() {
691
+ //
692
+ // var current_user = false;
693
+ //
694
+ // function checkLoggedIn(callback) {
695
+ // // /session returns a JSON representation of the logged in user
696
+ // // or an empty object
697
+ // if (!current_user) {
698
+ // $.getJSON('/session', function(json) {
699
+ // if (json.login) {
700
+ // // show the user as logged in
701
+ // current_user = json;
702
+ // // execute the route path
703
+ // callback();
704
+ // } else {
705
+ // // show the user as not logged in
706
+ // current_user = false;
707
+ // // the context of aroundFilters is an EventContext
708
+ // this.redirect('#/login');
709
+ // }
710
+ // });
711
+ // } else {
712
+ // // execute the route path
713
+ // callback();
714
+ // }
715
+ // };
716
+ //
717
+ // this.around(checkLoggedIn);
718
+ //
719
+ // });
720
+ //
721
+ around: function(callback) {
722
+ this.arounds.push(callback);
723
+ return this;
724
+ },
725
+
726
+ // Returns `true` if the current application is running.
727
+ isRunning: function() {
728
+ return this._running;
729
+ },
730
+
731
+ // Helpers extends the EventContext prototype specific to this app.
732
+ // This allows you to define app specific helper functions that can be used
733
+ // whenever you're inside of an event context (templates, routes, bind).
734
+ //
735
+ // ### Example
736
+ //
737
+ // var app = $.sammy(function() {
738
+ //
739
+ // helpers({
740
+ // upcase: function(text) {
741
+ // return text.toString().toUpperCase();
742
+ // }
743
+ // });
744
+ //
745
+ // get('#/', function() { with(this) {
746
+ // // inside of this context I can use the helpers
747
+ // $('#main').html(upcase($('#main').text());
748
+ // }});
749
+ //
750
+ // });
751
+ //
752
+ //
753
+ // ### Arguments
754
+ //
755
+ // * `extensions` An object collection of functions to extend the context.
756
+ //
757
+ helpers: function(extensions) {
758
+ $.extend(this.context_prototype.prototype, extensions);
759
+ return this;
760
+ },
761
+
762
+ // Helper extends the event context just like `helpers()` but does it
763
+ // a single method at a time. This is especially useful for dynamically named
764
+ // helpers
765
+ //
766
+ // ### Example
767
+ //
768
+ // // Trivial example that adds 3 helper methods to the context dynamically
769
+ // var app = $.sammy(function(app) {
770
+ //
771
+ // $.each([1,2,3], function(i, num) {
772
+ // app.helper('helper' + num, function() {
773
+ // this.log("I'm helper number " + num);
774
+ // });
775
+ // });
776
+ //
777
+ // this.get('#/', function() {
778
+ // this.helper2(); //=> I'm helper number 2
779
+ // });
780
+ // });
781
+ //
782
+ // ### Arguments
783
+ //
784
+ // * `name` The name of the method
785
+ // * `method` The function to be added to the prototype at `name`
786
+ //
787
+ helper: function(name, method) {
788
+ this.context_prototype.prototype[name] = method;
789
+ return this;
790
+ },
791
+
792
+ // Actually starts the application's lifecycle. `run()` should be invoked
793
+ // within a document.ready block to ensure the DOM exists before binding events, etc.
794
+ //
795
+ // ### Example
796
+ //
797
+ // var app = $.sammy(function() { ... }); // your application
798
+ // $(function() { // document.ready
799
+ // app.run();
800
+ // });
801
+ //
802
+ // ### Arguments
803
+ //
804
+ // * `start_url` Optionally, a String can be passed which the App will redirect to
805
+ // after the events/routes have been bound.
806
+ run: function(start_url) {
807
+ if (this.isRunning()) { return false; }
808
+ var app = this;
809
+
810
+ // actually bind all the listeners
811
+ $.each(this.listeners.toHash(), function(name, callbacks) {
812
+ $.each(callbacks, function(i, listener_callback) {
813
+ app._listen(name, listener_callback);
814
+ });
815
+ });
816
+
817
+ this.trigger('run', {start_url: start_url});
818
+ this._running = true;
819
+ // set last location
820
+ this.last_location = null;
821
+ if (this.getLocation() == '' && typeof start_url != 'undefined') {
822
+ this.setLocation(start_url);
823
+ }
824
+ // check url
825
+ this._checkLocation();
826
+ this._location_proxy.bind();
827
+ this.bind('location-changed', function() {
828
+ app._checkLocation();
829
+ });
830
+
831
+ // bind to submit to capture post/put/delete routes
832
+ this.bind('submit', function(e) {
833
+ var returned = app._checkFormSubmission($(e.target).closest('form'));
834
+ return (returned === false) ? e.preventDefault() : false;
835
+ });
836
+
837
+ // bind unload to body unload
838
+ $(window).bind('beforeunload', function() {
839
+ app.unload();
840
+ });
841
+
842
+ // trigger html changed
843
+ return this.trigger('changed');
844
+ },
845
+
846
+ // The opposite of `run()`, un-binds all event listeners and intervals
847
+ // `run()` Automaticaly binds a `onunload` event to run this when
848
+ // the document is closed.
849
+ unload: function() {
850
+ if (!this.isRunning()) { return false; }
851
+ var app = this;
852
+ this.trigger('unload');
853
+ // clear interval
854
+ this._location_proxy.unbind();
855
+ // unbind form submits
856
+ this.$element().unbind('submit').removeClass(app.eventNamespace());
857
+ // unbind all events
858
+ $.each(this.listeners.toHash() , function(name, listeners) {
859
+ $.each(listeners, function(i, listener_callback) {
860
+ app._unlisten(name, listener_callback);
861
+ });
862
+ });
863
+ this._running = false;
864
+ return this;
865
+ },
866
+
867
+ // Will bind a single callback function to every event that is already
868
+ // being listened to in the app. This includes all the `APP_EVENTS`
869
+ // as well as any custom events defined with `bind()`.
870
+ //
871
+ // Used internally for debug logging.
872
+ bindToAllEvents: function(callback) {
873
+ var app = this;
874
+ // bind to the APP_EVENTS first
875
+ $.each(this.APP_EVENTS, function(i, e) {
876
+ app.bind(e, callback);
877
+ });
878
+ // next, bind to listener names (only if they dont exist in APP_EVENTS)
879
+ $.each(this.listeners.keys(true), function(i, name) {
880
+ if (app.APP_EVENTS.indexOf(name) == -1) {
881
+ app.bind(name, callback);
882
+ }
883
+ });
884
+ return this;
885
+ },
886
+
887
+ // Returns a copy of the given path with any query string after the hash
888
+ // removed.
889
+ routablePath: function(path) {
890
+ return path.replace(QUERY_STRING_MATCHER, '');
891
+ },
892
+
893
+ // Given a verb and a String path, will return either a route object or false
894
+ // if a matching route can be found within the current defined set.
895
+ lookupRoute: function(verb, path) {
896
+ var app = this, routed = false;
897
+ this.trigger('lookup-route', {verb: verb, path: path});
898
+ if (typeof this.routes[verb] != 'undefined') {
899
+ $.each(this.routes[verb], function(i, route) {
900
+ if (app.routablePath(path).match(route.path)) {
901
+ routed = route;
902
+ return false;
903
+ }
904
+ });
905
+ }
906
+ return routed;
907
+ },
908
+
909
+ // First, invokes `lookupRoute()` and if a route is found, parses the
910
+ // possible URL params and then invokes the route's callback within a new
911
+ // `Sammy.EventContext`. If the route can not be found, it calls
912
+ // `notFound()`. If `raise_errors` is set to `true` and
913
+ // the `error()` has not been overriden, it will throw an actual JS
914
+ // error.
915
+ //
916
+ // You probably will never have to call this directly.
917
+ //
918
+ // ### Arguments
919
+ //
920
+ // * `verb` A String for the verb.
921
+ // * `path` A String path to lookup.
922
+ // * `params` An Object of Params pulled from the URI or passed directly.
923
+ //
924
+ // ### Returns
925
+ //
926
+ // Either returns the value returned by the route callback or raises a 404 Not Found error.
927
+ //
928
+ runRoute: function(verb, path, params, target) {
929
+ var app = this,
930
+ route = this.lookupRoute(verb, path),
931
+ context,
932
+ wrapped_route,
933
+ arounds,
934
+ around,
935
+ befores,
936
+ before,
937
+ callback_args,
938
+ final_returned;
939
+
940
+ this.log('runRoute', [verb, path].join(' '));
941
+ this.trigger('run-route', {verb: verb, path: path, params: params});
942
+ if (typeof params == 'undefined') { params = {}; }
943
+
944
+ $.extend(params, this._parseQueryString(path));
945
+
946
+ if (route) {
947
+ this.trigger('route-found', {route: route});
948
+ // pull out the params from the path
949
+ if ((path_params = route.path.exec(this.routablePath(path))) !== null) {
950
+ // first match is the full path
951
+ path_params.shift();
952
+ // for each of the matches
953
+ $.each(path_params, function(i, param) {
954
+ // if theres a matching param name
955
+ if (route.param_names[i]) {
956
+ // set the name to the match
957
+ params[route.param_names[i]] = _decode(param);
958
+ } else {
959
+ // initialize 'splat'
960
+ if (!params.splat) { params.splat = []; }
961
+ params.splat.push(_decode(param));
962
+ }
963
+ });
964
+ }
965
+
966
+ // set event context
967
+ context = new this.context_prototype(this, verb, path, params, target);
968
+ // ensure arrays
969
+ arounds = this.arounds.slice(0);
970
+ befores = this.befores.slice(0);
971
+ // set the callback args to the context + contents of the splat
972
+ callback_args = [context].concat(params.splat);
973
+ // wrap the route up with the before filters
974
+ wrapped_route = function() {
975
+ var returned;
976
+ while (befores.length > 0) {
977
+ before = befores.shift();
978
+ // check the options
979
+ if (app.contextMatchesOptions(context, before[0])) {
980
+ returned = before[1].apply(context, [context]);
981
+ if (returned === false) { return false; }
982
+ }
983
+ }
984
+ app.last_route = route;
985
+ context.trigger('event-context-before', {context: context});
986
+ returned = route.callback.apply(context, callback_args);
987
+ context.trigger('event-context-after', {context: context});
988
+ return returned;
989
+ };
990
+ $.each(arounds.reverse(), function(i, around) {
991
+ var last_wrapped_route = wrapped_route;
992
+ wrapped_route = function() { return around.apply(context, [last_wrapped_route]); };
993
+ });
994
+ try {
995
+ final_returned = wrapped_route();
996
+ } catch(e) {
997
+ this.error(['500 Error', verb, path].join(' '), e);
998
+ }
999
+ return final_returned;
1000
+ } else {
1001
+ return this.notFound(verb, path);
1002
+ }
1003
+ },
1004
+
1005
+ // Matches an object of options against an `EventContext` like object that
1006
+ // contains `path` and `verb` attributes. Internally Sammy uses this
1007
+ // for matching `before()` filters against specific options. You can set the
1008
+ // object to _only_ match certain paths or verbs, or match all paths or verbs _except_
1009
+ // those that match the options.
1010
+ //
1011
+ // ### Example
1012
+ //
1013
+ // var app = $.sammy(),
1014
+ // context = {verb: 'get', path: '#/mypath'};
1015
+ //
1016
+ // // match against a path string
1017
+ // app.contextMatchesOptions(context, '#/mypath'); //=> true
1018
+ // app.contextMatchesOptions(context, '#/otherpath'); //=> false
1019
+ // // equivilent to
1020
+ // app.contextMatchesOptions(context, {only: {path:'#/mypath'}}); //=> true
1021
+ // app.contextMatchesOptions(context, {only: {path:'#/otherpath'}}); //=> false
1022
+ // // match against a path regexp
1023
+ // app.contextMatchesOptions(context, /path/); //=> true
1024
+ // app.contextMatchesOptions(context, /^path/); //=> false
1025
+ // // match only a verb
1026
+ // app.contextMatchesOptions(context, {only: {verb:'get'}}); //=> true
1027
+ // app.contextMatchesOptions(context, {only: {verb:'post'}}); //=> false
1028
+ // // match all except a verb
1029
+ // app.contextMatchesOptions(context, {except: {verb:'post'}}); //=> true
1030
+ // app.contextMatchesOptions(context, {except: {verb:'get'}}); //=> false
1031
+ // // match all except a path
1032
+ // app.contextMatchesOptions(context, {except: {path:'#/otherpath'}}); //=> true
1033
+ // app.contextMatchesOptions(context, {except: {path:'#/mypath'}}); //=> false
1034
+ //
1035
+ contextMatchesOptions: function(context, match_options, positive) {
1036
+ // empty options always match
1037
+ var options = match_options;
1038
+ if (typeof options === 'undefined' || options == {}) {
1039
+ return true;
1040
+ }
1041
+ if (typeof positive === 'undefined') {
1042
+ positive = true;
1043
+ }
1044
+ // normalize options
1045
+ if (typeof options === 'string' || _isFunction(options.test)) {
1046
+ options = {path: options};
1047
+ }
1048
+ if (options.only) {
1049
+ return this.contextMatchesOptions(context, options.only, true);
1050
+ } else if (options.except) {
1051
+ return this.contextMatchesOptions(context, options.except, false);
1052
+ }
1053
+ var path_matched = true, verb_matched = true;
1054
+ if (options.path) {
1055
+ // wierd regexp test
1056
+ if (_isFunction(options.path.test)) {
1057
+ path_matched = options.path.test(context.path);
1058
+ } else {
1059
+ path_matched = (options.path.toString() === context.path);
1060
+ }
1061
+ }
1062
+ if (options.verb) {
1063
+ verb_matched = options.verb === context.verb;
1064
+ }
1065
+ return positive ? (verb_matched && path_matched) : !(verb_matched && path_matched);
1066
+ },
1067
+
1068
+
1069
+ // Delegates to the `location_proxy` to get the current location.
1070
+ // See `Sammy.HashLocationProxy` for more info on location proxies.
1071
+ getLocation: function() {
1072
+ return this._location_proxy.getLocation();
1073
+ },
1074
+
1075
+ // Delegates to the `location_proxy` to set the current location.
1076
+ // See `Sammy.HashLocationProxy` for more info on location proxies.
1077
+ //
1078
+ // ### Arguments
1079
+ //
1080
+ // * `new_location` A new location string (e.g. '#/')
1081
+ //
1082
+ setLocation: function(new_location) {
1083
+ return this._location_proxy.setLocation(new_location);
1084
+ },
1085
+
1086
+ // Swaps the content of `$element()` with `content`
1087
+ // You can override this method to provide an alternate swap behavior
1088
+ // for `EventContext.partial()`.
1089
+ //
1090
+ // ### Example
1091
+ //
1092
+ // var app = $.sammy(function() {
1093
+ //
1094
+ // // implements a 'fade out'/'fade in'
1095
+ // this.swap = function(content) {
1096
+ // this.$element().hide('slow').html(content).show('slow');
1097
+ // }
1098
+ //
1099
+ // get('#/', function() {
1100
+ // this.partial('index.html.erb') // will fade out and in
1101
+ // });
1102
+ //
1103
+ // });
1104
+ //
1105
+ swap: function(content) {
1106
+ return this.$element().html(content);
1107
+ },
1108
+
1109
+ // a simple global cache for templates. Uses the same semantics as
1110
+ // `Sammy.Cache` and `Sammy.Storage` so can easily be replaced with
1111
+ // a persistant storage that lasts beyond the current request.
1112
+ templateCache: function(key, value) {
1113
+ if (typeof value != 'undefined') {
1114
+ return _template_cache[key] = value;
1115
+ } else {
1116
+ return _template_cache[key];
1117
+ }
1118
+ },
1119
+
1120
+ // This thows a '404 Not Found' error by invoking `error()`.
1121
+ // Override this method or `error()` to provide custom
1122
+ // 404 behavior (i.e redirecting to / or showing a warning)
1123
+ notFound: function(verb, path) {
1124
+ var ret = this.error(['404 Not Found', verb, path].join(' '));
1125
+ return (verb === 'get') ? ret : true;
1126
+ },
1127
+
1128
+ // The base error handler takes a string `message` and an `Error`
1129
+ // object. If `raise_errors` is set to `true` on the app level,
1130
+ // this will re-throw the error to the browser. Otherwise it will send the error
1131
+ // to `log()`. Override this method to provide custom error handling
1132
+ // e.g logging to a server side component or displaying some feedback to the
1133
+ // user.
1134
+ error: function(message, original_error) {
1135
+ if (!original_error) { original_error = new Error(); }
1136
+ original_error.message = [message, original_error.message].join(' ');
1137
+ this.trigger('error', {message: original_error.message, error: original_error});
1138
+ if (this.raise_errors) {
1139
+ throw(original_error);
1140
+ } else {
1141
+ this.log(original_error.message, original_error);
1142
+ }
1143
+ },
1144
+
1145
+ _checkLocation: function() {
1146
+ var location, returned;
1147
+ // get current location
1148
+ location = this.getLocation();
1149
+ // compare to see if hash has changed
1150
+ if (location != this.last_location) {
1151
+ // reset last location
1152
+ this.last_location = location;
1153
+ // lookup route for current hash
1154
+ returned = this.runRoute('get', location);
1155
+ }
1156
+ return returned;
1157
+ },
1158
+
1159
+ _getFormVerb: function(form) {
1160
+ var $form = $(form), verb;
1161
+ $_method = $form.find('input[name="_method"]');
1162
+ if ($_method.length > 0) { verb = $_method.val(); }
1163
+ if (!verb) { verb = $form[0].getAttribute('method'); }
1164
+ return $.trim(verb.toString().toLowerCase());
1165
+ },
1166
+
1167
+ _checkFormSubmission: function(form) {
1168
+ var $form, path, verb, params, returned;
1169
+ this.trigger('check-form-submission', {form: form});
1170
+ $form = $(form);
1171
+ path = $form.attr('action');
1172
+ verb = this._getFormVerb($form);
1173
+ if (!verb || verb == '') { verb = 'get'; }
1174
+ this.log('_checkFormSubmission', $form, path, verb);
1175
+ if (verb === 'get') {
1176
+ this.setLocation(path + '?' + $form.serialize());
1177
+ returned = false;
1178
+ } else {
1179
+ params = $.extend({}, this._parseFormParams($form));
1180
+ returned = this.runRoute(verb, path, params, form.get(0));
1181
+ };
1182
+ return (typeof returned == 'undefined') ? false : returned;
1183
+ },
1184
+
1185
+ _parseFormParams: function($form) {
1186
+ var params = {},
1187
+ form_fields = $form.serializeArray(),
1188
+ i;
1189
+ for (i = 0; i < form_fields.length; i++) {
1190
+ params = this._parseParamPair(params, form_fields[i].name, form_fields[i].value);
1191
+ }
1192
+ return params;
1193
+ },
1194
+
1195
+ _parseQueryString: function(path) {
1196
+ var params = {}, parts, pairs, pair, i;
1197
+
1198
+ parts = path.match(QUERY_STRING_MATCHER);
1199
+ if (parts) {
1200
+ pairs = parts[1].split('&');
1201
+ for (i = 0; i < pairs.length; i++) {
1202
+ pair = pairs[i].split('=');
1203
+ params = this._parseParamPair(params, _decode(pair[0]), _decode(pair[1]));
1204
+ }
1205
+ }
1206
+ return params;
1207
+ },
1208
+
1209
+ _parseParamPair: function(params, key, value) {
1210
+ if (params[key]) {
1211
+ if (_isArray(params[key])) {
1212
+ params[key].push(value);
1213
+ } else {
1214
+ params[key] = [params[key], value];
1215
+ }
1216
+ } else {
1217
+ params[key] = value;
1218
+ }
1219
+ return params;
1220
+ },
1221
+
1222
+ _listen: function(name, callback) {
1223
+ return this.$element().bind([name, this.eventNamespace()].join('.'), callback);
1224
+ },
1225
+
1226
+ _unlisten: function(name, callback) {
1227
+ return this.$element().unbind([name, this.eventNamespace()].join('.'), callback);
1228
+ }
1229
+
1230
+ });
1231
+
1232
+ // `Sammy.RenderContext` is an object that makes sequential template loading,
1233
+ // rendering and interpolation seamless even when dealing with asyncronous
1234
+ // operations.
1235
+ //
1236
+ // `RenderContext` objects are not usually created directly, rather they are
1237
+ // instatiated from an `Sammy.EventContext` by using `render()`, `load()` or
1238
+ // `partial()` which all return `RenderContext` objects.
1239
+ //
1240
+ // `RenderContext` methods always returns a modified `RenderContext`
1241
+ // for chaining (like jQuery itself).
1242
+ //
1243
+ // The core magic is in the `then()` method which puts the callback passed as
1244
+ // an argument into a queue to be executed once the previous callback is complete.
1245
+ // All the methods of `RenderContext` are wrapped in `then()` which allows you
1246
+ // to queue up methods by chaining, but maintaing a guarunteed execution order
1247
+ // even with remote calls to fetch templates.
1248
+ //
1249
+ Sammy.RenderContext = function(event_context) {
1250
+ this.event_context = event_context;
1251
+ this.callbacks = [];
1252
+ this.previous_content = null;
1253
+ this.content = null;
1254
+ this.next_engine = false;
1255
+ this.waiting = false;
1256
+ };
1257
+
1258
+ $.extend(Sammy.RenderContext.prototype, {
1259
+
1260
+ // The "core" of the `RenderContext` object, adds the `callback` to the
1261
+ // queue. If the context is `waiting` (meaning an async operation is happening)
1262
+ // then the callback will be executed in order, once the other operations are
1263
+ // complete. If there is no currently executing operation, the `callback`
1264
+ // is executed immediately.
1265
+ //
1266
+ // The value returned from the callback is stored in `content` for the
1267
+ // subsiquent operation. If you return `false`, the queue will pause, and
1268
+ // the next callback in the queue will not be executed until `next()` is
1269
+ // called. This allows for the guarunteed order of execution while working
1270
+ // with async operations.
1271
+ //
1272
+ // ### Example
1273
+ //
1274
+ // this.get('#/', function() {
1275
+ // // initialize the RenderContext
1276
+ // // Even though `load()` executes async, the next `then()`
1277
+ // // wont execute until the load finishes
1278
+ // this.load('myfile.txt')
1279
+ // .then(function(content) {
1280
+ // // the first argument to then is the content of the
1281
+ // // prev operation
1282
+ // $('#main').html(content);
1283
+ // });
1284
+ // });
1285
+ //
1286
+ then: function(callback) {
1287
+ if (_isFunction(callback)) {
1288
+ var context = this;
1289
+ if (this.waiting) {
1290
+ this.callbacks.push(callback);
1291
+ } else {
1292
+ this.wait();
1293
+ setTimeout(function() {
1294
+ var returned = callback.apply(context, [context.content, context.previous_content]);
1295
+ if (returned !== false) {
1296
+ context.next(returned);
1297
+ }
1298
+ }, 13);
1299
+ }
1300
+ }
1301
+ return this;
1302
+ },
1303
+
1304
+ // Pause the `RenderContext` queue. Combined with `next()` allows for async
1305
+ // operations.
1306
+ //
1307
+ // ### Example
1308
+ //
1309
+ // this.get('#/', function() {
1310
+ // this.load('mytext.json')
1311
+ // .then(function(content) {
1312
+ // var context = this,
1313
+ // data = JSON.parse(content);
1314
+ // // pause execution
1315
+ // context.wait();
1316
+ // // post to a url
1317
+ // $.post(data.url, {}, function(response) {
1318
+ // context.next(JSON.parse(response));
1319
+ // });
1320
+ // })
1321
+ // .then(function(data) {
1322
+ // // data is json from the previous post
1323
+ // $('#message').text(data.status);
1324
+ // });
1325
+ // });
1326
+ wait: function() {
1327
+ this.waiting = true;
1328
+ },
1329
+
1330
+ // Resume the queue, setting `content` to be used in the next operation.
1331
+ // See `wait()` for an example.
1332
+ next: function(content) {
1333
+ this.waiting = false;
1334
+ if (typeof content !== 'undefined') {
1335
+ this.previous_content = this.content;
1336
+ this.content = content;
1337
+ }
1338
+ if (this.callbacks.length > 0) {
1339
+ this.then(this.callbacks.shift());
1340
+ }
1341
+ },
1342
+
1343
+ // Load a template into the context.
1344
+ // The `location` can either be a string specifiying the remote path to the
1345
+ // file, a jQuery object, or a DOM element.
1346
+ //
1347
+ // No interpolation happens by default, the content is stored in
1348
+ // `content`.
1349
+ //
1350
+ // In the case of a path, unless the option `{cache: false}` is passed the
1351
+ // data is stored in the app's `templateCache()`.
1352
+ //
1353
+ // If a jQuery or DOM object is passed the `innerHTML` of the node is pulled in.
1354
+ // This is useful for nesting templates as part of the initial page load wrapped
1355
+ // in invisible elements or `<script>` tags. With template paths, the template
1356
+ // engine is looked up by the extension. For DOM/jQuery embedded templates,
1357
+ // this isnt possible, so there are a couple of options:
1358
+ //
1359
+ // * pass an `{engine:}` option.
1360
+ // * define the engine in the `data-engine` attribute of the passed node.
1361
+ // * just store the raw template data and use `interpolate()` manually
1362
+ //
1363
+ // If a `callback` is passed it is executed after the template load.
1364
+ load: function(location, options, callback) {
1365
+ var context = this;
1366
+ return this.then(function() {
1367
+ var should_cache, cached;
1368
+ if (_isFunction(options)) {
1369
+ callback = options;
1370
+ options = {};
1371
+ } else {
1372
+ options = $.extend({}, options);
1373
+ }
1374
+ if (callback) { this.then(callback); }
1375
+ if (typeof location === 'string') {
1376
+ // its a path
1377
+ should_cache = !(options.cache === false);
1378
+ delete options.cache;
1379
+ if (options.engine) {
1380
+ context.next_engine = options.engine;
1381
+ delete options.engine;
1382
+ }
1383
+ if (should_cache && (cached = this.event_context.app.templateCache(location))) {
1384
+ return cached;
1385
+ }
1386
+ this.wait();
1387
+ $.ajax($.extend({
1388
+ url: location,
1389
+ data: {},
1390
+ type: 'get',
1391
+ success: function(data) {
1392
+ if (should_cache) {
1393
+ context.event_context.app.templateCache(location, data);
1394
+ }
1395
+ context.next(data);
1396
+ }
1397
+ }, options));
1398
+ return false;
1399
+ } else {
1400
+ // its a dom/jQuery
1401
+ if (location.nodeType) {
1402
+ return location.innerHTML;
1403
+ }
1404
+ if (location.selector) {
1405
+ // its a jQuery
1406
+ context.next_engine = location.attr('data-engine');
1407
+ if (options.clone === false) {
1408
+ return location.remove()[0].innerHTML.toString();
1409
+ } else {
1410
+ return location[0].innerHTML.toString();
1411
+ }
1412
+ }
1413
+ }
1414
+ });
1415
+ },
1416
+
1417
+ // `load()` a template and then `interpolate()` it with data.
1418
+ //
1419
+ // ### Example
1420
+ //
1421
+ // this.get('#/', function() {
1422
+ // this.render('mytemplate.template', {name: 'test'});
1423
+ // });
1424
+ //
1425
+ render: function(location, data, callback) {
1426
+ if (_isFunction(location) && !data) {
1427
+ return this.then(location);
1428
+ } else {
1429
+ return this.load(location).interpolate(data, location).then(callback);
1430
+ }
1431
+ },
1432
+
1433
+ // itterates over an array, applying the callback for each item item. the
1434
+ // callback takes the same style of arguments as `jQuery.each()` (index, item).
1435
+ // The return value of each callback is collected as a single string and stored
1436
+ // as `content` to be used in the next iteration of the `RenderContext`.
1437
+ collect: function(array, callback) {
1438
+ var context = this;
1439
+ return this.then(function() {
1440
+ var contents = "";
1441
+ $.each(array, function(i, item) {
1442
+ var returned = callback.apply(context, [i, item]);
1443
+ contents += returned;
1444
+ return returned;
1445
+ });
1446
+ return contents;
1447
+ });
1448
+ },
1449
+
1450
+ // loads a template, and then interpolates it for each item in the `data`
1451
+ // array.
1452
+ renderEach: function(location, name, data, callback) {
1453
+ if (_isArray(name)) {
1454
+ callback = data;
1455
+ data = name;
1456
+ name = null;
1457
+ }
1458
+ if (!data && _isArray(this.content)) {
1459
+ data = this.content;
1460
+ }
1461
+ return this.load(location).collect(data, function(i, value) {
1462
+ var idata = {};
1463
+ name ? (idata[name] = value) : (idata = value);
1464
+ return this.event_context.interpolate(this.content, idata, location);
1465
+ });
1466
+ },
1467
+
1468
+ // uses the previous loaded `content` and the `data` object to interpolate
1469
+ // a template. `engine` defines the templating/interpolation method/engine
1470
+ // that should be used. If `engine` is not passed, the `next_engine` is
1471
+ // used. If `retain` is `true`, the final interpolated data is appended to
1472
+ // the `previous_content` instead of just replacing it.
1473
+ interpolate: function(data, engine, retain) {
1474
+ var context = this;
1475
+ return this.then(function(content, prev) {
1476
+ if (this.next_engine) {
1477
+ engine = this.next_engine;
1478
+ this.next_engine = false;
1479
+ }
1480
+ var rendered = context.event_context.interpolate(content, data, engine);
1481
+ return retain ? prev + rendered : rendered;
1482
+ });
1483
+ },
1484
+
1485
+ // executes `EventContext#swap()` with the `content`
1486
+ swap: function() {
1487
+ return this.then(function(content) {
1488
+ this.event_context.swap(content);
1489
+ }).trigger('changed', {});
1490
+ },
1491
+
1492
+ // Same usage as `jQuery.fn.appendTo()` but uses `then()` to ensure order
1493
+ appendTo: function(selector) {
1494
+ return this.then(function(content) {
1495
+ $(selector).append(content);
1496
+ }).trigger('changed', {});
1497
+ },
1498
+
1499
+ // Same usage as `jQuery.fn.prependTo()` but uses `then()` to ensure order
1500
+ prependTo: function(selector) {
1501
+ return this.then(function(content) {
1502
+ $(selector).prepend(content);
1503
+ }).trigger('changed', {});
1504
+ },
1505
+
1506
+ // Replaces the `$(selector)` using `html()` with the previously loaded
1507
+ // `content`
1508
+ replace: function(selector) {
1509
+ return this.then(function(content) {
1510
+ $(selector).html(content);
1511
+ }).trigger('changed', {});
1512
+ },
1513
+
1514
+ // trigger the event in the order of the event context. Same semantics
1515
+ // as `Sammy.EventContext#trigger()`. If data is ommitted, `content`
1516
+ // is sent as `{content: content}`
1517
+ trigger: function(name, data) {
1518
+ return this.then(function(content) {
1519
+ if (typeof data == 'undefined') { data = {content: content}; }
1520
+ this.event_context.trigger(name, data);
1521
+ });
1522
+ }
1523
+
1524
+ });
1525
+
1526
+ // `Sammy.EventContext` objects are created every time a route is run or a
1527
+ // bound event is triggered. The callbacks for these events are evaluated within a `Sammy.EventContext`
1528
+ // This within these callbacks the special methods of `EventContext` are available.
1529
+ //
1530
+ // ### Example
1531
+ //
1532
+ // $.sammy(function() {
1533
+ // // The context here is this Sammy.Application
1534
+ // this.get('#/:name', function() {
1535
+ // // The context here is a new Sammy.EventContext
1536
+ // if (this.params['name'] == 'sammy') {
1537
+ // this.partial('name.html.erb', {name: 'Sammy'});
1538
+ // } else {
1539
+ // this.redirect('#/somewhere-else')
1540
+ // }
1541
+ // });
1542
+ // });
1543
+ //
1544
+ // Initialize a new EventContext
1545
+ //
1546
+ // ### Arguments
1547
+ //
1548
+ // * `app` The `Sammy.Application` this event is called within.
1549
+ // * `verb` The verb invoked to run this context/route.
1550
+ // * `path` The string path invoked to run this context/route.
1551
+ // * `params` An Object of optional params to pass to the context. Is converted
1552
+ // to a `Sammy.Object`.
1553
+ // * `target` a DOM element that the event that holds this context originates
1554
+ // from. For post, put and del routes, this is the form element that triggered
1555
+ // the route.
1556
+ //
1557
+ Sammy.EventContext = function(app, verb, path, params, target) {
1558
+ this.app = app;
1559
+ this.verb = verb;
1560
+ this.path = path;
1561
+ this.params = new Sammy.Object(params);
1562
+ this.target = target;
1563
+ };
1564
+
1565
+ Sammy.EventContext.prototype = $.extend({}, Sammy.Object.prototype, {
1566
+
1567
+ // A shortcut to the app's `$element()`
1568
+ $element: function() {
1569
+ return this.app.$element();
1570
+ },
1571
+
1572
+ // Look up a templating engine within the current app and context.
1573
+ // `engine` can be one of the following:
1574
+ //
1575
+ // * a function: should conform to `function(content, data) { return interploated; }`
1576
+ // * a template path: 'template.ejs', looks up the extension to match to
1577
+ // the `ejs()` helper
1578
+ // * a string referering to the helper: "mustache" => `mustache()`
1579
+ //
1580
+ // If no engine is found, use the app's default `template_engine`
1581
+ //
1582
+ engineFor: function(engine) {
1583
+ var context = this, engine_match;
1584
+ // if path is actually an engine function just return it
1585
+ if (_isFunction(engine)) { return engine; }
1586
+ // lookup engine name by path extension
1587
+ engine = engine.toString();
1588
+ if ((engine_match = engine.match(/\.([^\.]+)$/))) {
1589
+ engine = engine_match[1];
1590
+ }
1591
+ // set the engine to the default template engine if no match is found
1592
+ if (engine && _isFunction(context[engine])) {
1593
+ return context[engine];
1594
+ }
1595
+ if (context.app.template_engine) {
1596
+ return this.engineFor(context.app.template_engine);
1597
+ }
1598
+ return function(content, data) { return content; };
1599
+ },
1600
+
1601
+ // using the template `engine` found with `engineFor()`, interpolate the
1602
+ // `data` into `content`
1603
+ interpolate: function(content, data, engine) {
1604
+ return this.engineFor(engine).apply(this, [content, data]);
1605
+ },
1606
+
1607
+ // Create and return a `Sammy.RenderContext` calling `render()` on it.
1608
+ // Loads the template and interpolate the data, however does not actual
1609
+ // place it in the DOM.
1610
+ //
1611
+ // ### Example
1612
+ //
1613
+ // // mytemplate.mustache <div class="name">{{name}}</div>
1614
+ // render('mytemplate.mustache', {name: 'quirkey'});
1615
+ // // sets the `content` to <div class="name">quirkey</div>
1616
+ // render('mytemplate.mustache', {name: 'quirkey'})
1617
+ // .appendTo('ul');
1618
+ // // appends the rendered content to $('ul')
1619
+ //
1620
+ render: function(location, data, callback) {
1621
+ return new Sammy.RenderContext(this).render(location, data, callback);
1622
+ },
1623
+
1624
+ // create a new `Sammy.RenderContext` calling `load()` with `location` and
1625
+ // `options`. Called without interpolation or placement, this allows for
1626
+ // preloading/caching the templates.
1627
+ load: function(location, options, callback) {
1628
+ return new Sammy.RenderContext(this).load(location, options, callback);
1629
+ },
1630
+
1631
+ // `render()` the the `location` with `data` and then `swap()` the
1632
+ // app's `$element` with the rendered content.
1633
+ partial: function(location, data) {
1634
+ return this.render(location, data).swap();
1635
+ },
1636
+
1637
+ // Changes the location of the current window. If `to` begins with
1638
+ // '#' it only changes the document's hash. If passed more than 1 argument
1639
+ // redirect will join them together with forward slashes.
1640
+ //
1641
+ // ### Example
1642
+ //
1643
+ // redirect('#/other/route');
1644
+ // // equivilent to
1645
+ // redirect('#', 'other', 'route');
1646
+ //
1647
+ redirect: function() {
1648
+ var to, args = _makeArray(arguments),
1649
+ current_location = this.app.getLocation();
1650
+ if (args.length > 1) {
1651
+ args.unshift('/');
1652
+ to = this.join.apply(this, args);
1653
+ } else {
1654
+ to = args[0];
1655
+ }
1656
+ this.trigger('redirect', {to: to});
1657
+ this.app.last_location = this.path;
1658
+ this.app.setLocation(to);
1659
+ if (current_location == to) {
1660
+ this.app.trigger('location-changed');
1661
+ }
1662
+ },
1663
+
1664
+ // Triggers events on `app` within the current context.
1665
+ trigger: function(name, data) {
1666
+ if (typeof data == 'undefined') { data = {}; }
1667
+ if (!data.context) { data.context = this; }
1668
+ return this.app.trigger(name, data);
1669
+ },
1670
+
1671
+ // A shortcut to app's `eventNamespace()`
1672
+ eventNamespace: function() {
1673
+ return this.app.eventNamespace();
1674
+ },
1675
+
1676
+ // A shortcut to app's `swap()`
1677
+ swap: function(contents) {
1678
+ return this.app.swap(contents);
1679
+ },
1680
+
1681
+ // Raises a possible `notFound()` error for the current path.
1682
+ notFound: function() {
1683
+ return this.app.notFound(this.verb, this.path);
1684
+ },
1685
+
1686
+ // //=> Sammy.EventContext: get #/ {}
1687
+ toString: function() {
1688
+ return "Sammy.EventContext: " + [this.verb, this.path, this.params].join(' ');
1689
+ }
1690
+
1691
+ });
1692
+
1693
+ // An alias to Sammy
1694
+ $.sammy = window.Sammy = Sammy;
1695
+
1696
+ })(jQuery);