Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

ruby on rails - How to use ActionCable as API

I built a very simple app using Rails 5 beta 1 and ActionCable to show when users come online and let them send messages to each other.

Now, I would basically like to take the client-side part of ActionCable, implement it in the context of another app (that does not run on Rails 5) and connect it with the first app to send and receive data (such as the online status of users or messages).

To send data from that second app, I assume, I can simply make an AJAX POST request. The question is: How do I subscribe from my second app to an open connection of the first app?

Or even: How do I subscribe to the ActionCable connection of my Rails app from another app via API?

My guess is, I essentially want to include this coffeescript somehow in my second app:

App.appearance = App.cable.subscriptions.create "AppearanceChannel",
  connected: ->
    # Called when the subscription is ready for use on the server

  disconnected: ->
    # Called when the subscription has been terminated by the server

  received: (data) ->
    # ...
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

While mwalsher's solution was extremely helpful to me, I recently found a pull request on the Rails repository with an official solution to my question.

https://github.com/rails/rails/pull/24991

I assume, in the near future this will be added to the main documentation. Here is the link to the official actioncable npm package: https://www.npmjs.com/package/actioncable

You can use it similar to mwalsher's solution with any JS app. Just install the npm package:

npm install actioncable --save

Here the JS example from the documentation:

ActionCable = require('actioncable')

var cable = ActionCable.createConsumer('wss://RAILS-API-PATH.com/cable')

cable.subscriptions.create('AppearanceChannel', {
  // normal channel code goes here...
});

Edit: The pull request has been merged for a while, now and the description is part of the official Readme - just not yet in the Rails Guides.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...