NUブログ 自作Webアプリで一発当てたいプログラマ

ShootingStarでCometアプリ作成

タグ:ruby, rails, 雑記

これから作成予定のアプリでCometを使う必要があるので、railsのShootingStarをインストールしてみました。ShootingStarにはサンプルのチャットアプリが付属しているので、まずはそれをインストールして動作確認してみます。

SootingStarのインストール

まずはrailsアプリを新規作成します。

% rails -d sqlite3 chat
% cd chat

続いて、ShootingStarプラグインをgemでインストールします。

% sudo gem install shooting_star

ShootingStarプラグインを使用するように初期設定を行います。

% shooting_star init

ここで、confing/shooting_star.ymlが生成されるので、portを変更する場合は修正します。8080って、既に他で使ってたので…

server:
  host: 0.0.0.0
  port: 8080 # <- ここを修正
shooter:
  uri: druby://0.0.0.0:7123

次に、Cometを実装するためのモデルクラスのMeteorを生成します。

% ./script/generate meteor

クライアントからの接続先は config/database.yml を編集します。

development: 
  adapter: sqlite3
  database: db/development.sqlite3
  timeout: 5000
  # ↓ここを追加
  shooting_star:
    server: "localhost:8888" # <- ここを接続先の ShootingStar サーバのアドレスに変更します。
    shooter: "druby://localhost:7123"

ShootingStarのサンプルアプリであるchatを生成します。

% ./script/generate chat

そしてDBのmigrate!

% rake db:migrate

最後にサーバを起動して完了

% ./script/server -d
% shooting_star start -d

チャットを改造

Cometで取得したメッセージを画面に表示する際に任意の JavaScript を実行するには

class ChatController < ApplicationController
  :
  :
  def talk
    @chat = Chat.new(
      :name => session[:name], :message => params[:message])
    if @chat.save
      content = render_component_as_string :action => 'show', :id => @chat.id
      javascript = render_to_string :update do |page|
#        page.insert_html :top, 'chat-list', content # <- ここをコメントアウト
        page.call "console.log", content # <- ここに、こんな感じで呼び出したいjsのメソッドを書く
      end
      Meteor.shoot 'chat', javascript
      render :update do |page|
        page[:message].clear
        page[:message].focus
      end
    else
      render :nothing => true
    end
  end
 :
 :