Skip to content

Instantly share code, notes, and snippets.

@ericraio
Created May 26, 2013 18:07
Show Gist options
  • Save ericraio/5653557 to your computer and use it in GitHub Desktop.
Save ericraio/5653557 to your computer and use it in GitHub Desktop.
class PostsController < ApplicationController
include ActionController::Live
before_filter :authenticate_user!, only: [:new, :create, :edit, :update, :destroy]
before_filter :set_post, only: [:show, :edit, :update, :destroy]
# GET /posts/:slug
def show
end
# GET /posts/new
def new
@post = Post.new
end
# GET /posts/:slug/edit
def edit
end
# POST /posts
def create
response.headers["Content-Type"] = "text/javascript"
@post = Post.new(post_params)
@post.user = current_user
if @post.save
$redis.publish('messages.create', @post.created_at)
flash[:notice] = 'Post was successfully created.'
if request.env['HTTP_REFERER'] == root_url
redirect_to :back
else
redirect_to @post
end
else
render action: 'new'
end
end
# PATCH/PUT /posts/:slug
def update
if @post.update(post_params)
redirect_to @post, notice: 'Post was successfully updated.'
else
redirect_to :back
end
end
# DELETE /posts/:slug
def destroy
@post.destroy
redirect_to posts_url, notice: 'Post was successfully destroyed.'
end
# GET /posts/events
#
def events
response.headers["Content-Type"] = "text/event-stream"
redis = Redis.new
redis.psubscribe('messages.*') do |on|
on.pmessage do |pattern, event, data|
post = current_user.followees_latest_posts(where: { :created_at.gte => data }).first
if post.present?
response.stream.write("event: #{event}\n")
response.stream.write("data: #{post.to_json}\n\n")
end
end
end
rescue IOError
logger.info("Stream closed")
ensure
redis.quit
response.stream.close
end
private
# Use callbacks to share common setup or constraints between actions.
def set_post
@post = Post.where(slug: params[:slug]).first
end
# Only allow a trusted parameter "white list" through.
def post_params
params.require(:post).permit(:body, :headline)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment