Sugar icon indicating copy to clipboard operation
Sugar copied to clipboard

How to use chainable methods in node.js (ES6)?

Open pie6k opened this issue 8 years ago • 4 comments

import { Date as SugarDate } from 'sugar';
SugarDate.create('tomorrow'); // is ok
SugarDate.create('tomorrow').isValid(); // error: isValid is not a function
SugarDate.isValid(SugarDate.create('tomorrow')); // works but it's crazy.

How do you use it in chainable way in node js without conflicts with native Date object?

pie6k avatar Nov 28 '16 19:11 pie6k

Sugar as of 2.0 has 3 methods of interaction: static, chainable, and extended. There essentially is one rule governing the different use of these methods, which is that static methods are always accessed as properties of the namespace (i.e. Sugar.Date.xxx), while chainable objects are always created through the namespace itself (i.e. new Sugar.Date()). This rule is internally consistent, and (I believe) intuitive, however it does unfortunately lead to the confusing situation that Sugar.Date.create returns a native date object, while new Sugar.Date returns a chainable object. Further, because Sugar.Date.create is so useful (and would be tedious to write out all the time), the chainable constructor forwards it's input to Sugar.Date.create so they can work together. This means that in your example:

new Sugar.Date(Sugar.Date.create('tomorrow')).isValid(); // This is what would normally be required
new Sugar.Date('tomorrow').isValid(); // This also works as a shortcut

Both work, but:

Sugar.Date.create('tomorrow').isValid();

...does not (without extended mode enabled). I agree that when taken together this can be unintuitive at first, and I'm open to suggestions about how to improve it...

andrewplummer avatar Nov 28 '16 22:11 andrewplummer

Out of curiosity have you visited the site's Dates page yet? I'm thinking that maybe having better docs on this page will help make this easier to understand.

andrewplummer avatar Nov 29 '16 01:11 andrewplummer

One other potential idea (mostly musing here): Maybe the majority of this confusion comes from the naming create, because Sugar.Date.create() essentially reads as "create a Sugar date" (as opposed to a native date object). If this were changed to parse, might this help alleviate confusion? The only thing I don't like about this idea is that there is also a Sugar.Array.create method that works the same way (and is also used by the Sugar.Array() chainable constructor), and it would be nice not to have to break parity here...

andrewplummer avatar Nov 29 '16 01:11 andrewplummer

It's been ages but just a note that I'm going to have a look at how to make this clearer in the next version...

andrewplummer avatar Aug 21 '18 13:08 andrewplummer