docbrown/app/controllers/messages_controller.rb
Mac Siri 8003191a4e Create Chat app (#175)
* Setup Pusher gem

* Create ChatChannel and Message model

* Create ChatChannelController

* Add back fix-db-schema-conflicts gem

* Add pusher-js package

* Add validations on Message & ChatChannel models

* Update Route

* Create MessageController

* Update ChatChannelController

* Create Chat app WIP

* Extract messenger render to Message Component

* Implement live chat WIP

* Implement live chat WIP (2)

* Add style and scrollToBottom feature for chat

* Create getUserDataAndCsrfToken function

* Add feature toggle to the new live chat

* Clean up ChatChannelsController & create spec

* Update ChatChannel spec

* Update Message spec

* Create MessagesController spec & refactor

* Clean up Chat app

* Fix lint

* Add character limit to Message
2018-04-04 14:19:57 -07:00

42 lines
1.1 KiB
Ruby

class MessagesController < ApplicationController
before_action :authenticate_user!
def create
@message = Message.new(message_params)
success = false
if @message.save
begin
message_json = create_pusher_payload(@message)
Pusher.trigger(@message.chat_channel.id, "message-created", message_json)
success = true
rescue Pusher::Error => e
logger.info "PUSHER ERROR: #{e.message}"
end
if success
render json: ["Message created"], status: 201
else
result = "Message created but could not trigger Pusher"
render json: [result, @message.to_json], status: 201
end
else
render json: e.message, status: 401
end
end
private
def create_pusher_payload(new_message)
{
username: new_message.user.username,
message: new_message.message_markdown,
timestamp: new_message.timestamp,
color: new_message.user.bg_color_hex,
}.to_json
end
def message_params
params.require(:message).permit(:message_html, :user_id, :chat_channel_id)
end
end