Rails 5 ActionCable Talk: Realtime the Rails Way

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello my name is Jeff nappy I am the director of software engineering at clear voice I gave a talk this past Tuesday March 15 2016 at GoDaddy about action cable and rails 5 we didn't get a chance to film it so I thought I would put up a video on youtube of hey doc here's a cat we're gonna talk about action cable action cable is real time for rails users love fast it's a fact chat like slack collaboration Google - like Google Docs instant gratification people want speed people want to see things update in real time action cable helps you build real-time apps with rails before action cable if you wanted to build a real-time map with rails you Adaline on a third-party gem like fey or use node with socket IO and/or you would use a third-party hosted service such as pusher that's no longer necessary with action cable an action cable is easy like DHH says if you're starting a new app or you're starting a new project building a majestic monolith it's gonna get you there faster if you're not having to to work with multiple technologies or have to manage your app across services and across repositories you're going to move a lot faster and with rails 5 you really can build a highly responsive real time app with just straight-up rails so when you get started with a action cable app the new struck file structure you're gonna be getting you're gonna have a channels folder at within your app this will be the standard structure you'll have an application folder application cable folder within that with your superclasses for your application cable you have the channel there and the connection and then for each channel you create you'll have named underscore channel RB file and that's where you primarily have your your surface logic for your channels on the front end you'll have channels folder added the java scripts and this is assuming you're using the generator so now you could write the JavaScript yourself with in which case these generate these generated files could and code could be placed anywhere but with the use of the generators you'll have a channels folder and you'll have a name dot copy for each channel that you create and then you'll have your main cable dot coffee speaking of coffee I'm gonna have a sip of coffee right now so with the new channel generator in rails 5 you can simply run rails generate channel and then the name of your channel and list out the methods you want to create you should think of action cable channels as methods it's RPC method calls so their remote procedure calls remote function calls so when you make a call to an action cable channel method from the front end you're gonna be executing that code on the back end you know as if as nearly as if it was local so as I did to my talk this past week I'm gonna do it live we're gonna go ahead and code up a quick action cable example so I don't really also just over to the terminal and we'll take a look at it so first thing we're gonna do we need to make sure we have the latest rails installed and we're gonna make sure we have the pre-release bypassing the pre flag that's gonna ensure we get rails 500 beta3 at this point so we've got 500 beta3 installed now we're gonna create a new map I'm just gonna use R which is an alias that I have for the rails command so I can use this with a shim you got to specify the rails version so we're gonna specify if we have multiple versions installed and you just specify what we'd like to use so I'm gonna use rails underscore 500 beta3 underscore new and imma call this a PC okay now that we got our app installed I'm gonna jump into it and I'm gonna go ahead and I'm gonna go ahead and initialize a git repository and add the current folder to it and then I'm gonna go ahead and and and commit I'm doing this because I think it's good practice to create a git repository for every project you're working on and I also want to show basic usage wicket so I just ran a basically I get I get in it and a git add and then I I ran a quick commit there so now we have our repository set up next thing I'm gonna do going to go ahead and generate a rooms controller so we have a chat rooms we're gonna have a controller there so I'm gonna go ahead and run that and we're gonna go to generate that rooms controller room strollers gonna give us a place where we can display messages and and where we can have the the main page for our app so they've got that initialized I'm gonna go ahead and create a model we're gonna have a message model since we're making a chat service so we're just gonna create a quick message model I'm just gonna have content a content attribute on and we're gonna that's gonna be a text text field now that we've created a model I'm going to go ahead and migrate one cool thing about rails five is that we no longer use the write command to run our tasks we simply just simply use the rails command for everything so now we're you instead of using rake DB my gravy's rails DB migrate I'm gonna go ahead and commit again now that way you've created those so we had that in our history no commit there we added our folder we're gonna commit it and now I'm gonna go ahead and jump in and create a little test message so you can see that when we run rails it means the rails console real simply just type rails see that's gonna be your console it's gonna give you kind of access to the backend of your app if you're not familiar with it so we'll go ahead and do message create content hello world now we're gonna have that message stuff I do message all will see that hello world message has been created cool so now that we've done that I'm gonna go ahead and update our routes so that we can pull this up at a browser we go go here we're gonna actually have our route route go to our rooms show method here so go ahead and do that now I'm gonna go ahead and demonstrate we'll go ahead and start the server so I can do our s run the server okay real servers starting and then let's go ahead and pull open a browser for that we're going ahead and go to pull up local those three thousand there and there we go we got our our rooms controller is definitely loading now I'm gonna go ahead and update the controller so that it'll load messages then I'm going to update our templates here so we can see them so let's get back into the terminal here and we'll go ahead and update our controller we're going to implement this show method here gonna say we're gonna load all the messages in here here's a message oh and the real app this would be paginating we wouldn't load every single message we would we would load only the recent messages and then have a method a way of paginating those results for our demonstration here I'm just gonna load all the messages that we have next thing I'm gonna do is I'm going to go ahead and update our show template here now instead of writing this HTML right now I'm just going to go ahead and pop in a little simple little prepared template I got here so it's just gonna have oh I just have h1 here with our action cable chat it's got our messages it's gonna render the messages into a div that's all that that's all that's going to be now we're gonna need to create a message a partial view here so I'm gonna go ahead and open up our views here and go ahead and create a folder for that because since we haven't created any yet we don't have a folder there so I'll go ahead and create a messages folder under the views /c underscore message HTML the DRB now we got that up we got that file created now I can pop into messages messages email potential are your B and then I'm going to go ahead and populate that with a existing partial that I created for that there we go it's real simple it's just a div class message got a paragraph tag we're gonna put the message content in there that's gonna be about it great so at this point I'm gonna go ahead and do a get add again cuz we have our views created so I'm gonna doing it get add and I'm gonna do it commit for our views here then we can go ahead and pop in pop back into the browser and we should see our messages popping great here's our test message that we that we created previously that's just the basic rails app now so we've got a message model where we're storing messages and we've got a controller where we're able to contain those messages within a room so next step we're gonna go ahead and generate an action cable channel so we can see action cable let's get to work I want to show you how easy it is to get real-time in your app so actually cable simply I'm just gonna generate I'm using a generator I'm gonna say our rails generate channel I'm gonna call it a room channel and I'm gonna I'm gonna create a speak method within that channel real quick so we got our room channel generated and we got our for the back end and we got our room coffee for the front end generated now in order to activate action cable we're gonna go ahead and up open the app keep assets Java scripts cable that copy and in here you just need to uncomment these here the two lot these two lines that's it that turns on action cable in the front end and now you need to open the routes dot RB so you'll pop open routes we will go ahead and uncomment this line here that mounts action cable for the routes so that will activate action cable and we'll be able to see in the front end the next step in order to implement this will be to open up the front end coffee channel and implement will implement these speak method there so let's do that we'll go into room channel and let's implement that speak method this will end up getting encoded into a JSON object and set to the back end and on the other side of things we want to implement the freeze receipt method and so when we receive a message we're just going to go ahead and pop that into our home now let's actually wrap that in a make that a little bit prettier here great so we got that implemented in the front end that's gonna that's gonna be when we speak we're gonna be calling our back end speak our PC with a mess passing in message into it and then when we receive data from action cable we're gonna be calling it with this data method we're gonna just append that data into the Dom inside of our messages div now let me open up the backend cable here now this is one of the things about the rails 5 actually capable generator that is kind of confusing is that stream from is not set by default so you need to populate it it's simply gonna be room channel and then speak is going to have have data path to it the front is actually gonna be through reaction cable you're gonna be getting a hash so here we'll have data and then we'll have a met that will have a message key within it now in order to broadcast back out to the browser we're just gonna say action cable dot server dot broadcast and then we're gonna say room underscore channel and data message and that's it we should be wired up for action cable now so what we do when you make changes to actually cable you need to always restart the rail server so I'll go ahead and restart the real server here and then we'll go back over to the browser and give it a shot ok so let's see what happens here okay we successfully upgraded to our web socket here so now let's just make sure that on the console let's see if we can send a message Wow very cool so it works that's fantastic so that's action cable that's real-time and rails in 15 minutes at this point I'm gonna go ahead and make it actually save the message to the database right now if I reload this page those messages are gonna disappear they no longer they're not being stored there not being persisted so now we're gonna persist those those messages we already created a message model so now we just have to have our action cable implementation create message records so go ahead and get back to the code here and let's go ahead and do that so instead of having the speak actually just broadcast back out we're just gonna go ahead and create a message we'll say a message dot to create I don't just a content colon message our data message so the issue here is that now we're creating the message but now we've got a broadcast it back out to action cable so how will we do that well let's go ahead and jump into our model and look at that okay now we're in the model well what we want to do here is we want to have an after create commit after we create the object we committed to the database then we want to send the message out to the channel in order to do that we're not going to want to do this inside the context of the channel itself so we're gonna want to use a background job that so I'm gonna go ahead and create a broadcast message job and I'm gonna tell it to perform later which will run it in the background and I'm gonna pass this particular message object that was created to it now we'll go ahead and and use the generators to generate that job so we'll go rails generate job and we'll say broadcast message now we'll go ahead and generate our broadcast message job so we can pop that open so let's go ahead and edit that job we're gonna perform we're gonna get we get called we're gonna have we're gonna be getting our message object there so now what we need to do here is we're gonna this is what we're gonna broadcast so we're gonna say action cable dot server dot broadcast never say room Channel and then we're gonna send a message but we're gonna have to render we want to render that message what we're gonna do is we're gonna actually use action view to do our rendering so we can say render message message and then we'll go ahead and put Matt a private method with that render function so we'll say under message and then in here we'll go ahead and use a shiny new rails 5 feature which is we can go to the application controller and we can use render dot it's called render render and then this will use our the view layer of rails on the backend so we can now do full full rails view rendering from background jobs or any other sort of back-end job or via the main purpose of this was for rails API so let's go ahead and render the message and now calling that it'll know to find our partial and we'll render our HTML and with that we will be able to use all the caching mechanisms available in rails which is really fantastic ok great so we not now we have that broadcast message job because we made changes to the channel we will have we will want to can't to kill our rails process so we'll do that we'll restart that and then we'll also go ahead and update our room coffee there and take our paragraph tag out of out of that so we'll go into the JavaScript general room and we'll go in here and right here where we put this paragraph tag we're no longer gonna need that because we are gonna be passing the HTML into from from rails rails is gonna be rendering our HTML for us great ok so we should be able to see action cable with persistent data now so let's go back and and look at the browser okay boom hello world everything's all good okay let's go ahead and say Jeff Wow cool and we can say Travis neat and when we reload those messages we'll still either so what's happening here is we're we're making that our PC called over WebSockets to the backend the backend is creating a record in the data in the database and then after it creates it we're calling we have a callback that is firing a background task that renders the HTML template and spits it back out over the WebSocket to the client and and we see it in the browser very very cool and very easy so with that I will say that is the conclusion of action cable chat in rails you you can use that with multiple users and without authentication they can message back and forth obviously that's just a little toy implementation so at this point I'm gonna take up a step further and I'm gonna add user registrations and and and ownership of messages to this implementation so let's go ahead and do that okay so first thing I'm gonna do I'm gonna add devise in to our gem file devise is a popular user registrations gem it I it's highly advisable to use something like devised to put my user accounts it's been battle tested there's you know the uses it uses a battle-tested cryptographic algorithms for for managing passwords and it it's something that I highly recommend for that somebody is their github repository is gem there may be some credibility issues using the bleeding and bleeding edge versions of rails so I'm gonna go ahead and do that makes it makes it I'm pretty reliable so let's go ahead and run the bundle after this bundle completes we're gonna go ahead and run the device generators to get things set up in our project okay bundle so we're gonna go ahead and run a device install that's gonna go ahead and just set up our to something to device basics now I'm going to use the devise generator to generate a user model for us to use this will be our user the that we use for registrations and lastly I'm gonna actually go ahead and add ownership the reference for our user to messages this is using a cool feature of that was introduced in rails 4 - I believe that lets you use add references with migrations which makes it very easy to to add references that'll be you've got our user added to the messages we'll go ahead and run a migration then I'm gonna go ahead and commit this so that we have a stopping point here great very cool ok so now we need to add an ownership to our model so I'm going to go into the model and we're gonna add our relationship in here we're gonna give it an ownership by our user and then we're gonna go ahead and pop it our controller and require authentication great okay so let's add another vacation there this is a how we add authentication using the device controls cool so now another row at that point I'm gonna go ahead and jump in and pull in some pilot some some HTML templates that I prepared for this update our application HTML there some basic stuff it just changes title on a couple other little things make it a little bit more attractive go ahead and to the message we're gonna populate that one a little bit more markup there and the messages a little more advanced we're going to we're introducing the users email address and that sort of thing now let's go ahead and pop in to the coffee and remember our coffee basically just added this line here to scroll to the top so it's a little bit more interactive that's it now we're gonna go into rooms coffee which is the controller of JavaScript and I'm just gonna add it's gonna make it a little bit more attractive onload it's gonna unload we're gonna scroll the messages to the top we're gonna focus the input that's about it cool and we're gonna also implement some JavaScript to input on the messages and we're gonna lastly we're going to update our main room template here now we're gonna add a logout link we're just rendering the messages nothing too fancy there okay so I've got those updates in there it's fantastic we're gonna need now to add the current user to messages when we create them so in order to do that we're gonna have to implement our current user on on our application channel this is because action cable doesn't actually have access to the user session it only has access to the user's cookies so in order to implement that we're gonna have to utilize the hooks that are provided by a warden which is part of devise in order to create cookies at sign in and destroy cookies at sign out so in order to that I'm gonna go ahead and create a new file so we need to go ahead and go into our config here and go into our initializers work this is where you initialize your gems and whatnot and I'm gonna go ahead add a new file there in the initializers there so under the initializers I'm gonna actually be creating a warden underscore hooks RB and inside of this file which I'll open up here inside this warden hooks file I'm gonna go ahead and read in a file I've got here already prepared and basically for board and we're just gonna have after after the user is authenticated and we're going to set a cookie that's signed with the cryptographic secret key of the app and we're gonna set an expiration date and we're gonna we're gonna delete that cookie at logout and we'll go ahead and say that then we're gonna have to go it open up our connection our application cable connection here so we'll go ahead and go into connection RB this is our application cable and inside the connection inside here we're going to need to implement our current you a current user method so let me show you how that works basically on connect to the cable we're gonna set the current user the self current user to find verified user and we're gonna add a logger flat AG so that we can see messages from each user in the console and we're going to implement this find verified user method which will pull the current user by idea and if it's there and then return it otherwise it will reject it and that'll be it pretty good okay we'll see if that guy and now let's go ahead and update all of our message records so that they all have a user because before we can use the users we're gonna need to do that so I'll jump out of here we're in the console again now spring may give us trouble here Springs preloader I'm gonna make I'm gonna I'm a restarted because we added new gems and unless things changed oops didn't you do that but we'll go ahead and let spring start over itself pop open the console here and I'm gonna go ahead and update the messages to all have users so we're gonna go ahead just do message at all the update underscore all I'm gonna say user underscore ID : 1 we're going to update all all the messages to have the same user ID they're pretty straightforward ok now let's go ahead and fire up our app again we reload here we are going to get we're going to have to authenticate okay this is devised here so we're gonna go ahead and create a new account go ahead and sign up okay here's our here's our messages so now we have time stamps we have our email addresses attached to it we could register multiple users and and chat looks like we got a bug so we're our transaction isn't functioning correctly and it's because we haven't added a current user on to our channel so we'll go ahead and get in there and do that what we need to do here is go into our channel and right here we're gonna need to say user calling current underscore user stomach we created create a message we're gonna pass the current user and that's going to come from that implementation that we built in the application cable great so because I made a change to the channel I have to restart the rails server so go ahead and restart the real server will reload and let's pull up the browser great okay oh there we go send new messages okay cool okay so that's it we've got user registrations were able to create messages I'm gonna go ahead and do a side by side demo here let's go ahead and pull up I'm pulling my desktop and I'm gonna go ahead and pull up another browser in here pull them up side by side now I'm gonna use an incognito browser here so we can get two sessions fired up let's go in there and let's create a new account here was like say Joe go ahead sign up cool Joe's in there going here in the console and I'm just gonna send a message hey we got a message from Joe down here now if I send a message from this client we'll see you need let's see that populate down in here in that client very cool okay so go ahead and get back into the code here the next thing we're gonna do I'm just gonna put us as you down here so let's do that let's make it look nice and actually I'm gonna have to get I'm gonna update the show it's gonna be the only other file we're gonna change here let's get this guy an update okay see what she looks like and here it is I'll go ahead and open up another browser to another browser window year and another and we'll take a look send a message I'll send a couple messages very cool that's it so there we go there you have it there's a real-time chat with action cable user registrations and a nice pretty slack skin thanks for watching
Info
Channel: Jeff Nappi
Views: 13,268
Rating: undefined out of 5
Keywords: ruby, ruby on rails, actioncable, websockets, programming
Id: tyNepRO_ERc
Channel Id: undefined
Length: 40min 19sec (2419 seconds)
Published: Sat Mar 19 2016
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.