{"id":20824801,"url":"https://github.com/react-dev-james/rails","last_synced_at":"2025-03-12T07:14:51.647Z","repository":{"id":206158850,"uuid":"117215587","full_name":"react-dev-james/Rails","owner":"react-dev-james","description":null,"archived":false,"fork":false,"pushed_at":"2018-04-02T02:50:04.000Z","size":372,"stargazers_count":3,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"master","last_synced_at":"2025-01-18T17:25:04.813Z","etag":null,"topics":["activerecord","html","mvc","rails","ruby"],"latest_commit_sha":null,"homepage":null,"language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/react-dev-james.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"MIT-LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2018-01-12T08:35:18.000Z","updated_at":"2019-01-31T14:27:48.000Z","dependencies_parsed_at":"2023-11-08T10:32:53.110Z","dependency_job_id":null,"html_url":"https://github.com/react-dev-james/Rails","commit_stats":null,"previous_names":["react-dev-james/rails"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/react-dev-james%2FRails","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/react-dev-james%2FRails/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/react-dev-james%2FRails/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/react-dev-james%2FRails/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/react-dev-james","download_url":"https://codeload.github.com/react-dev-james/Rails/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243172144,"owners_count":20247887,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["activerecord","html","mvc","rails","ruby"],"created_at":"2024-11-17T22:23:47.586Z","updated_at":"2025-03-12T07:14:51.623Z","avatar_url":"https://github.com/react-dev-james.png","language":"Ruby","readme":"# Action Cable – Integrated WebSockets for Rails\n\nAction Cable seamlessly integrates WebSockets with the rest of your Rails application.\nIt allows for real-time features to be written in Ruby in the same style\nand form as the rest of your Rails application, while still being performant\nand scalable. It's a full-stack offering that provides both a client-side\nJavaScript framework and a server-side Ruby framework. You have access to your full\ndomain model written with Active Record or your ORM of choice.\n\n## Terminology\n\nA single Action Cable server can handle multiple connection instances. It has one\nconnection instance per WebSocket connection. A single user may have multiple\nWebSockets open to your application if they use multiple browser tabs or devices.\nThe client of a WebSocket connection is called the consumer.\n\nEach consumer can in turn subscribe to multiple cable channels. Each channel encapsulates\na logical unit of work, similar to what a controller does in a regular MVC setup. For example,\nyou could have a `ChatChannel` and an `AppearancesChannel`, and a consumer could be subscribed to either\nor to both of these channels. At the very least, a consumer should be subscribed to one channel.\n\nWhen the consumer is subscribed to a channel, they act as a subscriber. The connection between\nthe subscriber and the channel is, surprise-surprise, called a subscription. A consumer\ncan act as a subscriber to a given channel any number of times. For example, a consumer\ncould subscribe to multiple chat rooms at the same time. (And remember that a physical user may\nhave multiple consumers, one per tab/device open to your connection).\n\nEach channel can then again be streaming zero or more broadcastings. A broadcasting is a\npubsub link where anything transmitted by the broadcaster is sent directly to the channel\nsubscribers who are streaming that named broadcasting.\n\nAs you can see, this is a fairly deep architectural stack. There's a lot of new terminology\nto identify the new pieces, and on top of that, you're dealing with both client and server side\nreflections of each unit.\n\n## Examples\n\n### A full-stack example\n\nThe first thing you must do is define your `ApplicationCable::Connection` class in Ruby. This\nis the place where you authorize the incoming connection, and proceed to establish it,\nif all is well. Here's the simplest example starting with the server-side connection class:\n\n```ruby\n# app/channels/application_cable/connection.rb\nmodule ApplicationCable\n  class Connection \u003c ActionCable::Connection::Base\n    identified_by :current_user\n\n    def connect\n      self.current_user = find_verified_user\n    end\n\n    private\n      def find_verified_user\n        if verified_user = User.find_by(id: cookies.encrypted[:user_id])\n          verified_user\n        else\n          reject_unauthorized_connection\n        end\n      end\n  end\nend\n```\nHere `identified_by` is a connection identifier that can be used to find the specific connection again or later.\nNote that anything marked as an identifier will automatically create a delegate by the same name on any channel instances created off the connection.\n\nThis relies on the fact that you will already have handled authentication of the user, and\nthat a successful authentication sets a signed cookie with the `user_id`. This cookie is then\nautomatically sent to the connection instance when a new connection is attempted, and you\nuse that to set the `current_user`. By identifying the connection by this same current_user,\nyou're also ensuring that you can later retrieve all open connections by a given user (and\npotentially disconnect them all if the user is deleted or deauthorized).\n\nNext, you should define your `ApplicationCable::Channel` class in Ruby. This is the place where you put\nshared logic between your channels.\n\n```ruby\n# app/channels/application_cable/channel.rb\nmodule ApplicationCable\n  class Channel \u003c ActionCable::Channel::Base\n  end\nend\n```\n\nThe client-side needs to setup a consumer instance of this connection. That's done like so:\n\n```js\n// app/assets/javascripts/cable.js\n//= require action_cable\n//= require_self\n//= require_tree ./channels\n\n(function() {\n  this.App || (this.App = {});\n\n  App.cable = ActionCable.createConsumer(\"ws://cable.example.com\");\n}).call(this);\n```\n\nThe `ws://cable.example.com` address must point to your Action Cable server(s), and it\nmust share a cookie namespace with the rest of the application (which may live under http://example.com).\nThis ensures that the signed cookie will be correctly sent.\n\nThat's all you need to establish the connection! But of course, this isn't very useful in\nitself. This just gives you the plumbing. To make stuff happen, you need content. That content\nis defined by declaring channels on the server and allowing the consumer to subscribe to them.\n\n\n### Channel example 1: User appearances\n\nHere's a simple example of a channel that tracks whether a user is online or not, and also what page they are currently on.\n(This is useful for creating presence features like showing a green dot next to a user's name if they're online).\n\nFirst you declare the server-side channel:\n\n```ruby\n# app/channels/appearance_channel.rb\nclass AppearanceChannel \u003c ApplicationCable::Channel\n  def subscribed\n    current_user.appear\n  end\n\n  def unsubscribed\n    current_user.disappear\n  end\n\n  def appear(data)\n    current_user.appear on: data['appearing_on']\n  end\n\n  def away\n    current_user.away\n  end\nend\n```\n\nThe `#subscribed` callback is invoked when, as we'll show below, a client-side subscription is initiated. In this case,\nwe take that opportunity to say \"the current user has indeed appeared\". That appear/disappear API could be backed by\nRedis or a database or whatever else. Here's what the client-side of that looks like:\n\n```coffeescript\n# app/assets/javascripts/cable/subscriptions/appearance.coffee\nApp.cable.subscriptions.create \"AppearanceChannel\",\n  # Called when the subscription is ready for use on the server\n  connected: -\u003e\n    @install()\n    @appear()\n\n  # Called when the WebSocket connection is closed\n  disconnected: -\u003e\n    @uninstall()\n\n  # Called when the subscription is rejected by the server\n  rejected: -\u003e\n    @uninstall()\n\n  appear: -\u003e\n    # Calls `AppearanceChannel#appear(data)` on the server\n    @perform(\"appear\", appearing_on: $(\"main\").data(\"appearing-on\"))\n\n  away: -\u003e\n    # Calls `AppearanceChannel#away` on the server\n    @perform(\"away\")\n\n\n  buttonSelector = \"[data-behavior~=appear_away]\"\n\n  install: -\u003e\n    $(document).on \"turbolinks:load.appearance\", =\u003e\n      @appear()\n\n    $(document).on \"click.appearance\", buttonSelector, =\u003e\n      @away()\n      false\n\n    $(buttonSelector).show()\n\n  uninstall: -\u003e\n    $(document).off(\".appearance\")\n    $(buttonSelector).hide()\n```\n\nSimply calling `App.cable.subscriptions.create` will setup the subscription, which will call `AppearanceChannel#subscribed`,\nwhich in turn is linked to the original `App.cable` -\u003e `ApplicationCable::Connection` instances.\n\nNext, we link the client-side `appear` method to `AppearanceChannel#appear(data)`. This is possible because the server-side\nchannel instance will automatically expose the public methods declared on the class (minus the callbacks), so that these\ncan be reached as remote procedure calls via a subscription's `perform` method.\n\n### Channel example 2: Receiving new web notifications\n\nThe appearance example was all about exposing server functionality to client-side invocation over the WebSocket connection.\nBut the great thing about WebSockets is that it's a two-way street. So now let's show an example where the server invokes\nan action on the client.\n\nThis is a web notification channel that allows you to trigger client-side web notifications when you broadcast to the right\nstreams:\n\n```ruby\n# app/channels/web_notifications_channel.rb\nclass WebNotificationsChannel \u003c ApplicationCable::Channel\n  def subscribed\n    stream_from \"web_notifications_#{current_user.id}\"\n  end\nend\n```\n\n```coffeescript\n# Client-side, which assumes you've already requested the right to send web notifications\nApp.cable.subscriptions.create \"WebNotificationsChannel\",\n  received: (data) -\u003e\n    new Notification data[\"title\"], body: data[\"body\"]\n```\n\n```ruby\n# Somewhere in your app this is called, perhaps from a NewCommentJob\nActionCable.server.broadcast \\\n  \"web_notifications_#{current_user.id}\", { title: 'New things!', body: 'All the news that is fit to print' }\n```\n\nThe `ActionCable.server.broadcast` call places a message in the Action Cable pubsub queue under a separate broadcasting name for each user. For a user with an ID of 1, the broadcasting name would be `web_notifications_1`.\nThe channel has been instructed to stream everything that arrives at `web_notifications_1` directly to the client by invoking the\n`#received(data)` callback. The data is the hash sent as the second parameter to the server-side broadcast call, JSON encoded for the trip\nacross the wire, and unpacked for the data argument arriving to `#received`.\n\n\n### Passing Parameters to Channel\n\nYou can pass parameters from the client side to the server side when creating a subscription. For example:\n\n```ruby\n# app/channels/chat_channel.rb\nclass ChatChannel \u003c ApplicationCable::Channel\n  def subscribed\n    stream_from \"chat_#{params[:room]}\"\n  end\nend\n```\n\nIf you pass an object as the first argument to `subscriptions.create`, that object will become the params hash in your cable channel. The keyword `channel` is required.\n\n```coffeescript\n# Client-side, which assumes you've already requested the right to send web notifications\nApp.cable.subscriptions.create { channel: \"ChatChannel\", room: \"Best Room\" },\n  received: (data) -\u003e\n    @appendLine(data)\n\n  appendLine: (data) -\u003e\n    html = @createLine(data)\n    $(\"[data-chat-room='Best Room']\").append(html)\n\n  createLine: (data) -\u003e\n    \"\"\"\n    \u003carticle class=\"chat-line\"\u003e\n      \u003cspan class=\"speaker\"\u003e#{data[\"sent_by\"]}\u003c/span\u003e\n      \u003cspan class=\"body\"\u003e#{data[\"body\"]}\u003c/span\u003e\n    \u003c/article\u003e\n    \"\"\"\n```\n\n```ruby\n# Somewhere in your app this is called, perhaps from a NewCommentJob\nActionCable.server.broadcast \\\n  \"chat_#{room}\", { sent_by: 'Paul', body: 'This is a cool chat app.' }\n```\n\n\n### Rebroadcasting message\n\nA common use case is to rebroadcast a message sent by one client to any other connected clients.\n\n```ruby\n# app/channels/chat_channel.rb\nclass ChatChannel \u003c ApplicationCable::Channel\n  def subscribed\n    stream_from \"chat_#{params[:room]}\"\n  end\n\n  def receive(data)\n    ActionCable.server.broadcast \"chat_#{params[:room]}\", data\n  end\nend\n```\n\n```coffeescript\n# Client-side, which assumes you've already requested the right to send web notifications\nApp.chatChannel = App.cable.subscriptions.create { channel: \"ChatChannel\", room: \"Best Room\" },\n  received: (data) -\u003e\n    # data =\u003e { sent_by: \"Paul\", body: \"This is a cool chat app.\" }\n\nApp.chatChannel.send({ sent_by: \"Paul\", body: \"This is a cool chat app.\" })\n```\n\nThe rebroadcast will be received by all connected clients, _including_ the client that sent the message. Note that params are the same as they were when you subscribed to the channel.\n\n\n\n\n## Configuration\n\nAction Cable has three required configurations: a subscription adapter, allowed request origins, and the cable server URL (which can optionally be set on the client side).\n\n### Redis\n\nBy default, `ActionCable::Server::Base` will look for a configuration file in `Rails.root.join('config/cable.yml')`.\nThis file must specify an adapter and a URL for each Rails environment. It may use the following format:\n\n```yaml\nproduction: \u0026production\n  adapter: redis\n  url: redis://10.10.3.153:6381\ndevelopment: \u0026development\n  adapter: redis\n  url: redis://localhost:6379\ntest: *development\n```\n\nYou can also change the location of the Action Cable config file in a Rails initializer with something like:\n\n```ruby\nRails.application.paths.add \"config/cable\", with: \"somewhere/else/cable.yml\"\n```\n\n### Allowed Request Origins\n\nAction Cable will only accept requests from specific origins.\n\nBy default, only an origin matching the cable server itself will be permitted.\nAdditional origins can be specified using strings or regular expressions, provided in an array.\n\n```ruby\nRails.application.config.action_cable.allowed_request_origins = ['http://rubyonrails.com', /http:\\/\\/ruby.*/]\n```\n\nWhen running in the development environment, this defaults to \"http://localhost:3000\".\n\nTo disable protection and allow requests from any origin:\n\n```ruby\nRails.application.config.action_cable.disable_request_forgery_protection = true\n```\n\nTo disable automatic access for same-origin requests, and strictly allow\nonly the configured origins:\n\n```ruby\nRails.application.config.action_cable.allow_same_origin_as_host = false\n```\n\n### Consumer Configuration\n\nOnce you have decided how to run your cable server (see below), you must provide the server URL (or path) to your client-side setup.\nThere are two ways you can do this.\n\nThe first is to simply pass it in when creating your consumer. For a standalone server,\nthis would be something like: `App.cable = ActionCable.createConsumer(\"ws://example.com:28080\")`, and for an in-app server,\nsomething like: `App.cable = ActionCable.createConsumer(\"/cable\")`.\n\nThe second option is to pass the server URL through the `action_cable_meta_tag` in your layout.\nThis uses a URL or path typically set via `config.action_cable.url` in the environment configuration files, or defaults to \"/cable\".\n\nThis method is especially useful if your WebSocket URL might change between environments. If you host your production server via https, you will need to use the wss scheme\nfor your Action Cable server, but development might remain http and use the ws scheme. You might use localhost in development and your\ndomain in production.\n\nIn any case, to vary the WebSocket URL between environments, add the following configuration to each environment:\n\n```ruby\nconfig.action_cable.url = \"ws://example.com:28080\"\n```\n\nThen add the following line to your layout before your JavaScript tag:\n\n```erb\n\u003c%= action_cable_meta_tag %\u003e\n```\n\nAnd finally, create your consumer like so:\n\n```coffeescript\nApp.cable = ActionCable.createConsumer()\n```\n\n### Other Configurations\n\nThe other common option to configure is the log tags applied to the per-connection logger. Here's an example that uses the user account id if available, else \"no-account\" while tagging:\n\n```ruby\nconfig.action_cable.log_tags = [\n  -\u003e request { request.env['user_account_id'] || \"no-account\" },\n  :action_cable,\n  -\u003e request { request.uuid }\n]\n```\n\nFor a full list of all configuration options, see the `ActionCable::Server::Configuration` class.\n\nAlso note that your server must provide at least the same number of database connections as you have workers. The default worker pool is set to 4, so that means you have to make at least that available. You can change that in `config/database.yml` through the `pool` attribute.\n\n\n## Running the cable server\n\n### Standalone\nThe cable server(s) is separated from your normal application server. It's still a Rack application, but it is its own Rack\napplication. The recommended basic setup is as follows:\n\n```ruby\n# cable/config.ru\nrequire_relative '../config/environment'\nRails.application.eager_load!\n\nrun ActionCable.server\n```\n\nThen you start the server using a binstub in bin/cable ala:\n```sh\n#!/bin/bash\nbundle exec puma -p 28080 cable/config.ru\n```\n\nThe above will start a cable server on port 28080.\n\n### In app\n\nFor example, to listen for WebSocket requests on `/websocket`, specify that path to `config.action_cable.mount_path`:\n\n```ruby\n# config/application.rb\nclass Application \u003c Rails::Application\n  config.action_cable.mount_path = '/websocket'\nend\n```\n\nFor every instance of your server you create and for every worker your server spawns, you will also have a new instance of Action Cable, but the use of Redis keeps messages synced across connections.\n\n### Notes\n\nBeware that currently, the cable server will _not_ auto-reload any changes in the framework. As we've discussed, long-running cable connections mean long-running objects. We don't yet have a way of reloading the classes of those objects in a safe manner. So when you change your channels, or the model your channels use, you must restart the cable server.\n\nWe'll get all this abstracted properly when the framework is integrated into Rails.\n\nThe WebSocket server doesn't have access to the session, but it has access to the cookies. This can be used when you need to handle authentication. You can see one way of doing that with Devise in this [article](http://www.rubytutorial.io/actioncable-devise-authentication).\n\n## Dependencies\n\nAction Cable provides a subscription adapter interface to process its pubsub internals. By default, asynchronous, inline, PostgreSQL, and Redis adapters are included. The default adapter in new Rails applications is the asynchronous (`async`) adapter. To create your own adapter, you can look at `ActionCable::SubscriptionAdapter::Base` for all methods that must be implemented, and any of the adapters included within Action Cable as example implementations.\n\n\n## Deployment\n\nAction Cable is powered by a combination of WebSockets and threads. All of the\nconnection management is handled internally by utilizing Ruby's native thread\nsupport, which means you can use all your regular Rails models with no problems\nas long as you haven't committed any thread-safety sins.\n\nThe Action Cable server does _not_ need to be a multi-threaded application server.\nAction Cable\nthen manages connections internally, in a multithreaded manner, regardless of\nwhether the application server is multi-threaded or not. So Action Cable works\nwith all the popular application servers -- Unicorn, Puma and Passenger.\n\nAction Cable does not work with WEBrick, because WEBrick does not support the\nRack socket hijacking API.\n\n## Frontend assets\n\nAction Cable's frontend assets are distributed through two channels: the\nofficial gem and npm package, both titled `actioncable`.\n\n### Gem usage\n\nThrough the `actioncable` gem, Action Cable's frontend assets are\navailable through the Rails Asset Pipeline. Create a `cable.js` or\n`cable.coffee` file (this is automatically done for you with Rails\ngenerators), and then simply require the assets:\n\nIn JavaScript...\n\n```javascript\n//= require action_cable\n```\n\n... and in CoffeeScript:\n\n```coffeescript\n#= require action_cable\n```\n\n### npm usage\n\nIn addition to being available through the `actioncable` gem, Action Cable's\nfrontend JS assets are also bundled in an officially supported npm module,\nintended for usage in standalone frontend applications that communicate with a\nRails application. A common use case for this could be if you have a decoupled\nfrontend application written in React, Ember.js, etc. and want to add real-time\nWebSocket functionality.\n\n### Installation\n\n```\nnpm install actioncable --save\n```\n\n### Usage\n\nThe `ActionCable` constant is available as a `require`-able module, so\nyou only have to require the package to gain access to the API that is\nprovided.\n\nIn JavaScript...\n\n```javascript\nActionCable = require('actioncable')\n\nvar cable = ActionCable.createConsumer('wss://RAILS-API-PATH.com/cable')\n\ncable.subscriptions.create('AppearanceChannel', {\n  // normal channel code goes here...\n});\n```\n\nand in CoffeeScript...\n\n```coffeescript\nActionCable = require('actioncable')\n\ncable = ActionCable.createConsumer('wss://RAILS-API-PATH.com/cable')\n\ncable.subscriptions.create 'AppearanceChannel',\n    # normal channel code goes here...\n```\n\n## Download and Installation\n\nThe latest version of Action Cable can be installed with [RubyGems](#gem-usage),\nor with [npm](#npm-usage).\n\n\n## License\n\nAction Cable is released under the MIT license:\n\n* https://opensource.org/licenses/MIT\n\n\n## Support\n\nAPI documentation is at:\n\n* http://api.rubyonrails.org\n\n\nFeature requests should be discussed on the rails-core mailing list here:\n\n* https://groups.google.com/forum/?fromgroups#!forum/rubyonrails-core\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Freact-dev-james%2Frails","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Freact-dev-james%2Frails","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Freact-dev-james%2Frails/lists"}