mazeltov7のweb断片

備忘録的なテキトーなことを書きます。(技術記事はQiitaに移行しました http://qiita.com/mazeltov7 )

Private_pubを使ってRails4で簡単なチャットアプリを作ってみる

Private_pub(https://github.com/ryanb/private_pub)
RailsCastのライアンさんが作った、fayeを使ったチャットアプリが簡単に作れるgem。
fayeではセキュリティ周りの設定が面倒だったりするので、hogehogeってことで作ったらしい。

RailsCastの「#316 Private Pub 」通りにやってみて、すぐに動く。本当にあっという間にできるので、びっくりする。

gemファイルに

gem 'private_pub'
gem 'thin'

入れる。

で、rails g private_pub:installで
create config/private_pub.yml
create private_pub.ru
を作成する。

それぞれの中身は以下。
config/private_pub.yml

development:
  server: "http://localhost:9292/faye"
  secret_token: "secret"
test:
  server: "http://localhost:9292/faye"
  secret_token: "secret"
production:
  server: "http://example.com/faye"
  secret_token: "hogehogehogheogehogehogheogheoghehgoeho"
  signature_expiration: 3600 # one hour


private_pub.ru

# Run with: rackup private_pub.ru -s thin -E production
require "bundler/setup"
require "yaml"
require "faye"
require "private_pub"

Faye::WebSocket.load_adapter('thin')

PrivatePub.load_config(File.expand_path("../config/private_pub.yml", __FILE__), ENV["RAILS_ENV"] || "development")
run PrivatePub.faye_app

で、rackup private_pub.ru -s thin -E productionでthinを動かしてあげて、

application.jsに

//= require private_pub

を追加する。

あとは、
create.js.erbで

<% publish_to "/messages/new" do %>
  $("#chat").append("<%= j render(@message) %>");
<% end %>
$("#new_message")[0].reset();

publishして、

index.html.erbで

<h1>Chat</h1>

<ul id="chat">
  <%= render @messages %>
</ul>

<%= form_for Message.new, remote: true do |f| %>
  <%= f.text_field :content %>
  <%= f.submit "Send" %>
<% end %>

<%= subscribe_to "/messages/new" %>

subscribeするともう終わり!
簡単!早い!


それで作ったのが、こちら。
https://github.com/mazeltov7/private_pub-app




ちなみに、上記のやり方(js.erbに書くやり方)だけじゃなくて、
JSONでやるやり方もRailsCastの終わりの方に紹介されてて、自由度高い感じあります。

ただ、もう1年くらいアップデートされていない模様で、
これからもする気ない!??ぽい感じあるので、そのあたりがつらいですね。