From be987ca421041baaea1a67efe9b97361cb096e8e Mon Sep 17 00:00:00 2001 From: Ben Allfree Date: Tue, 7 Nov 2017 10:50:55 -0800 Subject: [PATCH] feat(traits): allow user to pass options to `addTrait` * Add settings to trait registration * settings -> options --- src/Lucid/Model/index.js | 4 ++-- test/unit/traits.spec.js | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/src/Lucid/Model/index.js b/src/Lucid/Model/index.js index eaeb035b..5940ab1f 100644 --- a/src/Lucid/Model/index.js +++ b/src/Lucid/Model/index.js @@ -378,7 +378,7 @@ class Model extends BaseModel { * * @param {Function|String} trait - A plain function or reference to IoC container string */ - static addTrait (trait) { + static addTrait (trait, options = {}) { if (typeof (trait) !== 'function' && typeof (trait) !== 'string') { throw GE .InvalidArgumentException @@ -390,7 +390,7 @@ class Model extends BaseModel { */ trait = typeof (trait) === 'string' ? `${trait}.register` : trait const { method } = resolver.forDir('modelTraits').resolveFunc(trait) - method(this) + method(this, options) } /** diff --git a/test/unit/traits.spec.js b/test/unit/traits.spec.js index 75f3dc90..688190b8 100644 --- a/test/unit/traits.spec.js +++ b/test/unit/traits.spec.js @@ -254,4 +254,40 @@ test.group('Traits', (group) => { assert.deepEqual(stack, ['on user', 'on profile']) }) + + test('pass options to trait via ioc container', (assert) => { + class FooTrait { + register (ctx, options) { + assert.deepEqual(ctx, User) + assert.deepEqual(options, {foo: 1}) + } + } + + ioc.fake('FooTrait', () => { + return new FooTrait() + }) + + class User extends Model { + static boot () { + super.boot() + this.addTrait('@provider:FooTrait', {foo: 1}) + } + } + + User._bootIfNotBooted() + }) + + test('pass options to bound function', (assert) => { + class User extends Model { + static boot () { + super.boot() + this.addTrait((ctx, options) => { + assert.deepEqual(ctx, User) + assert.deepEqual(options, {foo: 1}) + }, {foo: 1}) + } + } + + User._bootIfNotBooted() + }) })