* websocket-railsで特定グループにメッセージを送信する [#j2ab5228]
#setlinebreak(on)

#contents
-- 関連
--- [[websocket-railsインストール]]
--- [[websocket-railsで特定ユーザにメッセージを送信する]]


** 準備 [#a11e3e5e]
[[websocket-railsインストール]] を参照して環境構築

** サーバ処理の作成 [#idb87ae9]

#html(<div style="padding:10px;">)

*** WebSocketイベント定義 [#rfafff2f]
config/events.rb
#myterm2(){{

  subscribe :notify_group , 'messages#notify_group'
}}

*** WebScoketコントローラ作成 [#a9e4e397]
app/controller/messages_controller.rb
#mycode2(){{
class MessagesController < WebsocketRails::BaseController

  #
  # グループ通知
  #
  def notify_group

    logger.debug("notify_group!");

    # 未ログイン時は何もしない
    if !current_user
      return
    end 

    channel_name = message[:gid]
    msg          = message[:msg]
    from_uid     = current_user.id
    from_user    = User.find(from_uid)
    from_email   = from_user[:email]

    logger.debug("channel_name : " + channel_name.to_s )

    online_channel = false
    if WebsocketRails.channel_manager && WebsocketRails.channel_manager.channels
      WebsocketRails.channel_manager.channels.each do |key,channel|
        if key.to_s == channel_name.to_s
          online_channel = true
        end 
      end 
    end 

    if online_channel
      WebsocketRails[channel_name].trigger(:notification, { :msg => msg, :from => from_email , :type => "group" })
      logger.debug("group notify OK!(" + channel_name + ")");
      trigger_success({ :msg => "send OK!"})
    else
      # 通知失敗時
      logger.debug("notify error!");
      trigger_failure({ :error => "error!"})
    end 

  end 
  .
  .
end
}}

#html(</div>)


** 共通処理(js)の作成 [#ab5f89b0]

#html(<div style="padding:10px;">)

app/assets/javascript/_common.js
#mycode2(){{
jQuery(function($){

  var myapp = window.myapp = window.myapp || {};

  /** 
   * グループ通知のsubscribe
   */
  myapp.subscribe_channels = function(channels){
    if (!channels || channels.length == 0){ 
      return;
    }   
    for (var i in channels) {
      var channel_name = channels[i];
      console.log("subscribe_channels " + channel_name);
      myapp.channel = myapp.dispatcher.subscribe(channel_name);
      myapp.channel.bind('notification', function(data) {
        console.log('channel event received');
        myapp.showNotifyDialog(data);
      }); 
    }   
  };

});
}}

#html(</div>)

** メッセージ送信用画面の作成 [#ce02408f]

#html(<div style="padding:10px;">)

*** コントローラの作成 [#n4f66abd]
app/controller/chats_controller.rb
#mycode2(){{
class ChatsController < ApplicationController

  #
  # グループ一覧を表示する
  #
  def groups

    @groups = group_list
    @gid = params[:gid] || nil 
    @msg = params[:msg] || nil 

    if request.post?
      to_group
    end 

  end


  private

    #
    # グループ一覧を取得する.
    #
    def group_list

      groups = []
      online_groups = []
      WebsocketRails.channel_manager.channels.each do |key,channel|
        logger.debug("key :" + key.to_s)
        online_groups << key.to_s
      end

      logger.debug(online_groups.to_s)

      all_groups = Group.all
      all_groups.each do |g|
        #rec = g.attributes.compact!
        rec = g.attributes
        rec["status"] = online_groups.include?(rec["channel_name"])
        groups << rec
      end

      groups
    end

}}

*** ビューの作成 [#m7320009]
app/views/chats/users.html.erb
#myhtml2(){{
<h3>グループを指定してメッセージを送信する</h3>

<%= render :partial => "shared/messages" %>

<%= form_tag('/chats/groups', :method => :post, :id => "sendto_group_form") do %>

<div>グループ</div>
<table class="tbl">
  <thead>
  <tr>
    <th>&nbsp;</th>
    <th>グループ</th>
    <th>オンライン</th>
  </tr>
  </thead>
  <tbody>
  <% if @groups %>
  <% @groups.each do |g| %>
  <tr>
    <td><input type="radio" name="gid" value="<%= g["channel_name"] %>" /></td>
    <td><%= g["name"] %></td>
    <td><%= g["status"] ? "◯" : "" %></td>
  </tr>
  <% end %>
  <% end %>
  </tbody>
</table>

<br />

<div>メッセージ</div>
<div>
  <textarea name="msg" rows="5" cols="40"><%= @msg %></textarea>
</div>

<input id="btn_ws"     type="button" value="Websocket送信" />

<% end %>
}}

*** クライアント処理の作成 [#k380ed7d]
app/assets/javascript/chats/users.js
#mycode2(){{
jQuery(function($){

  /** 
   * [websocket送信]
   */
  $(document).on("click", "#sendto_group_form #btn_ws", function(e){
    var data = { "gid" : $("form").find("[name=gid]:checked").val(),  "msg" : $("form").find("[name=msg]").val() };
    myapp.dispatcher.trigger("notify_group", data,
     function(data){
       myapp.showInfo("送信しました。");
     },  
     function(data){
       myapp.showError("送信できませんでした。");
     }   
    );  
  }); 

  // ws接続
  myapp.wsConnect();

  // subscribe
  myapp.subscribe_default();
});
}}

#html(</div>)

トップ   差分 バックアップ リロード   一覧 単語検索 最終更新   ヘルプ   最終更新のRSS