Skip to content

Instantly share code, notes, and snippets.

View UsamaAshraf's full-sized avatar

Usama Ashraf UsamaAshraf

View GitHub Profile
class PostSerializer < ActiveModel::Serializer
attributes :id, :title, :details, :author
def author
object.get_author_lazily do |author|
# Serialize the author after it has been loaded.
ActiveModelSerializers::SerializableResource
.new(author)
.as_json[:user]
end
end
class PostSerializer < ActiveModel::Serializer
attributes :id, :title, :details, :author
def author
object.get_author_lazily
end
end
class Post
def get_author_lazily
# The current post object is added to the batch here,
posts = Post.all
author_ids = posts.pluck(:author_id)
authors = User.where(:_id.in => author_ids)
# Somehow pass the author objects to the post serializer and
# map them to the correct post objects. Can't imagine what
# exactly that would look like, but probably not pretty.
render json: posts, pass_some_parameter_maybe: authors
class PostSerializer < ActiveModel::Serializer
attributes :id, :title, :details, :author
# Will run n Mongo queries for n posts being rendered.
def author
User.find(object.author_id)
end
end
# This is now a Mongoid document, not an ActiveRecord model.
class User
class PostsController < ApplicationController
def index
# Runs a SQL join with the users table.
posts = Post.includes(:author).all
render json: posts
end
end
class PostsController < ApplicationController
def index
posts = Post.all
render json: posts
end
end
class Post
belongs_to :author, class_name: 'User'
module.exports = (user) => {
setImmediate(() => {
// Send a welcome email or whatever.
});
}
class ChatUser {
displayNewMessageNotification(newMessage) {
// Push an alert message or something.
}
// `chatroom` is an instance of EventEmitter.
connectToChatroom(chatroom) {
chatroom.on('message-received', this.displayNewMessageNotification);
}
const myEmitter = require('./my_emitter');
const sendEmailOnRegistration = require('./send_email_on_registration');
const someOtherListener = require('./some_other_listener');
const doSomethingEntirelyDifferent = require('./do_something_entirely_different');
myEmitter.on('user-registered', sendEmailOnRegistration);
myEmitter.on('user-registered', someOtherListener);
myEmitter.on('user-registered:activated', doSomethingEntirelyDifferent);
const myEmitter = require('./my_emitter');
// Perform the registration steps
// The application should react differently if the new user has been activated instantly.
if (user.activated) {
myEmitter.emit('user-registered:activated', user);
} else {
myEmitter.emit('user-registered', user);