2014-12-03 55 views
2

任何人都可以向我解釋如何在使用Ember CLI時做猴子修補嗎?這是關於下面的方法:Monkey修補Ember數據(當使用ember-cli時)

https://github.com/emberjs/data/blob/fba5e5f09824caab3dfaf0e746f760b3eeacd269/packages/ember-data/lib/system/relationships/relationship.js#L284

BelongsToRelationship.prototype.addRecord = function(newRecord) { 
    if (this.members.has(newRecord)){ return;} 
    var type = this.relationshipMeta.type; 
    Ember.assert("You can only add a '" + type.typeKey + "' record to this relationship", newRecord instanceof type); 

    if (this.inverseRecord) { 
    this.removeRecord(this.inverseRecord); 
    } 

    this.inverseRecord = newRecord; 
    this._super$addRecord(newRecord); 
}; 

我希望暫時禁用斷言語句,但我看不出如何做到這一點不分叉整個項目。然後,我還需要分叉ember-data bower軟件包項目,然後創建我自己的分發版。

- 托馬斯

+0

我很好奇,是什麼推動你不得不這樣猴補丁燼數據。你能詳細說明一些用例嗎? – user239546 2014-12-05 01:58:35

+0

它與這個拉請求有關:https://github.com/emberjs/data/pull/2345。基本上我想有一個多態屬於與任何類型的模型的關係 – 2014-12-05 10:39:38

回答

1

BelongsToRelationship不在它可以通過全球範圍內訪問的方式定義。但是,您可以通過實例化DS.belongsTo關係的模型並在其中進行挖掘來檢索它。

這初始化應該做的伎倆:

// app/initializers/monkey-patch.js 

import DS from 'ember-data'; 
import Ember from 'ember'; 

//Hacky way to get BelongsToRelationship constructor 
var getBelongsToConstructor = function(store) { 
    var dummyRecord = store.createRecord(DS.Model.extend({ 
    dummy: DS.belongsTo(DS.Model.extend()) 
    })); 
    return dummyRecord._relationships.dummy.constructor; 
}; 

export default { 
    name: 'monkey-patch', 
    after: 'store', 
    initialize: function(container, application) { 
    var store = container.lookup('store:main'), 
     BelongsToRelationship = getBelongsToConstructor(store), 
     originalAssert = Ember.assert, 
     originalAddRecord = BelongsToRelationship.prototype.addRecord; 

    //Overriding assert in order to check Ember.disableAssert flag 
    Ember.assert = function() { 
     var args = Array.prototype.slice.call(arguments, 0), 
     retVal; 
     if (!Ember.disableAssert) { 
     retVal = originalAssert.apply(this, args); 
     } 
     return retVal; 
    }; 

    //Overriding BelongsToRelationship - calling super while asserion is disabled 
    BelongsToRelationship.prototype.addRecord = function() { 
     var args = Array.prototype.slice.call(arguments, 0), 
     retVal; 
     Ember.disableAssert = true; 
     retVal = originalAddRecord.apply(this, args); 
     Ember.disableAssert = false; 
     return retVal; 
    }; 
    } 
};