Add assertion API to jQuery.
authorFlorent Bruneau <florent.bruneau@polytechnique.org>
Tue, 18 Jan 2011 20:38:19 +0000 (21:38 +0100)
committerFlorent Bruneau <florent.bruneau@polytechnique.org>
Tue, 18 Jan 2011 20:38:19 +0000 (21:38 +0100)
Signed-off-by: Florent Bruneau <florent.bruneau@polytechnique.org>
htdocs/javascript/core.js

index d9f38f3..bf0e5d1 100644 (file)
  *  59 Temple Place, Suite 330, Boston, MA  02111-1307  USA                *
  ***************************************************************************/
 
+// {{{ Assertion
+
+// }}}
 // {{{ jQuery object extension
 
 (function($) {
+    function assert(condition, text) {
+        if ($.isFunction(condition)) {
+            condition = condition();
+        }
+        if (condition) {
+            return this;
+        }
+        if (!text) {
+            throw "Assertion failed";
+        } else {
+            throw "Assertion failed: " + text;
+        }
+    }
+
+
     /* Add new functions to jQuery namesapce */
     $.extend({
         /* The goal of the following functions is to provide an AJAX API that
             }
             $('body').appendTo(form);
             form.submit();
-        }
+        },
+
+        assert: assert
     });
 
     /* Add new functions to jQuery objects */
                            +'width='+w+',height='+h);
                 return false;
             });
+        },
+
+        assert: assert,
+
+        assertLength: function(len) {
+            return this.assert(function() {
+                return $(this).length == len;
+            });
+        },
+
+        assertId: function(id) {
+            return this.assert(function() {
+                return $(this).attr('id') == id;
+            });
+        },
+
+        assertClass: function(clazz) {
+            return this.assert(function() {
+                return $(this).hasClass(clazz);
+            });
         }
     });
 })(jQuery);