提交 40cc7254 编写于 作者: D David Heinemeier Hansson

Basic channel generator

上级 649b9d93
Description:
============
Stubs out a new cable channel and its CoffeeScript assets. Passes the chanel name, either
CamelCased or under_scored, and an optional list of channel actions as arguments.
This generates a channel class in app/channels.
Example:
========
rails generate channel Chat speak
creates a Chat channel class and CoffeeScript asset:
Channel: app/channels/chat_channel.rb
Assets: app/assets/javascript/channels/chat.coffee
module Rails
module Generators
class ChannelGenerator < NamedBase
source_root File.expand_path("../templates", __FILE__)
argument :actions, type: :array, default: [], banner: "method method"
check_class_collision suffix: "Channel"
def create_channel_file
template "channel.rb", File.join('app/channels', class_path, "#{file_name}_channel.rb")
template "assets/channel.coffee", File.join('app/assets/javascripts/cable/channels', class_path, "#{file_name}.coffee")
if self.behavior == :invoke
template "application_cable/connection.rb", 'app/channels/application_cable/connection.rb'
template "application_cable/channel.rb", 'app/channels/application_cable/channel.rb'
template "assets/consumer.coffee", 'app/assets/javascripts/cable/index.coffee'
end
end
protected
def file_name
@_file_name ||= super.gsub(/\_channel/i, '')
end
end
end
end
module ApplicationCable
class Channel < ActionCable::Channel::Base
# Logic shared between all channels
end
end
\ No newline at end of file
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
self.current_user = find_verified_user
end
protected
def find_verified_user
if current_user = authenticate_with_cookies
current_user
else
reject_unauthorized_connection
end
end
def authenticate_with_cookies
# User.find(cookies.signed[:user_id])
end
end
end
App.<%= class_name.underscore %> = App.cable.subscriptions.create "<%= class_name %>Channel",
connected: ->
# Called when the subscription is ready for use on the server
disconnected: ->
# Called when the subscription has been terminated by the server
<% actions.each do |action| -%>
<%= action %>: ->
@perform '<%= action %>'
<% end -%>
#= require cable
#= require_self
#= require ./channels
@App = {}
App.cable = Cable.createConsumer()
<% module_namespacing do -%>
class <%= class_name %>Channel < ApplicationChannel
def subscribed
# stream_from "some_channel"
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
<% actions.each do |action| -%>
def <%= action %>
end
<% end -%>
end
<% end -%>
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册