# TsRoutes for Rails [![Gem Version](https://badge.fury.io/rb/ts_routes.svg)](https://badge.fury.io/rb/ts_routes) [![Build Status](https://travis-ci.org/bitjourney/ts_routes-rails.svg?branch=master)](https://travis-ci.org/bitjourney/ts_routes-rails) This gem generates Rails URL helpers in TypeScript, which is synchronized to `routes.rb`. This is inspired by [js-routes](https://github.com/railsware/js-routes), which invents the great idea to export URL helpers to JavaScript. ## Usage In your `lib/tasks/ts_routes.rake`: ```ruby namespace :ts do TS_ROUTES_FILENAME = "javascripts/generated/routes.ts" desc "Generate #{TS_ROUTES_FILENAME}" task routes: :environment do Rails.logger.info("Generating #{TS_ROUTES_FILENAME}") source = TsRoutes.generate( exclude: [/admin/, /debug/], ) File.write(TS_ROUTES_FILENAME, source) end end ``` Then, execute `rake ts:routes` to generate `routes.ts` in your favorite path. And you can import it in TypeScript code: ```typescript import * as Routes from './generated/routes'; console.log(Routes.entriesPath({ page: 1, per: 20 })); // => /entries?page=1&per=20 console.log(Routes.entryPath(1)); // => /entries/1 ``` Generated URL helpers are almost compatible with Rails, but they are more strict: * You must pass required parameters to the helpers as non-named (i.e. normal) arguments * i.e. `Routes.entryPath(1)` for `/entries/:id` * `Routes.entryPath({ id })` is not allowed * Required parameters must not be `null` nor `undefined` * i.e. `Routes.entyPath(null)` does not compile * You must pass optional parameters as the last argument * i.e. `Routes.entriesPath({ page: 1, per: 2 })` ### Options Here are options for `TsRoutes.generate`:
name | description | default |
---|---|---|
routes | Rails routes to export | Rails.application.routes |
camel_case | naming style; doesn't change if false | true |
route_suffix | suffix for each route | "path" |
include | Array of Regexp patterns to include | nil |
exclude | Array of Regexp patterns to exclude | nil |
header | additional parts of generated files | "/* tslint:disable */" |