Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Guide to build a realtime application using Phoenix on Heroku

Guide to build a realtime application using Phoenix on Heroku

#m3dev M3 Tech Talk #32
Guide to build a realtime application using Phoenix on Heroku

Takayuki Matsubara

October 31, 2014
Tweet

More Decks by Takayuki Matsubara

Other Decks in Programming

Transcript

  1. Setup a Phoenix environment $ git clone https://github.com/phoenixframework/phoenix.git # $

    git checkout v0.4.1 $ cd phoenix $ mix do deps.get, compile ! v0.5.0 does not work on Heroku choose v0.4.1 or edge
  2. Create a Phoenix application $ mix phoenix.new phoenix_sample ../phoenix_sample $

    cd ../phoenix_sample $ git init $ git add . $ git commit -m 'initial commit'
  3. Running on local $ mix do deps.get, compile $ mix

    phoenix.start • do not forget to commit $ git add . $ git commit -m 'running on local'
  4. elixir_buildpack.config # Erlang version erlang_version=17.2 # Elixir version elixir_version=1.0.1 #

    Always rebuild from scratch on every deploy? always_rebuild=false # Export heroku config vars # config_vars_to_export=(DATABASE_URL)
  5. Running on Heroku $ git add -u $ git commit

    -m 'configuration for heroku' $ git push heroku master $ heroku open
  6. Create Channel web/channels/chat.ex defmodule PhoenixSample.Chat do use Phoenix.Channel def join(socket,

    "chat", message) do {:ok, socket} end def event(socket, "message", data) do IO.puts data["message"] broadcast socket, "broadcast_message", %{message: data["message"]} socket end end
  7. Mount Socket and register Channel add the following line to

    web/ router.ex use Phoenix.Router.Socket, mount: "/ws" channel "channel", PhoenixSample.Chat
  8. Html and JS side • Include some js files •

    Add message box • Write some js codes
  9. Include some js files web/templates/layout/ application.html.eex • Need to download

    jquery <script src="/js/jquery.js" type="text/javascript"></script> <script src="/js/phoenix.js" type="text/javascript"></script> <script src="/js/application.js" type="text/javascript"></script>
  10. Write some js codes priv/static/js/application.js $(function() { var socket =

    new Phoenix.Socket("/ws"); var $messageBox = $("#message-box"); var $allMessages = $("#all-messages"); socket.join("channel", "chat", {}, function(channel) { $messageBox.keypress(function(e) { if (e.which === 13) { e.preventDefault(); channel.send("message", { message: $messageBox.val() }); $messageBox.val(""); } }); channel.on("broadcast_message", function(data) { console.log("message: " + data['message']); $allMessages.prepend('<p>' + data['message'] + '</p>'); }); }); });
  11. See Also • Deploy Phoenix Application to Heroku • http://learnelixir.com/blog/2014/10/15/

    deploy-phonenix-application-to-heroku- server/ • Phoenix Λ heroku Ͱಈ͔͢ • http://qiita.com/ma2ge/items/ cfe17e02f593bb55b084