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 ๐ฆ
Code generation is skipped when routes have not changed.
This is achieved by adding a header to generated files:
// JsFromRoutes CacheKey 12d79db32ed146448798751582013757
//
// DO NOT MODIFY: This file was automatically generated by JsFromRoutes.
If for some reason you want to force regeneration, you can run:
JS_FROM_ROUTES_FORCE=true bin/rake js_from_routes:generate