Generate a ES6 module that contains Rails routes.
This gem provides "js:routes" rake task. It generates a ES6 requirable module which exports url helper functions defined in your Rails application.
Suppose the app has following routes:
# == Route Map
#
# Prefix Verb URI Pattern Controller#Action
# articles GET /articles(.:format) articles#index
# POST /articles(.:format) articles#create
# new_article GET /articles/new(.:format) articles#new
# edit_article GET /articles/:id/edit(.:format) articles#edit
# article GET /articles/:id(.:format) articles#show
# PATCH /articles/:id(.:format) articles#update
# PUT /articles/:id(.:format) articles#update
# DELETE /articles/:id(.:format) articles#destroy
Rails.application.routes.draw do
resources :articles
end
then rake js:routes
generates "app/assets/javascripts/rails-routes.js" as:
// Don't edit manually. `rake js:routes` generates this file.
export function article_path(params) { return '/articles/' + params.id + ''; }
export function articles_path(params) { return '/articles'; }
export function edit_article_path(params) { return '/articles/' + params.id + '/edit'; }
export function new_article_path(params) { return '/articles/new'; }
railsware/js-routes spreads url helpers via global variable.
This gem uses ES6 modules.
- Rails >= 3.2
Generate routes file.
rake js:routes
JSRailsRoutes supports several parameters:
Name | Type | Description | Default |
---|---|---|---|
includes |
Regexp |
routes match to the regexp are included | /.*/ |
excludes |
Regexp |
routes match to the regexp are excluded | /^$/ |
path |
String |
JS file path | Rails.root.join("app", "assets", "javascripts", "rails-routes.js") |
You can configure via JSRailsRoutes.configure
.
# Rakefile
JSRailsRoutes.configure do |c|
c.excludes = %r{^/(rails|sidekiq)}
c.path = Rails.root.join('path', 'to', 'rails-routes.js')
end
Now rake js:routes
ignores paths starting with "/rails" or "/sidekiq".
You can override the coniguration via command line parameters:
rake js:routes excludes='^/rails'
The command still ignores "/rails" but includes "/sidekiq".
Your Rails Gemfile:
gem 'js_rails_routes', group: :development
mizchi wrote "js:routes" task with referencing mtrpcic/js-routes.
yuku-t refactored and improved the mizchi's script and published to rubygems.