whatapalaver
whatapalaver

Reputation: 915

Rails Asset Pipeline removed - how to replicate rails-ujs helper methods

We are using Rails 5.2 at work and the asset pipeline has been removed. As a Rails newbie I keep coming across problems with methods not working as I expect.

For example the following link_to extract is processed as a GET request rather than DELETE and the confirmation is not shown.

<%=link_to 'Delete', admin_enhanced_object_media_item_path(@enhanced_object, media_item), method: :delete, data: { confirm: 'Are you sure?' }, class: 'btn btn--danger' %>

The following SO Q&A helped me understand that it related to a missing rails-ujs or jquery dependency and I was able to recover part of the functionality by replacing with button_to.

Rails' link_to method: GETing when it should DELETE

This sorted the method error but still doesn't show the confirmation alert.

I can see the missing methods in the Rails sourcecode (coffeescript) https://github.com/rails/rails/tree/master/actionview/app/assets/javascripts/rails-ujs/features

Given that I am not able to install rails-ujs am I able to replace these helper methods with vanilla JS in my application javascript files. Can anyone point me to an example of where this has been done or explained? I expect others work without the Rails asset pipeline but would like to maintain access to the unobtrusive javascript helpers listed here: https://edgeguides.rubyonrails.org/working_with_javascript_in_rails.html#rails-ujs-event-handlers

Upvotes: 0

Views: 371

Answers (1)

oneWorkingHeadphone
oneWorkingHeadphone

Reputation: 899

So this is quite old and a lot has changed since 5.2, but I found myself in an almost exact situation and I think it will become increasingly relevant as more and more people made different decisions with the asset pipeline changes.

The first thing to do is to add @rails/ujs to your bundler of choice (e.g. Webpack, vite, etc). At the time I'm writing this, there are two branches and the one mentioned in the comments is 2 major versions behind. This one seems to still be getting updates.

After that you will need to import it (likely into an entrypoint) and call it

import Rails from '@rails/ujs'
Rails.start()

This will allow you to use all the UJS methods (or in my case, fix all the broken ones after removing the asset pipeline). The package is 32kb (not zipped or minified). You could very likely cut that down by only grabbing the required methods from the github rep and copying them into your project. The actual functionality hasn't changed much over the last years.

Upvotes: 0

Related Questions