Using Actioncable Mode and the Rails 5 API Together

I am creating a very basic chat application. My goal is to create a backup Rails API server, and then create an iOS, Android, web client and desktop client. This is exclusively for learning web sockets and mobile development.

I have never used Actioncable, and my knowledge of Websockets is very limited. I would like to know if I can install Actioncable in my Rails API and associate it with Node (for example).

Does Actioncable Like Any Other Websocket? Can I connect to it from my Node application through ws://<host>/cableand have a pub-sub functional system between any client and Rails?

I apologize if this does not make sense, it is difficult for me to formulate it :)

Thank!

+4
source share
1 answer

Indeed you can!

  • Just like you create any api application, use a generator

    rails new my_app --api
    
  • Create your_channel

    rails generate channel your_channel
    
  • Add Mount Path to routes.rb

    mount ActionCable.server => '/cable'
    
  • Allow thread for subscription method in /app/channels/your_channel.rb

    class YourChannel < ApplicationCable::Channel
    
      def subscribed
        stream_from 'messages'        #  <----- Stream Name Here
      end
    
      def unsubscribed
        # Any cleanup needed when channel is unsubscribed
      end
    
    end
    
  • Call ActionCable.server.broadcastfrom any other part of your application to the stream

    ActionCable.server.broadcast 'messages', message: 'ping'
    
  • Now use your interface to test it. Since you said you want iOS Android, and also mentioned node, I assume that you are using (or want to use)react-native

    import ActionCable from 'react-native-actioncable';
    const cable = ActionCable.createConsumer("ws://localhost:3000/cable");
    
    class YourReactClass extends React.Component {
    
        # add or update the following
    
        componentDidMount = () => {
            console.log("componentDidMount executed");
            this.subscription = cable.subscriptions.create("OrderChannel", {
                connected: function() { console.log("connected: action cable") },
                    disconnected: function() { console.log("disconnected: action cable") },
                    received: function (data) { console.log(data) }
                }
            )
        };
    
        componentWillUnmount () {
            this.subscription &&
            cable.subscriptions.remove(this.subscription)
        }
    
    }
    

And you are good to go, build your logic on top of this ... If you have any problems, let me know.

+6
source

Source: https://habr.com/ru/post/1661240/


All Articles