Skip to content

Instantly share code, notes, and snippets.

@jsheridanwells
Last active December 11, 2017 15:12
Show Gist options
  • Save jsheridanwells/c36a2278fdeb8f4b1ab40a47b31972ef to your computer and use it in GitHub Desktop.
Save jsheridanwells/c36a2278fdeb8f4b1ab40a47b31972ef to your computer and use it in GitHub Desktop.
Rails Action Cable -API Only Setup
# configure cors
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins '127.0.0.1:8080'
resource '*',
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end
# allow cable requests from separate origin in Rails.application.configure...
config.action_cable.allowed_request_origins = ['http://127.0.0.1:8080/']
config.action_cable.disable_request_forgery_protection = true
config.action_cable.allow_same_origin_as_host = false
//npm install actioncable
//npm install browserify
//load actioncable
var ActionCable = require('./action_cable');
//create connection
var cable = ActionCable.createConsumer('ws://localhost:3000/cable')
//subscribe to channel
cable.subscriptions.create('MessageChannel', {
received: (data) => {
console.log(data);
$('#main').append(`<p>${data.message}</p>`);
}
});
//in this example, on posting a message,
// the message will be appended to #main on the dom
$('#send-button').click(() => {
$.ajax({
method: 'post',
url: 'http://localhost:3000/messages',
data: JSON.stringify({ "message" : {"content" : $('#message-box').val()}}),
contentType: "application/json; charset=utf-8",
dataType: "json",
});
});
# add rack-cors to gem file
gem 'rack-cors'
# set up message channel
class MessageChannel < ApplicationCable::Channel
def subscribed
stream_from 'message_channel'
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
end
# call the stream as part of any action
class MessagesController < ApplicationController
# POST /messages
def create
puts message_params
@message = Message.new(message_params)
if @message.save
render json: @message, status: :created, location: @message
ActionCable.server.broadcast 'message_channel',
message: @message.content
else
render json: @message.errors, status: :unprocessable_entity
end
end
private
# Only allow a trusted parameter "white list" through.
def message_params
puts params
params.require(:message).permit(:content)
end
end
# mount websocket server in the routes
Rails.application.routes.draw do
resources :messages
get 'messages/index'
get 'messages/create'
mount ActionCable.server, at: '/cable'
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment