• Stars
    star
    1,592
  • Rank 28,203 (Top 0.6 %)
  • Language
    Ruby
  • License
    MIT License
  • Created over 12 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Brings Rails named routes to javascript

JsRoutes

CI

Generates javascript file that defines all Rails named routes as javascript helpers

Intallation

Your Rails Gemfile:

gem "js-routes"

Setup

There are several possible ways to setup JsRoutes:

  • Quick and easy - Recommended
    • Uses Rack Middleware to automatically update routes locally
    • Automatically generates routes files on javascript build
    • Works great for a simple Rails application
  • Advanced Setup
    • Allows very custom setups
    • Automatic updates need to be customized
  • Webpacker ERB Loader - Legacy
    • Requires ESM module system (the default)
    • Doesn't support typescript definitions
  • Sprockets - Legacy
    • Deprecated and not recommended for modern apps

Quick Start

Setup Rack Middleware to automatically generate and maintain routes.js file and corresponding Typescript definitions routes.d.ts:

Use a Generator

Run a command:

rails generate js_routes:middleware

Setup Manually

Add the following to config/environments/development.rb:

  config.middleware.use(JsRoutes::Middleware)

Use it in any JS file:

import {post_path} from '../routes';

alert(post_path(1))

Upgrade js building process to update js-routes files in Rakefile:

task "javascript:build" => "js:routes:typescript"
# For setups without jsbundling-rails
task "assets:precompile" => "js:routes:typescript"

Add js-routes files to .gitignore:

/app/javascript/routes.js
/app/javascript/routes.d.ts

Webpacker ERB loader

IMPORTANT: the setup doesn't support IDE autocompletion with Typescript

Use a Generator

Run a command:

./bin/rails generate js_routes:webpacker

Setup manually

The routes files can be automatically updated without rake task being called manually. It requires rails-erb-loader npm package to work.

Add erb loader to webpacker:

yarn add rails-erb-loader
rm -f app/javascript/routes.js # delete static file if any

Create webpack ERB config config/webpack/loaders/erb.js:

module.exports = {
  module: {
    rules: [
      {
        test: /\.erb$/,
        enforce: 'pre',
        loader: 'rails-erb-loader'
      },
    ]
  }
};

Enable erb extension in config/webpack/environment.js:

const erb = require('./loaders/erb')
environment.loaders.append('erb', erb)

Create routes file app/javascript/routes.js.erb:

<%= JsRoutes.generate() %>

Use routes wherever you need them:

import {post_path} from 'routes.js.erb';

alert(post_path(2));

Advanced Setup

IMPORTANT: that this setup requires the JS routes file to be updates manually

Routes file can be generated with a rake task:

rake js:routes 
# OR for typescript support
rake js:routes:typescript

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

IMPORTANT: Requires Webpacker ERB Loader setup.

// app/javascript/admin/routes.js.erb
<%= JsRoutes.generate(include: /admin/) %>
// app/javascript/customer/routes.js.erb
<%= JsRoutes.generate(exclude: /admin/) %>

You can manipulate the generated helper manually by injecting ruby into javascript:

export const routes = <%= JsRoutes.generate(module_type: nil, namespace: nil) %>

If you want to generate the routes files manually with custom options, you can use JsRoutes.generate!:

path = Rails.root.join("app/javascript")

JsRoutes.generate!(
  "#{path}/app_routes.js", exclude: [/^admin_/, /^api_/]
)
JsRoutes.generate!(
"#{path}/adm_routes.js", include: /^admin_/
)
JsRoutes.generate!(
  "#{path}/api_routes.js", include: /^api_/, default_url_options: {format: "json"}
)

Typescript Definitions

JsRoutes has typescript support out of the box.

Restrictions:

  • Only available if module_type is set to ESM (strongly recommended and default).
  • Webpacker Automatic Updates are not available because typescript compiler can not be configured to understand .erb extensions.

For the basic setup of typscript definitions see Quick Start setup. More advanced setup would involve calling manually:

JsRoutes.definitions! # to output to file
# or 
JsRoutes.definitions # to output to string

Even more advanced setups can be achieved by setting module_type to DTS inside configuration which will cause any JsRoutes instance to generate defintions instead of routes themselves.

Sprockets (Deprecated)

If you are using Sprockets you may configure js-routes in the following way.

Setup the initializer (e.g. config/initializers/js_routes.rb):

JsRoutes.setup do |config|
  config.module_type = nil
  config.namespace = 'Routes'
end

Require JsRoutes in app/assets/javascripts/application.js or other bundle

//= require js-routes

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

rake tmp:cache:clear

This cache is not flushed on server restart in development environment.

Important: If routes.js file is not updated after some configuration change you need to run this rake task again.

Configuration

You can configure JsRoutes in two main ways. Either with an initializer (e.g. config/initializers/js_routes.rb):

JsRoutes.setup do |config|
  config.option = value
end

Or dynamically in JavaScript, although only Formatter Options are supported:

import {configure, config} from 'routes'

configure({
  option: value
});
config(); // current config

Available Options

Generator Options

Options to configure JavaScript file generator. These options are only available in Ruby context but not JavaScript.

  • module_type - JavaScript module type for generated code. Article
    • Options: ESM, UMD, CJS, AMD, DTS, nil.
    • Default: ESM
    • nil option can be used in case you don't want generated code to export anything.
  • documentation - specifies if each route should be annotated with JSDoc comment
    • Default: true
  • exclude - Array of regexps to exclude from routes.
    • Default: []
    • The regexp applies only to the name before the _path suffix, eg: you want to match exactly settings_path, the regexp should be /^settings$/
  • include - Array of regexps to include in routes.
    • Default: []
    • The regexp applies only to the name before the _path suffix, eg: you want to match exactly settings_path, the regexp should be /^settings$/
  • namespace - global object used to access routes.
    • Only available if module_type option is set to nil.
    • Supports nested namespace like MyProject.routes
    • Default: nil
  • camel_case - specifies if route helpers should be generated in camel case instead of underscore case.
    • Default: false
  • url_links - specifies if *_url helpers should be generated (in addition to the default *_path helpers).
    • Default: false
    • Note: generated URLs will first use the protocol, host, and port options specified in the route definition. Otherwise, the URL will be based on the option specified in the default_url_options config. If no default option has been set, then the URL will fallback to the current URL based on window.location.
  • compact - Remove _path suffix in path routes(*_url routes stay untouched if they were enabled)
    • Default: false
    • Sample route call when option is set to true: users() // => /users
  • application - a key to specify which rails engine you want to generate routes too.
    • This option allows to only generate routes for a specific rails engine, that is mounted into routes instead of all Rails app routes
    • Default: Rails.application
  • file - a file location where generated routes are stored
    • Default: app/javascript/routes.js if setup with Webpacker, otherwise app/assets/javascripts/routes.js if setup with Sprockets.

Formatter Options

Options to configure routes formatting. These options are available both in Ruby and JavaScript context.

  • default_url_options - default parameters used when generating URLs
    • Example: {format: "json", trailing_slash: true, protocol: "https", subdomain: "api", host: "example.com", port: 3000}
    • Default: {}
  • prefix - string that will prepend any generated URL. Usually used when app URL root includes a path component.
    • Example: /rails-app
    • Default: Rails.application.config.relative_url_root
  • serializer - a JS function that serializes a Javascript Hash object into URL paramters like {a: 1, b: 2} => "a=1&b=2".
    • Default: nil. Uses built-in serializer compatible with Rails
    • Example: jQuery.param - use jQuery's serializer algorithm. You can attach serialize function from your favorite AJAX framework.
    • Example: function (object) { ... } - use completely custom serializer of your application.
  • special_options_key - a special key that helps JsRoutes to destinguish serialized model from options hash
    • This option exists because JS doesn't provide a difference between an object and a hash
    • Default: _options

Usage

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

import {
  user_path, user_project_path, company_path
} as Routes from 'routes';

users_path() 
  // => "/users"

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

user_path(1, {anchor: 'profile'}) 
  // => "/users/1#profile"

new_user_project_path(1, {format: 'json'}) 
  // => "/users/1/projects/new.json"

user_project_path(1,2, {q: 'hello', custom: true}) 
  // => "/users/1/projects/2?q=hello&custom=true"

user_project_path(1,2, {hello: ['world', 'mars']}) 
  // => "/users/1/projects/2?hello%5B%5D=world&hello%5B%5D=mars"

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

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

In order to make routes helpers available globally:

import * as Routes from '../routes';
jQuery.extend(window, Routes)

Get spec of routes and required params

Possible to get spec of route by function toString:

import {user_path, users_path}  from '../routes'

users_path.toString() // => "/users(.:format)"
user_path.toString() // => "/users/:id(.:format)"

Route function also contain method requiredParams inside which returns required param names array:

users_path.requiredParams() // => []
user_path.requiredParams() // => ['id']

Rails Compatibility

JsRoutes tries to replicate the Rails routing API as closely as possible. If you find any incompatibilities (outside of what is described below), please open an issue.

Object and Hash distinction issue

Sometimes the destinction between JS Hash and Object can not be found by JsRoutes. In this case you would need to pass a special key to help:

import {company_project_path} from '../routes'

company_project_path({company_id: 1, id: 2}) // => Not enough parameters
company_project_path({company_id: 1, id: 2, _options: true}) // => "/companies/1/projects/2"

What about security?

JsRoutes itself does not have security holes. It makes URLs without access protection more reachable by potential attacker. If that is an issue for you, you may use one of the following solutions:

ESM Tree shaking

Make sure module_type is set to ESM (the default). Modern JS bundlers like Webpack can statically determine which ESM exports are used, and remove the unused exports to reduce bundle size. This is known as Tree Shaking.

JS files can use named imports to import only required routes into the file, like:

import {
  inbox_path,
  inboxes_path,
  inbox_message_path,
  inbox_attachment_path,
  user_path,
} from '../routes'

JS files can also use star imports (import * as) for tree shaking, as long as only explicit property accesses are used.

import * as routes from '../routes';

console.log(routes.inbox_path); // OK, only `inbox_path` is included in the bundle

console.log(Object.keys(routes)); // forces bundler to include all exports, breaking tree shaking

Exclude option

Split your routes into multiple files related to each section of your website like:

// admin-routes.js.erb
<%= JsRoutes.generate(include: /^admin_/) %>
// app-routes.js.erb
<%= JsRoutes.generate(exclude: /^admin_/) %>

Advantages over alternatives

There are some alternatives available. Most of them has only basic feature and don't reach the level of quality I accept. Advantages of this one are:

  • Rails 4,5,6 support
  • ESM Tree shaking support
  • Rich options set
  • Full rails compatibility
  • Support Rails #to_param convention for seo optimized paths
  • Well tested

Thanks to contributors

Have fun

License

FOSSA Status

More Repositories

1

upterm

A terminal emulator for the 21st century.
TypeScript
19,318
star
2

Sleipnir

BDD-style framework for Swift
Swift
847
star
3

bozon

🛠 Command line tool for building, testing and publishing modern Electron applications
JavaScript
757
star
4

BloodMagic

BloodMagic is a framework, which gives you a way to create custom property attributes.
Objective-C
317
star
5

global

"Global" provides accessor methods for your configuration data
Ruby
282
star
6

applepie

Semantic and Modular CSS Toolkit
CSS
280
star
7

rack_session_access

Rack middleware that provides access to rack.session environment
Ruby
259
star
8

caphub

Generate centralized capistrano skeleton for multiple deployment
Ruby
230
star
9

smt_rails

Shared mustache templates for rails 3.
Ruby
110
star
10

http_logger

Log your http api calls just like SQL queries
Ruby
106
star
11

rspec-example_steps

Given/When/Then steps for RSpec examples
Ruby
85
star
12

sht_rails

Shared handlebars templates for Rails 3
Ruby
76
star
13

actionmailer-balancer

A Ruby gem to send your ActionMailer mail through one of several delivery methods, selected by weight.
Ruby
76
star
14

capistrano-multiconfig

Capistrano extension that allows to use multiple configurations
Ruby
66
star
15

passenger-initscript

Manage multiple passenger instances
Shell
54
star
16

skypekit

Ruby FFI interface to libskypekit C library
Ruby
47
star
17

newrelic_platform_plugins

Ruby
41
star
18

piro

PiRo - it's Rocket for you Pivotal Tracker account
CoffeeScript
40
star
19

zero_deploy

Significantly improves typical deployment speed
Ruby
40
star
20

mailtrap-nodejs

Official mailtrap.io Node.js client
TypeScript
35
star
21

capistrano-calendar

Deployment event creation on (google) calendar service
Ruby
29
star
22

capistrano-patch

Capistrano patch recipes
Ruby
29
star
23

scaffy.railsware.com

Approach for writing and organizing your CSS for large-scale projects
JavaScript
29
star
24

mailtrap-php

The official mailtrap.io PHP client
PHP
20
star
25

libskypekit

Thread-safe C library with synchronous API using asynchronous C++ SkypeKit SDK
C
19
star
26

backfiller

The backfill machine for database records with null columns
Ruby
16
star
27

capistrano-ci

Ruby
16
star
28

indeed

Indeed.com integration plugin
Ruby
16
star
29

mailtrap-ruby

The official mailtrap.io Ruby client
Ruby
15
star
30

RBRouteBuilder

Build routes without strings and headache
C++
15
star
31

sprinkle_recipes

Railsware sprinkle recipes
Ruby
14
star
32

capistrano-uptodate

Capistrano extension that automatically check local repository with remote repository
Ruby
14
star
33

activeresource-persistent

HTTP persistent connection support for ActiveResource
Ruby
11
star
34

haproxy-slow-fast-request-balancer

HAProxy as "Slow-Fast" Request Balancer
10
star
35

