From e93f3a70f9a699f1577df6ce3ba9201b2ea97542 Mon Sep 17 00:00:00 2001 From: Mike Gerwitz Date: Thu, 29 Dec 2016 03:49:47 -0500 Subject: [PATCH] Support for named trait class extending We can call this a bugfix...it's more of a neglected feature that's otherwise completely inconsistent with the rest of the system. :) * lib/Trait.js (createNamedTrait): Support base. (_createStaging) [extend]: Support base. * test/Trait/NamedTest.js: Add test. --- lib/Trait.js | 23 +++++++++++++++------ test/Trait/NamedTest.js | 46 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 62 insertions(+), 7 deletions(-) diff --git a/lib/Trait.js b/lib/Trait.js index 71d55e4..fb76e92 100644 --- a/lib/Trait.js +++ b/lib/Trait.js @@ -62,12 +62,13 @@ function Trait() /** * Create a named trait * - * @param {string} name trait name - * @param {Object} def trait definition + * @param {string} name trait name + * @param {Object} dfn trait definition + * @param {Object=} base extension base * * @return {Function} named trait */ -function createNamedTrait( name, dfn ) +function createNamedTrait( name, dfn, base ) { if ( typeof name !== 'string' ) { @@ -77,16 +78,26 @@ function createNamedTrait( name, dfn ) } dfn.__name = name; - return Trait.extend( dfn ); + + var args = [ dfn ]; + if ( base !== undefined ) + { + args.unshift( base ); + } + + return Trait.extend.apply( null, args ); } function _createStaging( name ) { return { - extend: function( dfn ) + extend: function( /*...*/ ) { - return createNamedTrait( name, dfn ); + // [base, ]dfn + return ( arguments.length === 1 ) + ? createNamedTrait( name, arguments[ 0 ] ) + : createNamedTrait( name, arguments[ 1 ], arguments[ 0 ] ); }, implement: function() diff --git a/test/Trait/NamedTest.js b/test/Trait/NamedTest.js index b93efec..4303ec4 100644 --- a/test/Trait/NamedTest.js +++ b/test/Trait/NamedTest.js @@ -1,7 +1,7 @@ /** * Tests named trait definitions * - * Copyright (C) 2014 Free Software Foundation, Inc. + * Copyright (C) 2014, 2016 Free Software Foundation, Inc. * * This file is part of GNU ease.js. * @@ -167,4 +167,48 @@ require( 'common' ).testCase( // ensure that trait was properly named this.assertOk( T.toString().match( name ) ); }, + + + /** + * The extend method on the named staging object should work just as + * Trait.extend. + */ + 'Can extend class using named trait staging object': function() + { + var Sut = this.Sut, + name = "Extended", + expected = {}, + T = null; + + var C = this.Class( + { + _foo: null, + + getFoo: function() { return expected; }, + } ); + + this.assertDoesNotThrow( function() + { + T = Sut( name ) + .extend( C, + { + get: function() { return this.getFoo(); }, + } ); + } ); + + // should be okay if properly extended + this.assertStrictEqual( + expected, + C.use( T )().get() + ); + + // should _not_ be + this.assertThrows( function() + { + this.Class.use( T )(); + } ); + + // ensure that trait was properly named + this.assertOk( T.toString().match( name ) ); + }, } );