Javascript

Use Rails URL Helper with Javascript


Sometimes in some projects that I worked on I needed to use Rails URLs inside my JS, but I couldn't do this directly because, as you know, we need to integrate our scripts in some .erb file to be able to use them. So, to save you some time, you can use this gem.

Installing

gem "js-routes"

Setup

Require the js routes file in application.js or other manifest:

= require js-routes

Also in order to flush asset pipeline cache, sometimes you might need to run:

rake tmp:cache:clear

You have an advance setup mode adding config/initializers/jsroutes.rb to your initializers. To see all the available options you can modify, click here.

Usage

Configuration above will create a nice javascript file with Routes object that has all the Rails routes available:

Routes.users_path() // => "/users"
Routes.user_path(1) // => "/users/1"
Routes.user_path(1, {format: 'json'}) // => "/users/1.json"

This is how you can use a serialized object as a route function argument:

var google = {id: 1, name: "Google"};
Routes.company_path(google) // => "/companies/1"

Advanced Setup

In case you need multiple route files for different parts of your application, you have to create the files manually. If you have in your application an admin and an application namespace for example:

# app/assets/javascripts/admin/routes.js.erb
<%= JsRoutes.generate(namespace: "AdminRoutes", include: /admin/) %>

# app/assets/javascripts/admin.js.coffee
#= require admin/routes
# app/assets/javascripts/application/routes.js.erb
<%= JsRoutes.generate(namespace: "AppRoutes", exclude: /admin/) %>

# app/assets/javascripts/application.js.coffee
#= require application/routes

This gem is nice to have on any project, because it gives you the possibility to use the Rails URL helpers on your fronted, you don't need to work anymore on .erb files to be able to use Rails paths inside your js scripts, making it extremely helpful.

I hope this helps you and saves you time and effort. Remember to contribute on the gem if you have any ideas to improve it, or even better: create your own gems to solve other problems and tell us about them!

Post any questions or comments below, we're happy to read you.

Cheers!

Beginner
Administrate review
Development
Angular 2 Overview
Beginner
ReactJS: Loops in JSX