jalexiscv / base2

Automatically exported from code.google.com/p/base2
0 stars 0 forks source link

Allow Base cast specialization #149

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
This is not a bug but a feature request

I love the builtin casting ability of Base, but there are situations where I 
would like to customize coercion.  I have enclosed a small patch to enhance 
Base with this ability.  

Basically, it will look for a static coerce method in the class or its 
ancestors.  If one is found, it is called and the return value is used as the 
cast.  Otherwise, the default casting is performed. 

What version of the product are you using? On what operating system?
Currently on Mac OS X 10.9.4

Here is the diff (attached as well)

Index: base2/Base.js
===================================================================
--- base2/Base.js   (revision 310)
+++ base2/Base.js   (working copy)
@@ -23,6 +23,12 @@
         delete this.__constructing;
       } else {
         // Casting.
+        var coerce = _class;
+        do {
+          if (coerce.coerce)
+            return coerce.coerce.call(_class, arguments[0]);
+          coerce = coerce.ancestor;
+        } while (coerce && (coerce != Base));
         return extend(arguments[0], _prototype);
       }
     }

Original issue reported on code.google.com by cneuw...@gmail.com on 14 Jul 2014 at 6:56

Attachments:

GoogleCodeExporter commented 9 years ago
Here is a minor tweak that will fall through to default cast if no coercion is 
performed

Index: Base.js
===================================================================
--- Base.js (revision 310)
+++ Base.js (working copy)
@@ -23,6 +23,13 @@
         delete this.__constructing;
       } else {
         // Casting.
+        var cls = _class;
+        do {
+          if (cls.coerce) {
+            var cast = cls.coerce.call(_class, arguments[0]);
+            if (cast) return cast;
+          }
+        } while ((cls = cls.ancestor) && (cls != Base));
         return extend(arguments[0], _prototype);
       }
     }

Original comment by cneuw...@gmail.com on 15 Jul 2014 at 12:11

Attachments: