Code Generation ๐ค
Whenever you add a new route and refresh the page, the Rails reloader will kick in and generate path helpers for any of the exported routes.
If you are not running the development server, you can run a rake task to generate path helpers:
bin/rake js_from_routes:generate
By default, it will generate one file per controller, with one helper per exported action:
// app/javascript/api/VideoClipsApi.ts
import { definePathHelper } from '@js-from-routes/client'
export default {
download: definePathHelper('get', '/video_clips/:id/download'),
update: definePathHelper('patch', '/video_clips/:id'),
}
Notice how the HTTP verb becomes an implementation detail.
Changing the verb in routes.rb does not require updating your client code!
Customizing the Generated Code ๐
You can customize the code produced by the default template, or use your own template.
The following code examples assume that you are configuring JS From Routes in an initializer.
Using a different client
You can use any of the provided client libraries by using client_library:
config.client_library = '@js-from-routes/axios'
Using your own code
You can also use client_library to target your own code when generating path helpers:
config.client_library = '~/MyPathHelpers'
As a result, the default template will generate:
// app/javascript/api/VideoClipsApi.ts
import { definePathHelper } from '~/MyPathHelpers'
export default {
...
}
Using a different template
If you need to generate helpers in a different way, or want do something entirely different with exported routes, you can configure template_path to use your own template:
config.template_path = Rails.root.join('custom_js_from_routes.js.erb')
A routes variable will be available in the template, with the exported routes for a controller.
Each route exposes properties such as verb and path, check the source code for details.
See this pull request to get a sense of how flexible it can be.
Caching ๐ฆ
Generated files are only written when their content changed, so repeated runs leave untouched files alone and their modification times stay stable for file watchers.
In development, helpers are generated when the app boots, and afterwards only when one of the files Rails loads routes from (or one of the templates) has changed, using the same file watcher Rails uses to reload routes.
The rake task always regenerates everything:
bin/rake js_from_routes:generate