Wrap $.cookie in Ember goodness
To try and remove external dependencies from my Ember CLI apps with a Promise aware object wrapper.
This addon is designed to help pushing the external dependencies of cookies as far from my Ember CLI app as possible. By injecting this object where cookie access is needed, my Ember code can just deal with an Ember object. This also means that I can inject mock objects in during tests to simulate setting and getting cookies.
From within your Ember CLI application, run:
npm install --save-dev ember-cli-cookie
In an initializer, inject the cookie
object where needed:
export default {
name: 'test-initializer',
after: ['cookie'],
initialize: function(container, app) {
app.inject('controller', 'cookie', 'cookie:main');
}
}
Use this function to set a cookie, eg:
// /controllers/test.js
export default Ember.Controller.extend({
actions: {
testAction: function() {
var self = this;
var cookie = this.get('cookie');
cookie.setCookie('my-key', 'my-value')
.then(function() {
self.transitionToRoute('success');
});
}
}
});
Use this function to get a cookie, eg:
// /controllers/test.js
export default Ember.Controller.extend({
actions: {
testAction: function() {
var self = this;
var cookie = this.get('cookie');
var token = cookie.getCookie('my-key');
if (!token) {
this.transitionTo('login');
}
}
}
});
In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality.
- Aaron Chambers ([email protected])