Skip to content

Instantly share code, notes, and snippets.

@dylanjha
Last active January 31, 2016 17:55
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dylanjha/11004125 to your computer and use it in GitHub Desktop.
Save dylanjha/11004125 to your computer and use it in GitHub Desktop.
Set a `currentUser` in Ember world that all controllers ( and all views ) can access. I'm using Ember 1.5.0 and Ember Data 1.0.0-beta.6
<!DOCTYPE html>
<html>
<head>
<title>App</title>
<%= stylesheet_link_tag 'application', media: 'all' %>
<%= javascript_include_tag 'application' %>
<%= javascript_include_tag "templates/all" %>
<%= csrf_meta_tags %>
</head>
<body>
<%# Have Rails put the serialized User JSON into the DOM %>
<%= tag(:meta, content: UserSerializer.new(current_user).to_json(root: false), name: 'current-user') if user_signed_in? %>
<%= yield %>
</body>
</html>
//create an initailizer that does two things:
// 1. Parse the currentUser json from the meta tag that rails put in the DOM
// 2. Store that currentUser as a User Model into the data store - [ store.push() ]
// 3. Set the `content` property of CurrentUserController to the user instance
// 4. Inject currentUser into every controller
Ember.Application.initializer({
name: "currentUser",
initialize: function(container, application) {
var store = container.lookup('store:main'),
attributes = $("meta[name='current-user']").attr('content');
if(attributes){
var object = store.push(App.User, JSON.parse(attributes)),
user = App.User.find(object.id),
controller = container.lookup('controller:currentUser').set('content', user);
container.typeInjection('controller', 'currentUser', 'controller:currentUser');
}
}
});
App.CurrentUserController = Ember.ObjectController.extend({
isSignedIn: (function() {
return this.get('content') !== null;
}).property('content'),
});
// These links refresh the page. In my application,
// logging in and logging out are the only two times the page
// needs to refresh.
{{#if currentUser.isSignedIn}}
{{currentUser.name}}<a href="/users/sign_out">Logout</a>
{{else}}
<a href='/users/auth/facebook'>Sign Up</a>
{{/if}}
//the User model, implementing `find`, used in the initializer
App.User = DS.Model.extend({
email: attr('string'),
location: attr('string'),
profile_image_url: attr('string'),
name: attr('string')
});
App.User.reopenClass({
find: function(id){
return this.store.find('user', id);
},
findAll: function(){
return this.store.findAll('user');
}
});
@locks
Copy link

locks commented Nov 12, 2014

One nitpick: could you make current_user_controller use model instead of content?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment