Skip to content

Instantly share code, notes, and snippets.

@MattPorto
Created October 26, 2016 21:02
Show Gist options
  • Save MattPorto/5914d50a72b1803b9547b9ff3d81ffdb to your computer and use it in GitHub Desktop.
Save MattPorto/5914d50a72b1803b9547b9ff3d81ffdb to your computer and use it in GitHub Desktop.
# Uma pequena aplicação que utiliza o Action Cable para notificar novos comentarios dentro dela
# Criando a mensagem de evento (tirado de um turial do site: https://www.onehub.com/blog/2016/02/18/event-notifications-in-rails-5-with-actioncable/)
# rails g model event message:string
# rake db:migrate
# Criando controller e view para manipular os eventos
# rails g controller events index
#app/controllers/events_controller.rb
class EventsController < ApplicationController
def index
@events = Event.all.reverse
end
end
#Partial que mostra a timestamp do evento e a mensagem de notificação:
#app/views/events/_event.html.erb
<div class="event">
<%= event.created_at.to_formatted_s(:short) %>: <%= event.message %>
</div>
#app/views/index.html.erb
<h1>Activity</h1>
<div id="events">
<%= render @events %>
</div>
#config/routes.rb
Rails.application.routes.draw do
root to: 'events#index'
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
# Serve websocket cable requests in-process
mount ActionCable.server => '/cable'
end
#app/assets/javascripts/channels/activity.coffee
#descomentar isso:
@App ||= {}
App.cable = ActionCable.createConsumer()
# rails g channel activity vai gerar os seguintes arquivos:
# app/channels/activity_channel.rb
# app/assets/javascripts/channels/activity.coffee
#app/channels/activity_channel.rb
class ActivityChannel < ApplicationCable::Channel
def subscribed
stream_from "activity_channel"
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
end
#app/assets/javascripts/channels/activity.coffee
App.activity = App.cable.subscriptions.create "ActivityChannel",
connected: ->
# Called when the subscription is ready for use on the server
disconnected: ->
# Called when the subscription has been terminated by the server
received: (event) ->
# Called when there's incoming data on the websocket for this channel
$('#events').prepend "<div class='event'>#{event.message}</div>"
# Utilizando ActiveJob para manipular a transmissão das notificações
# rails g job EventBroadcast
# Vai gerar o arquivo: app/jobs/event_broadcast_job.rb
#app/jobs/event_broadcast_job.rb
class EventBroadcastJob < ApplicationJob
queue_as :default
def perform(event)
ActionCable.server.broadcast 'activity_channel', message: render_event(event)
end
private
def render_event(event)
ApplicationController.renderer.render(partial: 'events/event', locals: { event: event })
end
end
#app/models/event.rb
class Event < ApplicationRecord
after_create_commit { EventBroadcastJob.perform_later self }
end
# Usando scaffolding para criar o model,a view e o controller dos comentários
# rails g scaffold comment comment:string
# rails db:migrate
#app/models/comment.rb
class Comment < ApplicationRecord
after_create_commit { create_event }
private
def create_event
Event.create message: "A new comment has been created"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment