@rubyonjets/ujs-compat
v1.2.0
Published
UJS compat library with @rails/ujs library for Ruby on Jets and API Gateway
Readme
@rubyonjets/ujs-compat
UJS compat library for Ruby on Jets and API Gateway.
Overview
The @rails/ujs package adds unobtrusive JavaScript scripting support for Rails. This is typically done with:
yarn add @rails/ujsCall rails ujs code:
app/javascript/packs/application.js
import Rails from "@rails/ujs"
Rails.start()How Rails UJS Works
- The
@rails/ujspackage registers click handlers to links with thedata-deleteattribute. Example:<a data-confirm="Are you sure?" rel="nofollow" data-method="delete" href="/posts/123">Destroy</a> - When the link is clicked,
@rails/ujscreates a hidden form and submits the request as aPOSTrequest with a hidden field_method=delete. - The Rack::MethodOverride middleware is used to then adjust
POSTtoDELETErequest appropriately.
Essentially, a DELETE http request is mimiced using a POST http request. It all happens transparently, so developers don't really notice the magic happening behind the scenes.
The Issue
Unfortunately API Gateway REST APIs require actual DELETE requests to the resource, not mimiced POST requests. Example:
DELETE /posts/123Sending a POST /posts/123 with a _method=delete will not work with API Gateway because the POST /posts/123 route points to the posts#update method API Gateway.
The Fix
To fix the issue, this javascript library adds click handlers that intercept @rails/ujs handlers and sends an AJAX DELETE request correctly.
Usage
yarn add @rubyonjets/ujs-compatAnd then add the Jets ujs-compat code below the Rails ujs code.
app/javascript/packs/application.js
import jquery from 'jquery'
window.$ = jquery
import Jets from "@rubyonjets/ujs-compat"
Jets.start()Dependencies
This package is dependencies on jquery. You should configure your own jquery.
Thoughts and Considerations
- Considered putting
POST /posts/123to theposts#deleteaction instead ofposts#update. But that feels like unexpected behavior. - Considered adding logic at the lambda handlers processing logic to convert
posts#updateactions with_method=deleteto callposts#delete. This will make the logic closer to whatRack::MethodOverridedoes but again feels a little bit confusing. - So went with javascript library to handle things earlier. An actual DELETE request is sent via AJAX to API Gateway.
- Open to suggestions and improvements.
