Slide 1

Slide 1 text

No content

Slide 2

Slide 2 text

ACTIONCABLE, RAILS API AND REACT Modern Single Page Apps

Slide 3

Slide 3 text

Vipul A M @vipulnsward

Slide 4

Slide 4 text

No content

Slide 5

Slide 5 text

“* The weather in Taiwan is HOT with chances of rain in the afternoon. “ - Rexy Second time in Taiwan

Slide 6

Slide 6 text

No content

Slide 7

Slide 7 text

No content

Slide 8

Slide 8 text

No content

Slide 9

Slide 9 text

No content

Slide 10

Slide 10 text

No content

Slide 11

Slide 11 text

Rails App

Slide 12

Slide 12 text

Rails API JSON API ACa Auth JSON React Ember Mobile

Slide 13

Slide 13 text

Rails 5

Slide 14

Slide 14 text

http://blog.bigbinary.com/categories/Rails-5 Rails 5 Blog Series (43+ and counting)

Slide 15

Slide 15 text

API Applications

Slide 16

Slide 16 text

What is an API Application? http://developer.github.com http://dev.twitter.com http://developer.dribbble.com/

Slide 17

Slide 17 text

What is an API Application? https://developer.github.com/v3/emojis/ # GET /emojis
 
 {
 "+1": "https://github.global.ssl.fastly.net/images/icons/emoji/+1.png?v5",
 "-1": "https://github.global.ssl.fastly.net/images/icons/emoji/-1.png?v5",
 "101": "https://github.global.ssl.fastly.net/images/icons/emoji/100.png?v5",
 "1234": "https://github.global.ssl.fastly.net/images/icons/emoji/1234.png?v5",
 "8ball": "https://github.global.ssl.fastly.net/images/icons/emoji/8ball.png?v5",
 "a": "https://github.global.ssl.fastly.net/images/icons/emoji/a.png?v5",
 "ab": "https://github.global.ssl.fastly.net/images/icons/emoji/ab.png?v5"
 }


Slide 18

Slide 18 text

Rails API JSON API ACa Auth JSON React Ember Mobile

Slide 19

Slide 19 text

Why Rails? Rails Development Environment Nifty Testing Inbuilt security Parameter parsing Code Reloads anyone? Header responses Other Rails Goodness: AR, AM, AJ, ACa

Slide 20

Slide 20 text

AP Sweetness URLs and resources Caching Authentication respond_to and content types Generators Plugins- rack-cors, etc.

Slide 21

Slide 21 text

Lets create chatty $ rails new chatty --api

Slide 22

Slide 22 text

--api

Slide 23

Slide 23 text

The End

Slide 24

Slide 24 text

What this does Slimmed down middleware* stack No views & cruft from AV ApplicationController < ActionController::API


Slide 25

Slide 25 text

Default Stack - Rack::Sendfile
 - ActionDispatch::Static
 - ActionDispatch::Executor
 - ActiveSupport::Cache::Strategy::LocalCache::Middleware
 - Rack::Runtime
 - ActionDispatch::RequestId
 - Rails::Rack::Logger
 - ActionDispatch::ShowExceptions
 - ActionDispatch::DebugExceptions
 - ActionDispatch::RemoteIp
 - ActionDispatch::Reloader
 - ActionDispatch::Callbacks
 - ActiveRecord::Migration::CheckPending
 - Rack::Head
 - Rack::ConditionalGet
 - Rack::ETag

Slide 26

Slide 26 text

Extend - config.middleware.use Rack::MethodOverride - config.middleware.delete ::Rack::Sendfile

Slide 27

Slide 27 text

ActionController::API - ActionController::UrlFor
 - ActionController::Redirecting
 - AbstractController::Rendering and ActionController::ApiRendering
 - ActionController::Renderers::All
 - ActionController::ConditionalGet
 - ActionController::BasicImplicitRender
 - ActionController::StrongParameters
 - ActionController::ForceSSL
 - ActionController::DataStreaming
 - AbstractController::Callbacks
 - ActionController::Rescue
 - ActionController::Instrumentation
 - ActionController::ParamsWrapper

Slide 28

Slide 28 text

And more - AbstractController::Translation - ActionController::HttpAuthentication::Basic - ActionView::Layouts - ActionController::Cookies

Slide 29

Slide 29 text

Action Cable

Slide 30

Slide 30 text

What is Action Cable?

Slide 31

Slide 31 text

Pub/Sub

Slide 32

Slide 32 text

Concepts Server Side Components (Connections/Subscriptions) Client Side Components (JS/Coffee) (Consumers) 


Slide 33

Slide 33 text

Server Side Connections Channels Main Channel Subscriptions

Slide 34

Slide 34 text

Server Side Connections Channels Main Channel Subscriptions

Slide 35

Slide 35 text

Connections # app/channels/application_cable/connection.rb
 module ApplicationCable
 class Connection < ActionCable::Connection::Base
 identified_by :current_user
 
 def connect
 self.current_user = find_verified_user
 end
 
 protected
 def find_verified_user
 if current_user = User.find_by(id: cookies.signed[:user_id])
 current_user
 else
 reject_unauthorized_connection
 end
 end
 end
 end

Slide 36

Slide 36 text

Server Side Connections Channels Main Channel Subscriptions

Slide 37

Slide 37 text

Channels # app/channels/application_cable/channel.rb
 module ApplicationCable
 class Channel < ActionCable::Channel::Base
 end
 end # app/channels/update_channel.rb
 class UpdateChannel < ApplicationCable::Channel
 end # app/channels/chat_channel.rb
 class ChatChannel < ApplicationCable::Channel
 end
 


Slide 38

Slide 38 text

Server Side Connections Channels Main Channel Subscriptions

Slide 39

Slide 39 text

Channels # app/channels/chat_channel.rb
 class ChatChannel < ApplicationCable::Channel
 # Called when the consumer has successfully
 # become a subscriber of this channel.
 def subscribed
 end
 
 def my_custom_action
 end
 
 def user_posted_something
 end
 end


Slide 40

Slide 40 text

Client Side Consumer Connection Subscriber

Slide 41

Slide 41 text

Consumer Connection // app/assets/javascripts/cable.js
 //= require action_cable
 //= require_self
 //= require_tree ./channels
 
 (function() {
 this.App || (this.App = {});
 
 App.cable = ActionCable.createConsumer();
 }).call(this);

Slide 42

Slide 42 text

Subscription // app/assets/javascripts/cable/subscriptions/ chat.coffee App.cable.subscriptions.create({ channel: "ChatChannel", room: "Best Room" });

Slide 43

Slide 43 text

Tying them up together Streams Broadcasting

Slide 44

Slide 44 text

Streams # app/channels/chat_channel.rb
 class ChatChannel < ApplicationCable::Channel
 def subscribed stop_all_streams
 stream_from "chat_#{params[:room]}"
 end
 end # app/channels/comments_channel.rb class CommentsChannel < ApplicationCable::Channel
 def subscribed
 post = Post.find(params[:id])
 stream_for post
 end
 end


Slide 45

Slide 45 text

Broadcasts PingsChannel.broadcast_to(
 current_user,
 title: ‘Hey Mark!',
 body: ‘Joey is looking for you.’
 ) 
 CommentsChannel.broadcast_to(@post, @comment)

Slide 46

Slide 46 text

Client Side Subscription App.chatChannel = App.cable.subscriptions.create({ channel: "ChatChannel", room: "Best Room" }, {
 //Entry point when some data will be received received: function (data) {
 return this.appendLine(data);
 }, 
 appendLine: function (data) {
 var html;
 html = this.createLine(data);
 return $("[data-chat-room='Best Room']").append(html);
 }, 
 createLine: function (data) {
 return "data[ "sent_by" ] + “: "+ data[ "body" ];
 }
 });

Slide 47

Slide 47 text

this.perform('follow', { message_id: this.message_id }); App.chatChannel.send({ sent_by: "Vipul", body: "ACa is a bliss." }) Client Side Subscription

Slide 48

Slide 48 text

Somethings to take care of config.action_cable.allowed_request_origins = ['http://rubyonrails.com', %r{http://ruby.*}]
 
 config.action_cable.disable_request_forgery_protection = true


Slide 49

Slide 49 text

Running ACa puma

Slide 50

Slide 50 text

React JS

Slide 51

Slide 51 text

React A Simple Component state/props Life Cycle react-rails

Slide 52

Slide 52 text

A Simple Component var HelloMessage = React.createClass({
 render: function() {
 return
Hello {this.props.name}
;
 }
 });
 
 ReactDOM.render(, mountNode);


Slide 53

Slide 53 text

A Simple Component var Timer = React.createClass({
 getInitialState: function() {
 return {secondsElapsed: 0};
 },
 tick: function() {
 this.setState({secondsElapsed: this.state.secondsElapsed + 1});
 },
 componentDidMount: function() {
 this.interval = setInterval(this.tick, 1000);
 },
 componentWillUnmount: function() {
 clearInterval(this.interval);
 },
 render: function() {
 return (

Seconds Elapsed: {this.state.secondsElapsed}

 );
 }
 });
 
 ReactDOM.render(, mountNode);


Slide 54

Slide 54 text

Life Cycle

Slide 55

Slide 55 text

console.log('Start')
 var App = React.createClass({
 componentWillMount: function(){
 console.log('componentWillMount');
 },
 
 componentDidMount: function(){
 console.log('componentDidMount');
 },
 
 getInitialState: function(){
 return { status: true}
 },
 
 getDefaultProps: function(){
 return {name: 'John'};
 },
 
 …


Slide 56

Slide 56 text

…
 
 render: function() {
 console.log('render');
 return


 {this.state.status.toString()}



 },
 
 componentWillUnmount: function(){
 console.log('componentWillUnmount')
 },
 
 toggleState: function() {
 this.setState({status: !this.state.status})
 }
 });

Slide 57

Slide 57 text

https://www.packtpub.com/web-development/reactjs-example- building-modern-web-applications-react

Slide 58

Slide 58 text

Demo https://github.com/vipulnsward/actioncable-examples https://github.com/vipulnsward/chatty-node

Slide 59

Slide 59 text

spec "it works!”

Slide 60

Slide 60 text

… componentDidMount() {
 this.setupSubscription();
 }
 … setupSubscription() {
 
 App.comments = App.cable.subscriptions.create("CommentsChannel", {
 message_id: this.state.message.id,
 
 connected: function () {
 setTimeout(() => this.perform('follow', { message_id: this.message_id }), 1000);
 },
 
 received: function (data) {
 this.updateCommentList(data.comment);
 },
 
 updateCommentList: this.updateCommentList.bind(this)
 
 });
 
 }

Slide 61

Slide 61 text

class CommentsChannel < ApplicationCable::Channel
 def follow(data)
 stop_all_streams
 stream_from "messages:#{data['message_id'].to_i}:comments"
 end
 
 def unfollow
 stop_all_streams
 end
 end


Slide 62

Slide 62 text

Rails API JSON API ACa Auth JSON React Ember Mobile

Slide 63

Slide 63 text

Fin.

Slide 64

Slide 64 text

Images: flickr.com/search/? text=taiwan&license=2%2C3%2C4%2C5%2C6%2C9 http://blog.bigbinary.com/categories/Rails%205 https://www.packtpub.com/web-development/reactjs-example-building- modern-web-applications-react https://github.com/vipulnsward/actioncable-examples https://github.com/vipulnsward/chatty-node References