generator-electron-app

Yeoman generator to scaffold Electron app
JavaScript
9
star
36

scout-app-plugins

Useful plugins for the Scout Server Monitoring and Reporting Tool
Ruby
9
star
37

mailtrap-python

Official mailtrap.io Python client
Python
8
star
38

web-bundler

WebResourceBundler bundling particular resource (css or js) in one file. Encoding images in base64 and putting then in css directly.
Ruby
8
star
39

gcal4ruby

Author: Mike Reich. GCal4Ruby is a Ruby Gem that can be used to interact with the current version of the Google Calendar API. GCal4Ruby provides the following features: Create and edit calendar events, Add and invite users to events, Set reminders, Make recurring events.
Ruby
8
star
40

db_structure_ext

Extended rails tasks db:structure:dump/load that supports mysql views/triggers/routines
Ruby
7
star
41

github-actions

A collection of GitHub actions used at Railsware
JavaScript
7
star
42

jdt

JSON Driven Templates
JavaScript
7
star
43

shelltoad

Command line interface for airbrake (http://airbrake.io/)
Ruby
7
star
44

i18n_template

18nTemplate is made to extract phrases and translate html/xhtml/xml document or erb templates
Ruby
6
star
45

capistrano-changelog

Chagelog based on Git commits with a Pivotal story tags
Ruby
5
star
46

go-global

Golang configuration reader for AWS Parameter Store and more
Go
4
star
47

chain_flow

Helps to refactor complex data processing
Ruby
4
star
48

fakes3server

Fake AWS S3 server for local development
Go
4
star
49

jOverlay

Overlay jQuery plugin
JavaScript
4
star
50

dev_vagrant_box

Vagrant box for development (ruby, rails)
4
star
51

yaml_settings

YamlSettings is a simple configuration / settings solution that uses an ERB enabled YAML file.
Ruby
3
star
52

multiversion

Use Bundler and RVM to test your library against different gem versions and/or ruby versions.
Ruby
3
star
53

ui-library

UI Library Template
CSS
2
star
54

clicktale

Clicktale rails plugin by Railsware
Ruby
2
star
55

railsware.github.com

CSS
2
star
56

capybara-feature_helpers

Ruby
2
star
57

backbone_showcase

Ruby
2
star
58

em-rest-client

EventMachine::HttpRequest adapter for HTTP REST client
Ruby
2
star
59

newrelic_em_http

New Relic EM::HTTP instrumentation
Ruby
2
star
60

capistrano-strategy-copy-partial

Capistrano deploy strategy to transfer subdirectory of repository
Ruby
2
star
61

hbase-driver

Small and handy Ruby driver for HBase
Ruby
2
star
62

acme-aws-lambda

AWS Lambda function to generate Letsencrypt certificates (need AWS S3 and Route53)
Ruby
2
star
63

showroom

Ruby
2
star
64

email_templates

HTML
2
star
65

rest_facebook

Lightweight ruby facebook client
Ruby
1
star
66

plunger

Code review tool
Python
1
star
67

cat-aws-ssm-param

Go
1
star
68

rw-study-wishlist

Ruby
1
star
69

template

Rails project template
JavaScript
1
star
70

chef-rwci

Ruby
1
star
71

office-iot

Objective-C
1
star
72

simple_on_couch

Example of CouchApp application for RW articles
JavaScript
1
star
73

gdoc_mapreduce

JavaScript
1
star
74

scaffy

Repo moved to scaffy.railsware.com
1
star
75

highrise_assist

Assist for 37signals' highrise
Ruby
1
star
76

sidekiq_unique_retries

Unique Retries for Sidekiq
Ruby
1
star
77

skypekit_pure

Skypekit on pure ruby
Ruby
1
star
78

aws-ecs-tools

Ruby
1
star
79

capybara_mock

CapybaraMock
Ruby
1
star
80

handlebars_assets_i18n

Very simple handlebars_assets internationalization for .hamlbars and .slimbars templates
Ruby
1
star
81

paypal-sdk-http-adapters

HTTP Adapters for PayPal SDK
Ruby
1
star
82

harvest_report

Harvert reports for non-admin harvest users
Ruby
1
star
83

rest-client-adapters

RestClient Adapters
Ruby
1
star
84

versioned_item

Ruby
1
star
85

cordova-baxi-plugin

Java
1
star
86

column_info_reset

Reset ActiveRecord column info when unknown column exception occurs
Ruby
1
star
87

gdoc_pivotal

Gdoc updater for pivotal
JavaScript
1
star
88

mailtrap-examples

Mailtrap repo examples
HTML
1
star
89

mailtrap-elixir

The official mailtrap.io Elixir client
Elixir
1
star