Home > Blockchain >  Rails: run controller action from actioncable
Rails: run controller action from actioncable

Time:08-19

I have a rails SPA using react. I've recently started using actioncable. Since websockets have lower overhead than normal http connections I'd like to allow the javascript client to make requests over the websockets created by actioncable but I don't want to duplicate all my code from my controllers.

Is there a good way to trigger a controller from actioncable (eg set the params and current_user)? I could then just implement a method that switches whether or not it sends the json response via actioncable or by the usual render option (I don't have any views). I'm guessing this is a common need so I'm probably just not searching for the right thing.

CodePudding user response:

No

The way you interact with Rails controllers is by sending HTTP requests to your application. Which would defeat the entire purpose of the excersize.

Rails controllers aren't really just simple classes that are easy to extract into isolation. They are actually fully fledged Rack applications that live in a Rack middleware stack. Their entire purpose is to take an incoming HTTP request from the router and provide a response which is passed back up the stack.

While you can fake a request with Rack::MockRequest it starts to melt down as soon as your application depends on the other middleware in the stack. For example Devise depends on the Warden middleware - and the answer is more stubbing and mocking. This very flawed approach was used in the deprechiated controller tests - using it in production would be crazy.

I'm guessing this is a common need so I'm probably just not searching for the right thing.

It is. And the answer is quite simple. If you need to reuse code outside of the controller don't put it in a controller.

There are tons of different options such as mixins, service objects, ActiveJob etc.

  • Related