and update ActionCable guide to describe exception handling usage
# Please enter the commit message for your changes. Lines starting
# with '#' will be ignored, and an empty message aborts the commit.
#
# On branch master
# Your branch is behind 'origin/master' by 5 commits, and can be fast-forwarded.
#
# Changes to be committed:
# modified: actioncable/CHANGELOG.md
# modified: actioncable/lib/action_cable/connection/base.rb
# modified: actioncable/lib/action_cable/connection/subscriptions.rb
# modified: actioncable/test/connection/subscriptions_test.rb
# modified: guides/source/action_cable_overview.md
#
* You can distinguish connection among others with specific `application_name`
```sql
SELECT application_name FROM pg_stat_activity;
/*
application_name
------------------------
psql
ActionCable-PID-42
(2 rows)
*/
```
* It's possible to customize connection identification with `id` option in `cable.yml`
`ActionCable-PID-#{$$}` is the default value
* Related tests refactoring
* `ActionCable::Server#config.cable` is no mutated anymore inside Redis subscription adapter
We have run into issues in the past where the actioncable compiled
javascript bundle got out of sync with the source code. For example, in
30a0c7e040 only the compiled bundle was
modified. This meant that anyone who ran `yarn build` in the actioncable
directory would then see a dirty git status indicating changes to the
compiled bundle, despite not having made any changes to the actioncable
javascript source code. We fixed that particular inconsistency in
a4c27588d5. However, the same problem
could reoccur.
To address this, I've added a new test to enforce that actioncable's
compiled javascript bundle is in sync with the source code. When the
compiled bundle is in sync with the source code, the test will pass:
$ bundle exec ruby -Itest test/javascript_package_test.rb
Run options: --seed 19308
# Running:
yarn run v1.12.3
$ yarn lint && bundle exec rake assets:codegen
$ eslint app/javascript
$ rollup --config rollup.config.js
app/javascript/action_cable/index.js → app/assets/javascripts/action_cable.js...
created app/assets/javascripts/action_cable.js in 762ms
✨ Done in 6.35s.
.
Finished in 7.130345s, 0.1402 runs/s, 0.1402 assertions/s.
1 runs, 1 assertions, 0 failures, 0 errors, 0 skips
However, if the two are not in sync, the test will fail. For example, if
you were to apply the following patch (which only updates the source
code):
```
diff --git a/actioncable/app/javascript/action_cable/adapters.js b/actioncable/app/javascript/action_cable/adapters.js
index 4de8131438..d38d9a6a0b 100644
--- a/actioncable/app/javascript/action_cable/adapters.js
+++ b/actioncable/app/javascript/action_cable/adapters.js
@@ -1,4 +1,5 @@
export default {
+ foo: self.foo,
logger: self.console,
WebSocket: self.WebSocket
}
```
the test would then fail like this:
$ bundle exec ruby -Itest test/javascript_package_test.rb
Run options: --seed 26377
# Running:
yarn run v1.12.3
$ yarn lint && bundle exec rake assets:codegen
$ eslint app/javascript
$ rollup --config rollup.config.js
app/javascript/action_cable/index.js → app/assets/javascripts/action_cable.js...
created app/assets/javascripts/action_cable.js in 776ms
✨ Done in 5.55s.
F
Failure:
JavascriptPackageTest#test_compiled_code_is_in_sync_with_source_code [test/javascript_package_test.rb:16]:
--- expected
+++ actual
@@ -3,6 +3,7 @@
})(this, function(exports) {
\"use strict\";
var adapters = {
+ foo: self.foo,
logger: self.console,
WebSocket: self.WebSocket
};
rails test test/javascript_package_test.rb:9
Finished in 5.837403s, 0.1713 runs/s, 0.1713 assertions/s.
1 runs, 1 assertions, 1 failures, 0 errors, 0 skips
Thus, the actioncable test suite will now prevent "the compiled bundle
is out of sync" issues going forward.
Action Cable's JavaScript library can optionally be imported as an ES6 module via `import { … } from "@rails/actioncable/src"`, but that module is broken in most of the releases published on npm:
```
ERROR in ./node_modules/@rails/actioncable/src/connection.js
Module not found: Error: Can't resolve './internal' in './node_modules/@rails/actioncable/src'
@ ./node_modules/@rails/actioncable/src/connection.js
@ ./node_modules/@rails/actioncable/src/index.js
```
Because `internal.js` was gitignored, it would only be included if the publisher happened to have it generated locally. Committing it to version control ensures that won't happen, and gives us better visibility into changes over time.
References:
- https://github.com/rails/rails/pull/34370
- c0368ad090
* Remove unnecessary variable from ActionCable.createWebSocketURL
* Improve ActionCable test by creating the Consumer before reassigning URL
With this change, the test now actually verifies that the Consumer's url
property changes dynamically (from testURL to `${testURL}foo`).
* Fix alphabetization of ActionCable exports
* Failing test case
* feat: Dynamic Url Generation
Change createWebSocketURL to be a closure that allows url to be evaluated at the time the webSocket is established
* refactor: createWebSocketURL to Consumer, remove need for closure
Move initial call to createWebSocketURL in createConsumer
* docs: Add documentation for dynamic url and string args to createConsumer
Co-Authored-By: rmacklin <rmacklin@users.noreply.github.com>
[Ryan Castner, rmacklin]
That would allow us to test broadcasting made with channel, e.g.:
```ruby
class ChatRelayJob < ApplicationJob
def perform_later(room, msg)
ChatChannel.broadcast_to room, message: msg
end
end
```
To test this functionality we need to know the underlying stream name
(to use `assert_broadcasts`), which relies on `channel_name`.
We had to use the following code:
```ruby
assert_broadcasts(ChatChannel.broadcasting_for([ChatChannel.channel_name, room]), 1) do
ChatRelayJob.perform_now
end
```
The problem with this approach is that we use _internal_ API (we shouldn't care about `channel_name` prefix
in our code).
With this commit we could re-write the test as following:
```ruby
assert_broadcasts(ChatChannel.broadcasting_for(room), 1) do
ChatRelayJob.perform_now
end
```
This allows ActionCable to be used in a web worker, where the `document`
global is undefined. Previously, attempting to use ActionCable inside a
web worker would result in this exception after you try to open a
connection:
```
ReferenceError: document is not defined
```
The visibilitychange event won't ever get triggered in a worker, so
adding the listener is effectively a no-op there. But the listener is
mainly a convenience, rather than a critical piece of the javascript
interface, so using ActionCable in a worker will still work. (And you
could listen for visibilitychange yourself in a window script, then tell
the worker to reconnect if you still want that behavior.)
Before this change, attempting to use ActionCable inside a web worker
would result in an exception being thrown:
```
ReferenceError: window is not defined
```
By replacing the `window` reference with `self`, which is available in
both a window context and a worker context, we can avoid this error.
Ref:
https://developer.mozilla.org/en-US/docs/Web/API/Window/self
in Connection#close. We can do this because `isActive()` can only
return `true` if `this.webSocket` is truthy. (We can't have an active
connection without having instantiated a WebSocket. This is confirmed
in the code: Connection#isActive calls Connection#isState which calls
Connection#getState, which checks if `this.webSocket` is truthy and
returns `null` otherwise.)
* Don't reimplement assert_raises
Also test what happens in case there's no explicit rejection.
* Avoid OpenStruct. Remove space beneath private.
* Simplify verification methods for code under test.
* Match documentation with other Rails docs.
Also remove mention of the custom path argument for now.
Unsure how useful that really is.
In #34709 we updated the guide, but `actioncable/README.md` is still
outdated. Instead of fixing content in the file. I suggest
not duplicate the info that is already in the guide and instead remove
the info from the file and just add a message:
"You can read more about Action Cable in the
[Action Cable Overview](https://edgeguides.rubyonrails.org/action_cable_overview.html) guide."
The same approach is being used for Action Mailbox and Action Text,
see #34812 and #34878.
We had a discussion on the Core team and we don't want to expose this information
as a JSON endpoint and not by default.
It doesn't make sense to expose this JSON locally and this controller is only
accessible in dev, so the proposed access from a production app seems off.
This reverts commit 8eaffe7e89, reversing
changes made to b6e4305c3b.
Generally followed the pattern for https://github.com/rails/rails/pull/32034
* Removes needless CI configs for 2.4
* Targets 2.5 in rubocop
* Updates existing CHANGELOG entries for fewer merge conflicts
* Removes Hash#slice extension as that's inlined on Ruby 2.5.
* Removes the need for send on define_method in MethodCallAssertions.
The WebSocket dependency of ActionCable.Connection was made configurable
in 66901c1849
However, the reference here in Connection#getState was not updated to
use the configurable property. This change remedies that and adds a test
to verify it. Additionally, it backfills a test to ensure that
Connection#open uses the configurable property.
* Replace several ActionCable.* references with finer-grained imports
This reduces the number of circular dependencies among the module
imports from 4:
```
(!) Circular dependency: app/javascript/action_cable/index.js -> app/javascript/action_cable/connection.js -> app/javascript/action_cable/index.js
(!) Circular dependency: app/javascript/action_cable/index.js -> app/javascript/action_cable/connection_monitor.js -> app/javascript/action_cable/index.js
(!) Circular dependency: app/javascript/action_cable/index.js -> app/javascript/action_cable/consumer.js -> app/javascript/action_cable/index.js
(!) Circular dependency: app/javascript/action_cable/index.js -> app/javascript/action_cable/subscriptions.js -> app/javascript/action_cable/index.js
```
to 2:
```
(!) Circular dependency: app/javascript/action_cable/index.js -> app/javascript/action_cable/connection.js -> app/javascript/action_cable/index.js
(!) Circular dependency: app/javascript/action_cable/index.js -> app/javascript/action_cable/connection.js -> app/javascript/action_cable/connection_monitor.js -> app/javascript/action_cable/index.js
```
* Remove tests that only test javascript object property assignment
These tests really only assert that you can assign a property to
the ActionCable global object. That's true for pretty much any object
in javascript (it would only be false if the object has been frozen, or
has explicitly set some properties to be nonconfigurable).
* Refactor ActionCable to provide individual named exports
By providing individual named exports rather than a default export which
is an object with all of those properties, we enable applications to
only import the functions they need: any unused functions will be
removed via tree shaking.
Additionally, this restructuring removes the remaining circular
dependencies by extracting the separate adapters and logger modules, so
there are now no warnings when compiling the ActionCable bundle.
Note: This produces two small breaking API changes:
- The `ActionCable.WebSocket` getter and setter would be moved to
`ActionCable.adapters.WebSocket`. If a user is currently configuring
this, when upgrading they'd need to either add a delegated
getter/setter themselves, or change it like this:
```diff
- ActionCable.WebSocket = MyWebSocket
+ ActionCable.adapters.WebSocket = MyWebSocket
```
Applications which don't change the WebSocket adapter would not need
any changes for this when upgrading.
- Similarly, the `ActionCable.logger` getter and setter would be moved
to `ActionCable.adapters.logger`. If a user is currently configuring
this, when upgrading they'd need to either add a delegated
getter/setter themselves, or change it like this:
```diff
- ActionCable.logger = myLogger
+ ActionCable.adapters.logger = myLogger
```
Applications which don't change the logger would not need any changes
for this when upgrading.
These two aspects of the public API have to change because there's no
way to export a property setter for `WebSocket` (or `logger`) such that
this:
```js
import ActionCable from "actioncable"
ActionCable.WebSocket = MyWebSocket
```
would actually update `adapters.WebSocket`. (We can only offer that if
we have two separate source files like if `index.js` uses
`import * as ActionCable from "./action_cable" and then exports a
wrapper which has delegated getters and setters for those properties.)
This API change is very minor - it should be easy for applications to
add the `adapters.` prefix in their assignments or to patch in delegated
setters. And especially because most applications in the wild are not
ever changing the default value of `ActionCable.WebSocket` or
`ActionCable.logger` (because the default values are perfect), this API
breakage is worth the tree-shaking benefits we gain.
* Include source code in published actioncable npm package
This allows actioncable users to ship smaller javascript bundles to
visitors using modern browsers, as demonstrated in this repository:
https://github.com/rmacklin/actioncable-es2015-build-example
In that example, the bundle shrinks by 2.8K (25.2%) when you simply
change the actioncable import to point to the untranspiled src.
If you go a step further, like this:
```
diff --git a/app/scripts/main.js b/app/scripts/main.js
index 17bc031..1a2b2e0 100644
--- a/app/scripts/main.js
+++ b/app/scripts/main.js
@@ -1,6 +1,6 @@
-import ActionCable from 'actioncable';
+import * as ActionCable from 'actioncable';
let cable = ActionCable.createConsumer('wss://cable.example.com');
cable.subscriptions.create('AppearanceChannel', {
```
then the bundle shrinks by 3.6K (31.7%)!
In addition to allowing smaller bundles for those who ship untranspiled
code to modern browsers, including the source code in the published
package can be useful in other ways:
1. Users can import individual modules rather than the whole library
2. As a result of (1), users can also monkey patch parts of actioncable
by importing the relevant module, modifying the exported object, and
then importing the rest of actioncable (which would then use the
patched object).
Note: This is the same enhancement that we made to activestorage in
c0368ad090
* Remove unused commonjs & resolve plugins from ActionCable rollup config
These were added when we copied the rollup config from ActiveStorage,
but ActionCable does not have any commonjs dependencies (it doesn't have
any external dependencies at all), so these plugins are unnecessary here
* Change ActionCable.startDebugging() -> ActionCable.logger.enabled=true
and ActionCable.stopDebugging() -> ActionCable.logger.enabled=false
This API is simpler and more clearly describes what it does
* Change Travis configuration to run yarn install at the root for ActionCable builds
This is necessary now that the repository is using Yarn Workspaces
* Rename .coffee files in ActionCable test suite in prep for decaffeination
* Decaffeinate ActionCable tests
* Replace Blade with Karma and Rollup to run ActionCable JS tests
- Add karma and qunit devDependencies
- Add test script to ActionCable package
- Use rollup to bundle ActionCable tests
- Use karma as the ActionCable JS test runner
* Replace vendored mock-socket with package devDependency in ActionCable
* Move ActionCable yarn install to TravisCI before_install config
* Clean up decaffeinated ActionCable tests to use consistent formatting
30a0c7e040 commited changes to the
compiled bundle but not to the corresponding source files. This meant
that running `yarn build` was producing untracked changes to the
compiled bundle. The fix is to commit the changes to the source files
so that they are in sync.
We've replaced the sprockets `//= require` directives with ES2015
imports. As a result, the ActionCable javascript can now be compiled
with rollup (like ActiveStorage already is).
- Rename action_cable/index.js.erb -> action_cable/index.js
- Add rake task to generate a javascript module of the ActionCable::INTERNAL ruby hash
This will allow us to get rid of ERB from the actioncable javascript,
since it is only used to interpolate ActionCable::INTERNAL.to_json.
- Import INTERNAL directly in ActionCable Connection module
This is necessary to remove a load-order dependency conflict in the
rollup-compiled build. Using ActionCable.INTERNAL would result in a
runtime error:
```
TypeError: Cannot read property 'INTERNAL' of undefined
```
because ActionCable.INTERNAL is not set before the Connection module
is executed.
All other ActionCable.* references are executed inside of the body of a
function, so there is no load-order dependency there.
- Add eslint and eslint-plugin-import devDependencies to actioncable
These will be used to add a linting setup to actioncable like the one
in activestorage.
- Add .eslintrc to actioncable
This lint configuration was copied from activestorage
- Add lint script to actioncable
This is the same as the lint script in activestorage
- Add babel-core, babel-plugin-external-helpers, and babel-preset-env devDependencies to actioncable
These will be used to add ES2015 transpilation support to actioncable
like we have in activestorage.
- Add .babelrc to actioncable
This configuration was copied from activestorage
- Enable loose mode in ActionCable's babel config
This generates a smaller bundle when compiled
- Add rollup devDependencies to actioncable
These will be used to add a modern build pipeline to actioncable like
the one in activestorage.
- Add rollup config to actioncable
This is essentially the same as the rollup config from activestorage
- Add prebuild and build scripts to actioncable package
These scripts were copied from activestorage
- Invoke code generation task as part of actioncable's prebuild script
This will guarantee that the action_cable/internal.js module is
available at build time (which is important, because two other modules
now depend on it).
- Update actioncable package to reference the rollup-compiled files
Now that we have a fully functional rollup pipeline in actioncable, we
can use the compiled output in our npm package.
- Remove build section from ActionCable blade config
Now that rollup is responsible for building ActionCable, we can remove
that responsibility from Blade.
- Remove assets:compile and assets:verify tasks from ActionCable
Now that we've added a compiled ActionCable bundle to version control,
we don't need to compile and verify it at publish-time.
(We're following the pattern set in ActiveStorage.)
- Include compiled ActionCable javascript bundle in published gem
This is necessary to maintain support for depending on the ActionCable
javascript through the Sprockets asset pipeline.
- Add compiled ActionCable bundle to version control
This mirrors what we do in ActiveStorage, and allows ActionCable to
continue to be consumed via the sprockets-based asset pipeline when
using a git source instead of a published version of the gem.
- Remove unnecessary Array.from usages from subscriptions.js
These were all Arrays before, so Array.from is a no-op
- Remove unnecessary IIFEs from subscriptions.js
- Manually decaffeinate sample ActionCable code in comments
Here the coffeescript -> ES2015 conversion was done by hand rather than
using decaffeinate, because these code samples were simple enough.
- Refactor ActionCable.Subscription to avoid initClass
- Refactor ActionCable.Subscription to use ES2015 default parameters
- Refactor ActionCable.ConnectionMonitor to avoid initClass
- Refactor ActionCable.ConnectionMonitor to use shorter variations of null checks
- Remove unnecessary code created because of implicit returns in ConnectionMonitor
This removes the `return` statements that were returning the value of
console.log and those from private methods whose return value was not
being used.
- Refactor ActionCable.Connection to avoid initClass
- Refactor Connection#isProtocolSupported and #isState
This addresses these three decaffeinate cleanup suggestions:
- DS101: Remove unnecessary use of Array.from
- DS104: Avoid inline assignments
- DS204: Change includes calls to have a more natural evaluation order
It also removes the use of Array.prototype.includes, which means we
don't have to worry about providing a polyfill or requiring that end
users provide one.
- Refactor ActionCable.Connection to use ES2015 default parameters
- Refactor ActionCable.Connection to use shorter variations of null checks
- Remove return statements that return the value of console.log() in ActionCable.Connection
- Simplify complex destructure assignment in connection.js
decaffeinate had inserted
```
adjustedLength = Math.max(protocols.length, 1)
```
to be safe, but we know that there has to always be at least one
protocol, so we don't have to worry about protocols.length being 0 here.
- Refactor Connection#getState
The decaffeinate translation of this method was not very clear, so we've
rewritten it to be more natural.
- Simplify destructure assignment in connection.js
- Remove unnecessary use of Array.from from action_cable.js.erb
- Refactor ActionCable#createConsumer and #getConfig
This addresses these two decaffeinate cleanup suggestions:
- DS104: Avoid inline assignments
- DS207: Consider shorter variations of null checks
- Remove unnecessary code created because of implicit returns in action_cable.js.erb
This removes the `return` statements that were returning the value of
console.log and those from methods that just set and unset the
`debugging` flag.
- Remove decaffeinate suggestion about avoiding top-level this
In this case, the top-level `this` is intentional, so it's okay to
ignore this suggestion.
- Remove decaffeinate suggestions about removing unnecessary returns
I did remove some of the return statements in previous commits, where
it seemed appropriate. However, the rest of these should probably remain
because the return values have been exposed through the public API. If
we want to break that contract, we can do so, but I think it should be
done deliberately as part of a breaking-API change (separate from this
coffeescript -> ES2015 conversion)
- Remove unused `unsupportedProtocol` variable from connection.js
Leaving this would cause eslint to fail
- Refactor Subscriptions methods to avoid `for` ... `of` syntax
Babel transpiles `for` ... `of` syntax to use `Symbol.iterator`, which
would require a polyfill in applications that support older browsers.
The `for` ... `of` syntax was produced by running `decaffeinate`, but in
these instances a simpler `map` should be sufficient and avoid any
`Symbol` issues.
Using [decaffeinate], we have converted these files from coffeescript
syntax to ES2015 syntax. Decaffeinate is very conservative in the
conversion process to ensure exact coffeescript semantics are preserved.
Most of the time, it's safe to clean up the code, and decaffeinate has
left suggestions regarding potential cleanups we can take. I'll tackle
those cleanups separately.
After running decaffeinate, I ran:
```
eslint --fix app/javascript
```
using the eslint configuration from ActiveStorage to automatically
correct lint violations in the decaffeinated output. This removed 189
extra semicolons and changed one instance of single quotes to double
quotes.
Note: decaffeinate and eslint can't parse ERB syntax. So I worked around
that by temporarily quoting the ERB:
```diff
@ActionCable =
- INTERNAL: <%= ActionCable::INTERNAL.to_json %>
+ INTERNAL: "<%= ActionCable::INTERNAL.to_json %>"
WebSocket: window.WebSocket
logger: window.console
```
and then removing those quotes after running decaffeinate and eslint.
[decaffeinate]: https://github.com/decaffeinate/decaffeinate
- Rename action_cable/*.coffee -> *.js
- Move app/assets/javascripts/* -> app/javascript/*
- Rename action_cable.js.erb -> action_cable/index.js.erb
Renaming the extension to .js is in preparation for converting these
files from coffeescript to ES2015.
Moving the files to app/javascript and putting the entry point in
index.js.erb changes the structure of ActionCable's javascript to match
the structure of ActiveStorage's javascript.
(We are doing the file moving and renaming in a separate commit to
ensure that the git history of the files will be preserved - i.e. git
will track these as file renames rather than unrelated file
additions/deletions. In particular, git blame will still trace back to
the original authorship.)
* Use Webpacker by default on new apps
* Stop including coffee-rails by default
* Drop using a js_compressor by default
* Drop extra test for coffeescript inclusion by default
* Stick with skip_javascript to signify skipping webpack
* Don't install a JS runtime by default any more
* app/javascript will be the new default directory for JS
* Make it clear that this is just for configuring the default Webpack framework setup now
* Start using the Webpack tag in the default layout
* Irrelevant test
* jQuery is long gone
* Stop having asset pipeline compile default application.js
* Add rails-ujs by default to the Webpack setup
* Add Active Storage JavaScript to application.js pack by default
* Consistent quoting
* Add Turbolinks to default pack
* Add Action Cable to default pack
Need some work on how to set the global consumer that channels will
work with. @javan?
* Require all channels by default and use a separate consumer stub
* Channel generator now targets Webpack style
* Update task docs to match new generator style
* Use uniform import style
* Drop the JS assets generator
It was barely helpful as it was. It’s no longer helpful in a Webpacked
world. Sayonara!
* Add app/javascript to the stats directories
* Simpler import style
Which match the other imports.
* Address test failures from dropping JS compilation (and compression)
* webpacker-default: Modify `AssetsGeneratorTest`
Before:
```
$ bin/test test/generators/assets_generator_test.rb
Run options: --seed 46201
F
Failure:
AssetsGeneratorTest#test_assets [/Users/ttanimichi/ghq/github.com/ttanimichi/rails/railties/test/generators/assets_generator_test.rb:12]:
Expected file "app/assets/javascripts/posts.js" to exist, but does not
bin/test /Users/ttanimichi/ghq/github.com/ttanimichi/rails/railties/test/generators/assets_generator_test.rb:10
.
Finished in 0.031343s, 63.8101 runs/s, 95.7152 assertions/s.
2 runs, 3 assertions, 1 failures, 0 errors, 0 skips
```
After:
```
$ bin/test test/generators/assets_generator_test.rb
Run options: --seed 43571
..
Finished in 0.030370s, 65.8545 runs/s, 65.8545 assertions/s.
2 runs, 2 assertions, 0 failures, 0 errors, 0 skips
```
* webpacker-default: Modify `ChannelGeneratorTest`
Before:
```
$ bin/test test/generators/channel_generator_test.rb
Run options: --seed 8986
.F
Failure:
ChannelGeneratorTest#test_channel_with_multiple_actions_is_created [/Users/ttanimichi/ghq/github.com/ttanimichi/rails/railties/test/generators/channel_generator_test.rb:43]:
Expected file "app/assets/javascripts/channels/chat.js" to exist, but does not
bin/test /Users/ttanimichi/ghq/github.com/ttanimichi/rails/railties/test/generators/channel_generator_test.rb:34
.F
Failure:
ChannelGeneratorTest#test_channel_is_created [/Users/ttanimichi/ghq/github.com/ttanimichi/rails/railties/test/generators/channel_generator_test.rb:29]:
Expected file "app/assets/javascripts/channels/chat.js" to exist, but does not
bin/test /Users/ttanimichi/ghq/github.com/ttanimichi/rails/railties/test/generators/channel_generator_test.rb:22
E
Error:
ChannelGeneratorTest#test_cable_js_is_created_if_not_present_already:
Errno::ENOENT: No such file or directory @ apply2files - /Users/ttanimichi/ghq/github.com/ttanimichi/rails/railties/test/fixtures/tmp/app/assets/javascripts/cable.js
bin/test /Users/ttanimichi/ghq/github.com/ttanimichi/rails/railties/test/generators/channel_generator_test.rb:60
F
Failure:
ChannelGeneratorTest#test_channel_suffix_is_not_duplicated [/Users/ttanimichi/ghq/github.com/ttanimichi/rails/railties/test/generators/channel_generator_test.rb:87]:
Expected file "app/assets/javascripts/channels/chat.js" to exist, but does not
bin/test /Users/ttanimichi/ghq/github.com/ttanimichi/rails/railties/test/generators/channel_generator_test.rb:80
F
Failure:
ChannelGeneratorTest#test_channel_on_revoke [/Users/ttanimichi/ghq/github.com/ttanimichi/rails/railties/test/generators/channel_generator_test.rb:77]:
Expected file "app/assets/javascripts/cable.js" to exist, but does not
bin/test /Users/ttanimichi/ghq/github.com/ttanimichi/rails/railties/test/generators/channel_generator_test.rb:68
Finished in 0.064384s, 108.7227 runs/s, 481.4861 assertions/s.
7 runs, 31 assertions, 4 failures, 1 errors, 0 skips
```
After:
```
$ bin/test test/generators/channel_generator_test.rb
Run options: --seed 44857
.......
Finished in 0.060243s, 116.1961 runs/s, 697.1764 assertions/s.
7 runs, 42 assertions, 0 failures, 0 errors, 0 skips
```
* Fix shared generator tests.
* webpacker-default: Modify `ControllerGeneratorTest`
The JS assets generator was dropped. ref. 46215b1794
* Revert "Simpler import style". It's currently failing with an error of "TypeError: undefined is not an object (evaluating '__WEBPACK_IMPORTED_MODULE_2_activestorage___default.a.start')". Waiting for @javan to have a look.
This reverts commit 5d3ebb7105.
* require webpacker in test app
* Add webpacker without making the build hang/timeout. (#33640)
* use yarn workspaces to allow for installing unreleased packages and only generate js/bootsnap when required
* no longer need to have webpacker in env templates as webpacker moved this config to yml file
* Fix rubocop violation
* Got the test passing for the running scaffold
* update expected lines of code
* update middleware tests to account for webpacker
* disable js in plugins be default to get the tests passing (#34009)
* clear codeclimate report issues
* Anything newer than currently released is good
* Use Webpacker development version during development of Rails
* Edge should get development webpacker as well
* Add changelog entry for Webpacker change
Since Rails 6.0 will support Ruby 2.4.1 or higher
`# frozen_string_literal: true` magic comment is enough to make string object frozen.
This magic comment is enabled by `Style/FrozenStringLiteralComment` cop.
* Exclude these files not to auto correct false positive `Regexp#freeze`
- 'actionpack/lib/action_dispatch/journey/router/utils.rb'
- 'activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb'
It has been fixed by https://github.com/rubocop-hq/rubocop/pull/6333
Once the newer version of RuboCop released and available at Code Climate these exclude entries should be removed.
* Replace `String#freeze` with `String#-@` manually if explicit frozen string objects are required
- 'actionpack/test/controller/test_case_test.rb'
- 'activemodel/test/cases/type/string_test.rb'
- 'activesupport/lib/active_support/core_ext/string/strip.rb'
- 'activesupport/test/core_ext/string_ext_test.rb'
- 'railties/test/generators/actions_test.rb'
The hack was merged from action-cable-testing gem by mistake.
We don't need it in Rails 6.
(cherry picked from commit 92030ec4b4309835ed0e792229984a1f0a044cef)
ActionCable::Channel::TestCase provides an ability
to unit-test channel classes.
There are several reasons to write unit/functional cable tests:
- Access control (who has access to the channel? who can perform action and with which argument?
- Frontend-less applications have no system tests at all–and we still need a way to test channels logic.
See also #27191
This FIXME belongs to a code example that was imported from the
internet. As we aren't going to do anything about it, I prefer to remove
it so it stops from appearing on searches.
If `env` is duped or otherwise not the same as the original `env` that was
generated at the top of rack middleware, it is impossible for the server hijack
proc to update the right `env` instance. Therefore, capturing the return value
is more reliable. This is the recommendation of the rack SPEC.
Remove all `include ActiveSupport::Testing::MethodCallAssertions`
in actioncable's tests since we can do it only in `ActionCable::TestCase`
in order to prevent code duplication.
We use the same approach for other modules of Rails.
We have defined `ActionCable::TestCase` in `actioncable/test/test_helper.rb`
that we can use in order to prevent code duplication and build common
interface for actioncable's test.
* Global ignores at toplevel .gitignore
* Component-specific ignores in each toplevel directory
* Remove `actionview/test/tmp/.keep` for JRuby
```
rm actionview/test/tmp/ -fr
cd actionview/
bundle exec jruby -Itest test/template/digestor_test.rb
```
Related to #11743, #30392.
Closes#29978.
### Summary
This PR changes .rubocop.yml.
Regarding the code using `if ... else ... end`, I think the coding style
that Rails expects is as follows.
```ruby
var = if cond
a
else
b
end
```
However, the current .rubocop.yml setting does not offense for the
following code.
```ruby
var = if cond
a
else
b
end
```
I think that the above code expects offense to be warned.
Moreover, the layout by autocorrect is unnatural.
```ruby
var = if cond
a
else
b
end
```
This PR adds a setting to .rubocop.yml to make an offense warning and
autocorrect as expected by the coding style.
And this change also fixes `case ... when ... end` together.
Also this PR itself is an example that arranges the layout using
`rubocop -a`.
### Other Information
Autocorrect of `Lint/EndAlignment` cop is `false` by default.
https://github.com/bbatsov/rubocop/blob/v0.51.0/config/default.yml#L1443
This PR changes this value to `true`.
Also this PR has changed it together as it is necessary to enable
`Layout/ElseAlignment` cop to make this behavior.
pg-1.0.0 is just released and most Gemfiles don't restrict
it's version. But the version is checked when connecting to
the database, which leads to the following error:
Gem::LoadError: can't activate pg (~> 0.18), already activated pg-1.0.0
See also this pg issue:
https://bitbucket.org/ged/ruby-pg/issues/270/pg-100-x64-mingw32-rails-server-not-start
Preparation for pg-1.0 was done in commit f28a331023,
but the pg version constraint was not yet relaxed.
I often face the following error when running test/connection/client_socket_test.rb:
```
$ bin/test test/connection/client_socket_test.rb:38
Run options: --seed 44035
# Running:
F
Failure:
ActionCable::Connection::ClientSocketTest#test_delegate_socket_errors_to_on_error_handler
[/app/actioncable/test/connection/client_socket_test.rb:47]:
--- expected
+++ actual
@@ -1 +1 @@
-["foo"]
+["Broken pipe", "Broken pipe", "Broken pipe", "foo"]
```
It can be reproduced easily by applying the following patch:
```
diff --git a/actioncable/test/connection/client_socket_test.rb b/actioncable/test/connection/client_socket_test.rb
index 2051216010..6bb9f13ea7 100644
--- a/actioncable/test/connection/client_socket_test.rb
+++ b/actioncable/test/connection/client_socket_test.rb
@@ -34,7 +34,8 @@ def on_error(message)
@server.config.allowed_request_origins = %w( http://rubyonrails.com )
end
- test "delegate socket errors to on_error handler" do
+ 1000.times do |i|
+ test "delegate socket errors to on_error handler #{i}" do
run_in_eventmachine do
connection = open_connection
@@ -47,6 +48,7 @@ def on_error(message)
assert_equal %w[ foo ], connection.errors
end
end
+ end
test "closes hijacked i/o socket at shutdown" do
run_in_eventmachine do
```
The cause is writing io from different thread at the same time.
`connection.process` sends handshake message from [StreamEventLoop's thread][] whereas
`connection.handle_open` sends welcome message from current thread.
[StreamEventLoop's thread]: 067fc779c4/actioncable/lib/action_cable/connection/stream_event_loop.rb (L75)
Simplify our dev testing and CI story since we're also testing against
Redis for the Active Support cache store.
Directly test whether db, host, password, etc are passed through as
config instead of spinning up a Redis server with a password set on it.
* Use `gem 'redis', '~> 4.0'` for new app Gemfiles
* Loosen Action Cable redis-rb dep to `>= 3.3, < 5`
* Bump redis-namespace for looser Redis version dep
* Avoid using the underlying `redis.client` directly
* Use `Redis.new` instead of `Redis.connect`
* When the adapter is missing, raise an exception that points out config
typos and missing Gemfile entries. (We can assume that a non-builtin
adapter was used since these are always available.)
* When loading an adapter raises a LoadError, prefix its error message
to indicate that the adapter is likely missing an optional dependency.
If a frontend for some reason tries to unsubscribe from a non existing subscription, the following error is logged:
Could not execute command from ({"command"=>"unsubscribe", "identifier"=>"{\"channel\":\"SomeChannel\"}"}) [NoMethodError - undefined method `unsubscribe_from_channel' for nil:NilClass]
Instead, it will now properly log:
Could not execute command from ({"command"=>"unsubscribe", "identifier"=>"{\"channel\":\"SomeChannel\"}"}) [RuntimeError - Unable to find subscription with identifier: {"channel":"SomeChannel"}]
Don't use remove_method or remove_possible_method just before a new
definition: at best the purpose is unclear, and at worst it creates a
race condition.
Instead, prefer redefine_method when practical, and
silence_redefinition_of_method otherwise.
In some examples and guides we are recommending to use code like:
```ruby
verified_user = User.find_by(id: cookies.signed[:user_id])
```
My suggestion is to use instead:
```ruby
verified_user = User.find_by(id: cookies.encrypted[:user_id])
```
which invites users to prefer the "newer" encrypted cookies over the
"legacy" signed cookies.
- Adds RedisAdapterTest::AlternateConfiguration to account
for a relatively common alternative setup, as it’s used
as the first example in the
[Redis rubygem](https://github.com/redis/redis-rb#getting-started)
- Supplies original RedisAdapterTest with more complete
redis:// url format by adding a ‘userinfo’ (blank user),
so that it resembles the alternate configuration
- Supplies original EventedRedisAdapterTest with more complete
redis:// url as well
- Adds before_script to start redis-server with password as a daemon
and with explicit defaults copied from the default redis.conf
(Instead of using Travis' default init/upstart scripts for `redis` service)
* Allow a default value to be declared for class_attribute
* Convert to using class_attribute default rather than explicit setter
* Removed instance_accessor option by mistake
* False is a valid default value
* Documentation