LoginSignup
5
5

More than 5 years have passed since last update.

Rails4 | 新規・変更機能 | ActionController::Liveを利用したリアルタイム通信を試す

Posted at

Rails4 | 新規・変更機能 | ActionController::Liveを利用したリアルタイム通信を試す

概要

Rails4では手軽にPush型通信を行えるActionController::Liveが追加されたので試してみます。

前提

RailsのデフォルトのWebサーバーである、WEBricはリアルタイム通信に対応していないので、
pumaを利用して試します。

サンプル

仕様

  • 下記で scaffold した状態をベースとする
rails g scaffold person name:string age:integer
rake db:migrate

テーブルには以下のデータが登録されています

$ select * from people;
1|tanaka|20|2014-06-25 23:45:12.555117|2014-06-25 23:15:55.737728
2|suzuki|19|2014-06-25 23:45:30.476800|2014-06-25 23:15:50.489037
  • Personテーブルに 'honda' という名前のデータが登録されているか監視します。

サンプルコード

  • Gemfileに puma を追加
gem 'puma'
  • bundlerpuma をインストール

  • Controllerを作成

honda_check_controller.rb

class HondaCheckController < ApplicationController
  include ActionController::Live

  def index
    response.headers['Content-Type'] = 'text/plain'

    created = false
    loop do
      Person.uncached do
        honda = Person.where(name: 'honda')
        if honda.size > 0
          response.stream.write("honda is created\n")
          created = true
        else
          response.stream.write("honda is not created\n")
          sleep(rand(3))
        end
      end
      break if created
    end
  rescue IOError
  ensure
    response.close
  end
end
  • routes に HondaCheckController のルーティング情報を追加

routes.rb

  get 'honda_check' => 'honda_check#index'
  • サーバーを起動します。
puma
  • クライアントからcurlで接続してリアルタイム通信を開始します

'honda' はまだ登録されていないので 'honda is not created' が表示され続けます

$ curl localhost:9292/honda_check
honda is not created
honda is not created
honda is not created
:
:
  • DBに honda を登録します
sqlite> insert into people(name, age) values ('honda', 24);
sqlite> select * from people;
1|tanaka|20|2014-06-25 23:45:12.555117|2014-06-25 23:15:55.737728
2|suzuki|19|2014-06-25 23:45:30.476800|2014-06-25 23:15:50.489037
10|honda|24||
  • 'honda' の登録を検出し、 'honda is created' が表示され、処理が終了しました
$ curl localhost:9292/honda_check
honda is not created
honda is not created
honda is not created
:
honda is created
$ 
5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5