js-routes 1.4.9 → 2.0.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: bcc3b758ce05ed0444162cda94d5442b811a582330ea4418cf816763e4e482b0
4
- data.tar.gz: 3bfd8cc484ba00a6cd7ff0e5ffb90c3f3ec11c1d7aa9171572e93bc66b1cab42
3
+ metadata.gz: 86ed2a6e4f90ea3c7bbc91836148b23121acbb21c59e4b26e55f0925a2d37fce
4
+ data.tar.gz: 485241d5aa3e009545a78113c49e2781be677cb4ddfe91286329f325f8a6b9dc
5
5
  SHA512:
6
- metadata.gz: a51ee9fc01642e16287b648085debd75749b983b2602a2407068cc7159cd302f8b04bd065b1ea28f7314cd19ae60e535cede86af4e7d7073648ffe2b3222d006
7
- data.tar.gz: a979758f820232a129f9befd597a248511c76b05eab8aae5b62b56bf31a2f94580b889371aa52e584aac0fdfd5802a03f1632eaee65713b2438d98e29265846b
6
+ metadata.gz: 75844cdc35fc7cbf506fdd40eb00bc002c8bdc35397607943d28519572ae63f3f374cd249c4f50c218a979ffbbafe3938d5d2de0d1f03505e00549b9483a7ae6
7
+ data.tar.gz: ffb6920c23e81c18cc4c6e1476ae61f60801973e93583cd481ef6cd9f45171005de01124cc62aefc7862c2451cdbde31787efeeb8d2fb2e9dab223b1f5964230
data/.eslintrc.js ADDED
@@ -0,0 +1,15 @@
1
+ module.exports = {
2
+ root: true,
3
+ extends: [
4
+ 'eslint:recommended',
5
+ 'plugin:@typescript-eslint/eslint-recommended',
6
+ 'plugin:@typescript-eslint/recommended',
7
+ 'prettier/@typescript-eslint',
8
+ ],
9
+ parser: '@typescript-eslint/parser',
10
+ plugins: ['@typescript-eslint'],
11
+ rules: {
12
+ '@typescript-eslint/ban-types': 'off',
13
+ '@typescript-eslint/no-explicit-any': 'off'
14
+ },
15
+ };
data/.gitignore CHANGED
@@ -15,6 +15,8 @@ log
15
15
  # jeweler generated
16
16
  pkg
17
17
 
18
+ node_modules
19
+
18
20
  # Have editor/IDE/OS specific files you need to ignore? Consider using a global gitignore:
19
21
  #
20
22
  # * Create a file at ~/.gitignore
@@ -58,3 +60,5 @@ gemfiles/*.lock
58
60
  /spec/dummy/app/assets/javascripts/routes.js
59
61
  /spec/dummy/logs
60
62
  /spec/dummy/tmp
63
+ node_modules
64
+
data/.nvmrc ADDED
@@ -0,0 +1 @@
1
+ 14
data/.travis.yml CHANGED
@@ -5,7 +5,6 @@ before_install:
5
5
  - gem install bundler # need for jruby and ruby-head
6
6
 
7
7
  rvm:
8
- - 2.3.1
9
8
  - 2.4.1
10
9
  - 2.5.3
11
10
  - 2.6.0
@@ -22,6 +21,8 @@ gemfile:
22
21
  - gemfiles/rails50_sprockets_3.gemfile
23
22
  - gemfiles/rails51_sprockets_3.gemfile
24
23
  - gemfiles/rails52_sprockets_3.gemfile
24
+ env:
25
+ TRAVIS_CI: true
25
26
 
26
27
  sudo: false
27
28
  dist: xenial
data/CHANGELOG.md CHANGED
@@ -1,5 +1,34 @@
1
1
  ## master
2
2
 
3
+ ## v2.0.0
4
+
5
+ Version 2.0 has some breaking changes.
6
+ See [UPGRADE TO 2.0](./VERSION_2_UPGRADE.md) for guidance.
7
+
8
+ * `module_type` option support
9
+ * `documentation` option spport
10
+ * Migrated implementation to typescript
11
+ * ESM tree shaking support
12
+ * Support camel case `toParam` version of `to_param` property
13
+
14
+ ## v1.4.14
15
+
16
+ * Fix compatibility with UMD modules #237 [Comment](https://github.com/railsware/js-routes/issues/237#issuecomment-752754679)
17
+
18
+ ## v1.4.13
19
+
20
+ * Improve compatibility with node environment #269.
21
+ * Change default file location configuration to Webpacker if both Webpacker and Sprockets are loaded
22
+
23
+ ## v1.4.11
24
+
25
+ * Use app/javascript/routes.js as a default file location if app/javascript directory exists
26
+ * Add `default` export for better experience when used as es6 module
27
+
28
+ ## v1.4.10
29
+
30
+ * Require engine only when sprockets is loaded #257.
31
+
3
32
  ## v1.4.9
4
33
 
5
34
  * Allow to specify null namespace and receive routes as an object without assigning it anywhere #247
data/Readme.md CHANGED
@@ -4,6 +4,8 @@
4
4
 
5
5
  Generates javascript file that defines all Rails named routes as javascript helpers
6
6
 
7
+ [UPGRADE TO 2.0](./VERSION_2_UPGRADE.md)
8
+
7
9
  ## Intallation
8
10
 
9
11
  Your Rails Gemfile:
@@ -12,9 +14,97 @@ Your Rails Gemfile:
12
14
  gem "js-routes"
13
15
  ```
14
16
 
15
- ### Basic Setup
17
+ ## Setup
18
+
19
+ ### Quick Start
20
+
21
+ Run:
22
+
23
+ ```
24
+ rake js:routes
25
+ ```
26
+
27
+ Make routes available globally in `app/javascript/packs/application.js`:
28
+
29
+ ``` javascript
30
+ import * as Routes from 'routes';
31
+ window.Routes = Routes;
32
+ ```
33
+
34
+ Individual routes can be imported using:
35
+
36
+ ``` javascript
37
+ import {edit_post_path} from 'routes';
38
+ console.log(edit_post_path(1))
39
+ ```
40
+
41
+ **Note**: that this setup requires `rake js:routes` to be run each time routes file is updated.
42
+
43
+ <div id='webpacker'></div>
44
+
45
+ #### Webpacker + automatic updates
46
+
47
+
48
+ This setup can automatically update your routes without `rake js:routes` being called manually.
49
+ It requires [rails-erb-loader](https://github.com/usabilityhub/rails-erb-loader) npm package to work.
50
+
51
+ Add `erb` loader to webpacker:
52
+
53
+ ``` sh
54
+ yarn add rails-erb-loader
55
+ rm -f app/javascript/routes.js # delete static file if any
56
+ ```
57
+
58
+ Create webpack ERB config `config/webpack/loaders/erb.js`:
59
+
60
+ ``` javascript
61
+ module.exports = {
62
+ test: /\.js\.erb$/,
63
+ enforce: 'pre',
64
+ exclude: /node_modules/,
65
+ use: [{
66
+ loader: 'rails-erb-loader',
67
+ options: {
68
+ runner: (/^win/.test(process.platform) ? 'ruby ' : '') + 'bin/rails runner'
69
+ }
70
+ }]
71
+ }
72
+ ```
73
+
74
+ Enable `erb` extension in `config/webpacker/environment.js`:
16
75
 
17
- Require JsRoutes in `application.js` or other bundle
76
+ ``` javascript
77
+ const erb = require('./loaders/erb')
78
+ environment.loaders.append('erb', erb)
79
+ ```
80
+
81
+ Create routes file `app/javascript/routes.js.erb`:
82
+
83
+ ``` erb
84
+ <%= JsRoutes.generate() %>
85
+ ```
86
+
87
+ Use routes wherever you need them `app/javascript/packs/application.js`:
88
+
89
+ ``` javascript
90
+ import * as Routes from 'routes.js.erb';
91
+ window.Routes = Routes;
92
+ ```
93
+
94
+ #### Sprockets (Deprecated)
95
+
96
+ If you are using [Sprockets](https://github.com/rails/sprockets-rails) you may configure js-routes in the following way.
97
+
98
+ Setup the initializer (e.g. `config/initializers/js_routes.rb`):
99
+
100
+ ``` ruby
101
+ JsRoutes.setup do |config|
102
+ config.module_type = nil
103
+ config.namespace = 'Routes'
104
+ end
105
+ ```
106
+
107
+ Require JsRoutes in `app/assets/javascripts/application.js` or other bundle
18
108
 
19
109
  ``` js
20
110
  //= require js-routes
@@ -32,7 +122,7 @@ This cache is not flushed on server restart in development environment.
32
122
 
33
123
  ### Configuration
34
124
 
35
- You can configure JsRoutes in two main ways. Either with an initializer (e.g. `config/initializers/jsroutes.rb`):
125
+ You can configure JsRoutes in two main ways. Either with an initializer (e.g. `config/initializers/js_routes.rb`):
36
126
 
37
127
  ``` ruby
38
128
  JsRoutes.setup do |config|
@@ -40,107 +130,107 @@ JsRoutes.setup do |config|
40
130
  end
41
131
  ```
42
132
 
43
- Or dynamically in JavaScript, although not all configuration options are supported:
133
+ Or dynamically in JavaScript, although only [Formatter Options](#formatter-options) are supported (see below)
44
134
 
45
135
  ``` js
136
+ import * as Routes from 'routes'
46
137
  Routes.configure({
47
138
  option: value
48
139
  });
49
140
  Routes.config(); // current config
50
141
  ```
51
142
 
52
- Available options:
143
+ #### Available Options
53
144
 
54
- * `default_url_options` - default parameters used when generating URLs
55
- * Option is configurable at JS level with `Routes.configure()`
56
- * Example: {:format => "json", :trailing\_slash => true, :protocol => "https", :subdomain => "api", :host => "example.com", :port => 3000}
57
- * Default: {}
145
+ ##### Generator Options
146
+
147
+ Options to configure JavaScript file generator. These options are only available in Ruby context but not JavaScript.
148
+
149
+ * `module_type` - JavaScript module type for generated code. [Article](https://dev.to/iggredible/what-the-heck-are-cjs-amd-umd-and-esm-ikm)
150
+ * Options: `ESM`, `UMD`, `CJS`, `AMD`, `nil`.
151
+ * Default: `ESM`
152
+ * `nil` option can be used in case you don't want generated code to export anything.
153
+ * `documentation` - specifies if each route should be annotated with [JSDoc](https://jsdoc.app/) comment
154
+ * Default: `true`
58
155
  * `exclude` - Array of regexps to exclude from routes.
59
- * Default: []
156
+ * Default: `[]`
60
157
  * The regexp applies only to the name before the `_path` suffix, eg: you want to match exactly `settings_path`, the regexp should be `/^settings$/`
61
158
  * `include` - Array of regexps to include in routes.
62
- * Default: []
159
+ * Default: `[]`
63
160
  * The regexp applies only to the name before the `_path` suffix, eg: you want to match exactly `settings_path`, the regexp should be `/^settings$/`
64
161
  * `namespace` - global object used to access routes.
65
162
  * Supports nested namespace like `MyProject.routes`
66
- * Default: `Routes`
67
- * `prefix` - String representing a url path to prepend to all paths.
68
- * Option is configurable at JS level with `Routes.configure()`
69
- * Example: `http://yourdomain.com`. This will cause route helpers to generate full path only.
70
- * Default: `Rails.application.config.relative_url_root`
71
- * `camel_case` (version >= 0.8.8) - Generate camel case route names.
72
- * Default: false
73
- * `url_links` (version >= 0.8.9) - Generate `*_url` helpers (in addition to the default `*_path` helpers).
74
- * Example: true
75
- * Default: false
163
+ * Default: `nil`
164
+ * `camel_case` - specifies if route helpers should be generated in camel case instead of underscore case.
165
+ * Default: `false`
166
+ * `url_links` - specifies if `*_url` helpers should be generated (in addition to the default `*_path` helpers).
167
+ * Default: `false`
76
168
  * 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`.
77
- * `compact` (version > 0.9.9) - Remove `_path` suffix in path routes(`*_url` routes stay untouched if they were enabled)
78
- * Default: false
169
+ * `compact` - Remove `_path` suffix in path routes(`*_url` routes stay untouched if they were enabled)
170
+ * Default: `false`
79
171
  * Sample route call when option is set to true: Routes.users() => `/users`
80
- * `serializer` (version >= 1.1.0) - Puts a JS function here that serializes a Javascript Hash object into URL paramters: `{a: 1, b: 2} => "a=1&b=2"`.
81
- * Default: `nil`. Uses built-in serializer
82
- * Option is configurable at JS level with `Routes.configure()`
83
- * Example: `jQuery.param` - use jQuery's serializer algorithm. You can attach serialize function from your favorite AJAX framework.
84
- * Example: `MyApp.custom_serialize` - use completely custom serializer of your application.
85
-
86
- * `special_options_key` - a special key that helps JsRoutes to destinguish serialized model from options hash
87
- * This option is required because JS doesn't provide a difference between an object and a hash
88
- * Option is configurable at JS level with `Routes.configure()`
89
- * Default: `_options`
90
172
  * `application` - a key to specify which rails engine you want to generate routes too.
91
173
  * This option allows to only generate routes for a specific rails engine, that is mounted into routes instead of all Rails app routes
92
174
  * Default: `Rails.application`
175
+ * `file` - a file location where generated routes are stored
176
+ * Default: `app/javascript/routes.js` if setup with Webpacker, otherwise `app/assets/javascripts/routes.js` if setup with Sprockets.
177
+
178
+ ##### Formatter Options
179
+
180
+ Options to configure routes formatting. These options are available both in Ruby and JavaScript context.
181
+
182
+ * `default_url_options` - default parameters used when generating URLs
183
+ * Example: `{format: "json", trailing_slash: true, protocol: "https", subdomain: "api", host: "example.com", port: 3000}`
184
+ * Default: `{}`
185
+ * `prefix` - string that will prepend any generated URL. Usually used when app URL root includes a path component.
186
+ * Example: `/rails-app`
187
+ * Default: `Rails.application.config.relative_url_root`
188
+ * `serializer` - a JS function that serializes a Javascript Hash object into URL paramters like `{a: 1, b: 2} => "a=1&b=2"`.
189
+ * Default: `nil`. Uses built-in serializer compatible with Rails
190
+ * Example: `jQuery.param` - use jQuery's serializer algorithm. You can attach serialize function from your favorite AJAX framework.
191
+ * Example: `function (object) { ... }` - use completely custom serializer of your application.
192
+ * `special_options_key` - a special key that helps JsRoutes to destinguish serialized model from options hash
193
+ * This option exists because JS doesn't provide a difference between an object and a hash
194
+ * Default: `_options`
93
195
 
94
- ### Very Advanced Setup
196
+ ### Advanced Setup
95
197
 
96
198
  In case you need multiple route files for different parts of your application, you have to create the files manually.
97
199
  If your application has an `admin` and an `application` namespace for example:
98
200
 
99
201
  ```
100
- # app/assets/javascripts/admin/routes.js.erb
101
- <%= JsRoutes.generate(namespace: "AdminRoutes", include: /admin/) %>
102
-
103
- # app/assets/javascripts/admin.js.coffee
104
- #= require admin/routes
202
+ # app/javascript/admin/routes.js.erb
203
+ <%= JsRoutes.generate(include: /admin/) %>
105
204
  ```
106
205
 
107
206
  ```
108
- # app/assets/javascripts/application/routes.js.erb
109
- <%= JsRoutes.generate(namespace: "AppRoutes", exclude: /admin/) %>
110
-
111
- # app/assets/javascripts/application.js.coffee
112
- #= require application/routes
207
+ # app/javascript/customer/routes.js.erb
208
+ <%= JsRoutes.generate(exclude: /admin/) %>
113
209
  ```
114
210
 
115
- In order to generate the routes JS code to a string:
211
+ You can manipulate the generated helper manually by injecting ruby into javascript:
116
212
 
117
- ```ruby
118
- routes_js = JsRoutes.generate(options)
213
+ ``` erb
214
+ export const routes = <%= JsRoutes.generate(module_type: nil, namespace: nil) %>
119
215
  ```
120
216
 
121
217
  If you want to generate the routes files outside of the asset pipeline, you can use `JsRoutes.generate!`:
122
218
 
123
219
  ``` ruby
124
- path = "app/assets/javascripts"
125
- JsRoutes.generate!("#{path}/app_routes.js", :namespace => "AppRoutes", :exclude => [/^admin_/, /^api_/])
126
- JsRoutes.generate!("#{path}/adm_routes.js", :namespace => "AdmRoutes", :include => /^admin_/)
127
- JsRoutes.generate!("#{path}/api_routes.js", :namespace => "ApiRoutes", :include => /^api_/, :default_url_options => {:format => "json"})
128
- ```
129
-
130
- ### Rails relative URL root
220
+ path = Rails.root.join("app/javascript")
131
221
 
132
- If you've installed your application in a sub-path or sub-URI of your server instead of at the root, you need to set the `RAILS_RELATIVE_URL_ROOT` environment variable to the correct path prefix for your application when you precompile assets. Eg., if your application's base URL is "https://appl.example.com/Application1", the command to precompile assets would be:
222
+ JsRoutes.generate!("#{path}/app_routes.js", exclude: [/^admin_/, /^api_/])
223
+ JsRoutes.generate!("#{path}/adm_routes.js", include: /^admin_/)
224
+ JsRoutes.generate!("#{path}/api_routes.js", include: /^api_/, default_url_options: {format: "json"})
133
225
  ```
134
- RAILS_RELATIVE_URL_ROOT=/Application1 RAILS_ENV=production bundle exec rake assets:precompile
135
- ```
136
- The environment variable is only needed for precompilation of assets, at any other time (eg. when assets are compiled on-the-fly as in the development environment) Rails will set the relative URL root correctly on it's own.
137
-
138
226
 
139
227
  ## Usage
140
228
 
141
229
  Configuration above will create a nice javascript file with `Routes` object that has all the rails routes available:
142
230
 
143
231
  ``` js
232
+ import * as Routes from 'routes';
233
+
144
234
  Routes.users_path() // => "/users"
145
235
  Routes.user_path(1) // => "/users/1"
146
236
  Routes.user_path(1, {format: 'json'}) // => "/users/1.json"
@@ -181,11 +271,11 @@ This function allow to get the same `spec` for route, if you will get string rep
181
271
  '' + Routes.user_path // => "/users/:id(.:format)"
182
272
  ```
183
273
 
184
- Route function also contain inside attribute `required_params` required param names as array:
274
+ Route function also contain method `requiredParams` inside which returns required param names array:
185
275
 
186
276
  ```js
187
- Routes.users_path.required_params // => []
188
- Routes.user_path.required_params // => ['id']
277
+ Routes.users_path.requiredParams() // => []
278
+ Routes.user_path.requiredParams() // => ['id']
189
279
  ```
190
280
 
191
281
 
@@ -206,9 +296,34 @@ Routes.company_project_path({company_id: 1, id: 2, _options: true}) // => "/comp
206
296
 
207
297
  ## What about security?
208
298
 
209
- JsRoutes itself do not have security holes. It makes URLs
210
- without access protection more reachable by potential attacker.
211
- In order to prevent this use `:exclude` option for sensitive urls like `/admin_/`
299
+ JsRoutes itself does not have security holes.
300
+ It makes URLs without access protection more reachable by potential attacker.
301
+ If that is an issue for you, you may use one of the following solutions:
302
+
303
+ ### Explicit Import + ESM Tree shaking
304
+
305
+ Make sure `module_type` is set to `ESM` (the default) and JS files import only required routes into the file like:
306
+
307
+ ``` javascript
308
+ import {
309
+ inbox_path,
310
+ inboxes_path,
311
+ inbox_message_path,
312
+ inbox_attachment_path,
313
+ user_path,
314
+ } from 'routes.js.erb'
315
+ ```
316
+
317
+ ### Exclude option
318
+
319
+ Split your routes into multiple files related to each section of your website like:
320
+
321
+ ``` javascript
322
+ // admin-routes.js.erb
323
+ <%= JsRoutes.generate(include: /^admin_/)
324
+ // app-routes.js.erb
325
+ <%= JsRoutes.generate(exclude: /^admin_/)
326
+ ```
212
327
 
213
328
  ## JsRoutes and Heroku
214
329
 
@@ -228,11 +343,20 @@ There are some alternatives available. Most of them has only basic feature and d
228
343
  Advantages of this one are:
229
344
 
230
345
  * Rails 4,5,6 support
346
+ * [ESM Tree shaking](https://webpack.js.org/guides/tree-shaking/) support
231
347
  * Rich options set
232
348
  * Full rails compatibility
233
349
  * Support Rails `#to_param` convention for seo optimized paths
234
350
  * Well tested
235
351
 
352
+ ## Version 2 TODO
353
+
354
+ * Add routes generation .d.ts file
355
+ * Add config option on the output format: js, ts, d.ts
356
+ * Add prettier
357
+ * Add eslint
358
+ * Add development guide
359
+
236
360
  #### Thanks to [contributors](https://github.com/railsware/js-routes/contributors)
237
361
 
238
362
  #### Have fun