crumbly 2.0.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: ed17ee652b5921eb589230281536a0276637edbd773fc702efa7aafd4047de6b
4
- data.tar.gz: d0ba23f23a3d717a272a84d2170766153bf2d8f47e470c41f75ad3851a6d9f52
3
+ metadata.gz: 06aa2669dc2486a8c255ca46215e1c65e7ca3eaf76cd834501a7c0f8a1734237
4
+ data.tar.gz: 37ab7df264cbb31555bc2f3e646c2ea10036057dac7e9f4f70e022506906f6cf
5
5
  SHA512:
6
- metadata.gz: 4d56f2fe77659476bea73d87c4afd3135d110cc0c2fe5595afd7b8a8c08c3c1e46040c955baaaf0f314db2b4605f19463e5e40415089bcfa699940af9022289d
7
- data.tar.gz: bd6b976d63c096d029fd3a9e78c0101f031d160a5f1348dee55eabff5778098d6bee5ee2d971d3c7e44d8fea27b62195361426953e84d23e090cc321a0fe1fd3
6
+ metadata.gz: 5d77cc663933f726c4923fb1a5655ecff481b0eaabb6bcc0fb852306bf342e7f7838d420a68b823234fe3a13d4ea40355a500bdce8e80dc86ecb0a24788b2dc9
7
+ data.tar.gz: 6d3a5af07dcd0d5e69b3a6d2f6669c03c4eae29d182a17d30fa69f8f24886afd67f27d2b89e5394561f166c4033d4166d792fb4f5acca46902290b7140e6bb27
data/CHANGELOG.md CHANGED
@@ -2,6 +2,30 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [2.2.0] — 2026-11-06
6
+
7
+ A trail class can turn off derived trails with `derive_trails false`, and a derived level labels a record without its own `to_s` "Invoice 12" instead of `#<Invoice:0x…>`.
8
+
9
+ **New**
10
+ - `derive_trails false` in a trail class, for apps that want only the trails they write, as with gretel: a view without a `breadcrumb` call gets an empty `breadcrumb_trail` and a nil `breadcrumb_json_ld`. Subclasses inherit it and `derive_trails true` turns it back on. In such a class, `Crumbly.verify!` reports a crumb that only a derived trail would read as unused, and `Crumbly::Oracle.redundant_calls` lists nothing.
11
+
12
+ **Fixed**
13
+ - A derived level whose record's model doesn't define `to_s` is labelled with the translated model name and id, "Invoice 12", instead of Ruby's `#<Invoice:0x000…>`. A model's own `to_s` still wins.
14
+
15
+ ## [2.1.0] — 2026-11-06
16
+
17
+ Crumbs refuse `javascript:`, `vbscript:` and `data:` URLs, and a nil record, odd bytes or `=begin` comments no longer break Crumbly.
18
+
19
+ **New**
20
+ - `Crumbly::UnsafeUrl`, for a crumb or a `link` whose URL is `javascript:`, `vbscript:` or `data:`, in any case and with the spaces, control characters, tabs and line breaks that browsers drop. It raises in development and test; in production it goes to `Rails.error`, and the level keeps its label without the link. `Crumbly.raise_on_unsafe_url` chooses, like the other two settings.
21
+
22
+ **Fixed**
23
+ - loofah's floor moves to 2.25.3, and with it nokogiri's to 1.19.5: the first versions without the 2026 advisories, two of them in the HTML5 scrubber Crumbly calls on `html_safe` labels.
24
+ - `breadcrumb` with a nil record, or an object without a model, raises or reports `Crumbly::UnknownCrumb` instead of a `NoMethodError` that failed the page. A `parent:` that is not a crumb raises an `ArgumentError` that names it.
25
+ - `breadcrumb_json_ld` replaces invalid bytes in a label with U+FFFD, and reads `HTTPS://` as an absolute URL.
26
+ - `Crumbly.verify!` and `crumbly-convert --views` read files that are not UTF-8 instead of crashing.
27
+ - `crumbly-convert` writes `=begin` comments as `#` lines, and keeps a loop value interpolated in a regexp, a command, a `%W` array or `%Q/`, where it wrote Ruby that doesn't parse.
28
+
5
29
  ## [2.0.0] — 2026-11-05
6
30
 
7
31
  GretelX is now Crumbly, in the levups organization: same breadcrumbs, new names.
@@ -62,7 +86,9 @@ tests. Replaces gretel: `crumbly-convert` turns its breadcrumbs files into Crumb
62
86
  `breadcrumb` calls a derived trail may now cover.
63
87
  - `Crumbly::Oracle.compare` draws trails with gretel and with Crumbly, from a test of an app migrating.
64
88
 
65
- [Unreleased]: https://github.com/levups/crumbly/compare/v2.0.0...HEAD
89
+ [Unreleased]: https://github.com/levups/crumbly/compare/v2.2.0...HEAD
90
+ [2.2.0]: https://github.com/levups/crumbly/compare/v2.1.0...v2.2.0
91
+ [2.1.0]: https://github.com/levups/crumbly/compare/v2.0.0...v2.1.0
66
92
  [2.0.0]: https://github.com/levups/crumbly/compare/v1.1.0...v2.0.0
67
93
  [1.1.0]: https://github.com/levups/crumbly/compare/v1.0.0...v1.1.0
68
94
  [1.0.0]: https://github.com/levups/crumbly/releases/tag/v1.0.0
data/README.md CHANGED
@@ -1,40 +1,53 @@
1
1
  # Crumbly
2
2
 
3
- Breadcrumbs for Rails: namespaced, derived from your routes, checked in tests.
3
+ Crumbly builds breadcrumb trails for Rails apps. A breadcrumb trail is the line of links at the top of a page that
4
+ shows where it sits in the site:
4
5
 
5
- <https://levups.github.io/crumbly/>: guide, migration from gretel, breadcrumbs_on_rails and loaf, benchmarks.
6
+ ```
7
+ Home › Customers › Alice › Orders › Order 2026-0042
8
+ ```
9
+
10
+ You describe each level once, as a Ruby method that names its parent. Most pages need nothing more: when a view
11
+ doesn't say which trail it wants, Crumbly works it out from the controller, the action and the routes. A test
12
+ checks every trail in the app, so a broken one fails CI before anyone opens the page.
13
+
14
+ The guide, the migration notes and the benchmarks are also on the website: <https://levups.github.io/crumbly/>.
6
15
 
7
- [gretel](https://github.com/kzkn/gretel) works, but on a real back office (one file of about 1,000 lines,
8
- 265 crumbs, 380 call sites), its shape is what hurts:
16
+ ## Why Crumbly
9
17
 
10
- - one global file and one flat namespace, where a crumb defined twice silently replaces the first, and an
11
- admin area cannot keep its breadcrumbs apart from a storefront's;
12
- - mistakes that only show when someone opens the page;
13
- - blocks run through `instance_exec` and helpers reached through `method_missing`;
14
- - every trail written by hand, even when the routes already describe it.
18
+ Crumbly was written to replace [gretel](https://github.com/kzkn/gretel) in a back office with 265 crumbs, in one
19
+ file of about 1,000 lines, and 380 calls in views. It works differently in a few ways:
15
20
 
16
- Crumbly keeps gretel's good idea (a crumb names its parent) and changes the rest:
21
+ - The crumbs of each part of the app live in their own class, `Admin::Breadcrumbs` or `Storefront::Breadcrumbs`,
22
+ so the admin and the storefront can both have an `orders` crumb.
23
+ - A crumb is a plain method. Route helpers work in it as in a view, and a backtrace points at its line.
24
+ - Index, show, new and edit pages get their trail from the routes and the record the controller loaded, so most
25
+ views name no crumb.
26
+ - One test reads every crumb and fails on a parent, a route helper or a crumb name that doesn't exist, without
27
+ touching the database.
28
+ - The trail comes back as data, and your layout writes the HTML. The gem has no styles or rendering options.
29
+ - Rendering a five-level trail as an `<ol>` takes 45.4 µs against 57.6 µs for gretel, with 274 allocations
30
+ instead of 345 (YJIT off). JSON-LD is a little slower: see [Performance](#performance).
17
31
 
18
- - **One class per namespace.** `Admin::Breadcrumbs` and `Storefront::Breadcrumbs` each hold their own crumbs,
19
- under the same names if they like. Zeitwerk loads them, so they load before a prefork server forks.
20
- - **One crumb per Ruby method.** The parent is a plain method call, and the URL helpers come from your routes.
21
- There is no DSL to learn and no `method_missing`, and a backtrace points at the method.
22
- - **Derived by default.** A view that names no crumb gets the trail of its action, built from the routes and
23
- the record its controller loaded.
24
- - **Mistakes raise early.** A crumb defined twice raises when the class loads, and an unknown crumb raises in
25
- development and test. In production it is reported and the page renders without a trail.
26
- - **Data, not HTML.** `breadcrumb_trail` returns levels (label, URL, extra links, `current?`), and your own
27
- component renders them.
32
+ Its runtime dependencies are Action Pack, Active Support and Loofah, which Rails already installs.
28
33
 
29
34
  ## Installation
30
35
 
36
+ Add the gem to your Gemfile:
37
+
31
38
  ```ruby
32
39
  gem "crumbly"
33
40
  ```
34
41
 
35
- The railtie adds `breadcrumb`, `breadcrumb_trail` and `breadcrumb_json_ld` to your views, and `breadcrumbs_with` to your controllers.
42
+ It needs Ruby 3.3 or later and Rails 8.0 or later. There is nothing to configure: the gem adds `breadcrumb`,
43
+ `breadcrumb_trail` and `breadcrumb_json_ld` to your views, and `breadcrumbs_with` to your controllers.
44
+
45
+ ## Getting started
36
46
 
37
- ## Usage
47
+ ### 1. Write the crumbs
48
+
49
+ Crumbs live in a class that inherits from `Crumbly::Trail`. Every public method in it is a crumb. A crumb returns
50
+ a label and a URL, and its parent if it has one:
38
51
 
39
52
  ```ruby
40
53
  # app/breadcrumbs/admin/breadcrumbs.rb
@@ -55,10 +68,17 @@ module Admin
55
68
  end
56
69
  ```
57
70
 
58
- ```erb
59
- <%# app/views/admin/orders/show.html.erb: optional, this is what the trail derives on its own %>
60
- <% breadcrumb @order %>
71
+ The parent of `order` is the result of calling `orders`, so the trail of an order page is Home › Orders ›
72
+ Order 42. When `root` exists, every trail starts with it. Your route helpers work inside the class as they do in
73
+ a view. Rails loads the file like any other in `app/`, so `app/breadcrumbs/admin/breadcrumbs.rb` defines
74
+ `Admin::Breadcrumbs`.
75
+
76
+ ### 2. Render the trail in the layout
61
77
 
78
+ `breadcrumb_trail` returns the levels of the current page, from the root to the page itself. Each level has a
79
+ `label`, a `url` and `current?`, which is true for the last one. The HTML is up to you:
80
+
81
+ ```erb
62
82
  <%# app/views/layouts/admin.html.erb %>
63
83
  <nav aria-label="Breadcrumb">
64
84
  <ol>
@@ -69,175 +89,130 @@ end
69
89
  </nav>
70
90
  ```
71
91
 
72
- - `breadcrumb :name, *arguments` calls the crumb named `name`, and `breadcrumb @record` calls the crumb named
73
- after the record's model (`order` for an `Order`). For a single-table inheritance subclass with no crumb of
74
- its own, it falls back on its parent class's.
75
- - `root`, when you define it, starts every trail.
76
- - `crumb label, url = nil, parent: nil, links: []`. `url` takes a string, a record or a polymorphic array
77
- (`[:admin, owner, :returns]`), or nothing for a level without a link. `links:` holds extra
78
- `link(label, url)`s for a level that points to more than one page.
79
- - `crumb_for(record)` is the crumb of a record found by its model, which is how you write a polymorphic parent.
80
- - Private methods are helpers, not crumbs. View helpers are reached through `helpers` (`helpers.t(".orders")`).
81
- - Every name that works in a view is a crumb, so `Crumbly::Trail` keeps its own methods private. The ones
82
- your crumbs must not be named after are `crumb`, `link`, `crumb_for` and `helpers`.
92
+ On the page of an order whose `to_s` is "Order 42", with the admin routes at `/admin`, this writes:
83
93
 
84
- ### Namespaces
85
-
86
- `Admin::OrdersController` reads `Admin::Breadcrumbs`, falling back on enclosing modules and then on a
87
- top-level `Breadcrumbs`. A controller elsewhere picks one explicitly:
88
-
89
- ```ruby
90
- class CheckoutController < ApplicationController
91
- breadcrumbs_with Storefront::Breadcrumbs
92
- end
94
+ ```html
95
+ <nav aria-label="Breadcrumb">
96
+ <ol>
97
+ <li><a href="/admin">Home</a></li>
98
+ <li><a href="/admin/orders">Orders</a></li>
99
+ <li>Order 42</li>
100
+ </ol>
101
+ </nav>
93
102
  ```
94
103
 
95
- ### Derived trails
104
+ ### 3. Pick a crumb in a view, when you need to
96
105
 
97
- When a view does not call `breadcrumb`, the trail follows the action:
106
+ A view can name the crumb it wants:
98
107
 
99
- | Action | Trail |
100
- |---|---|
101
- | `index` | the collection: your `posts` crumb, or else the model's plural name linked to the `index` route |
102
- | `show` | the record: your `post` crumb, or else `to_s` linked to the `show` route, under the collection |
103
- | `new`, `create` | "New" (`crumbly.new`) under the collection |
104
- | `edit`, `update` | "Edit" (`crumbly.edit`) under the record |
108
+ ```erb
109
+ <%# app/views/admin/orders/show.html.erb %>
110
+ <% breadcrumb @order %>
111
+ ```
105
112
 
106
- The record is the one the controller already loaded (`@post` in `PostsController`): it is never looked up
107
- again. To change how a trail is derived, override the private methods `collection_crumb`, `record_crumb`,
108
- `new_record_crumb` or `edit_record_crumb`.
113
+ `breadcrumb @order` calls the crumb named after the record's model, `order` for an `Order`. To call a crumb by
114
+ name, write `breadcrumb :orders`, and pass its arguments after the name (`breadcrumb :order, @order`).
109
115
 
110
- Under a nested route, each `:<name>_id` path parameter is a parent level, outermost first.
111
- `/admin/posts/5/comments` gives Comments under Post 5 under Posts, the post being `@post`, as the controller
112
- loaded it: your `post` crumb, or else its `to_s` linked to its `show` route, under the posts collection. A
113
- parent the controller did not load is never queried: the trail skips the nesting's crumb, keeps that parent's
114
- collection (Posts) and goes straight to the current level.
116
+ In this example the line isn't needed. A `show` page with no `breadcrumb` call already gets the trail of its
117
+ record (see [Trails Crumbly works out on its own](#trails-crumbly-works-out-on-its-own)).
115
118
 
116
- ### Order of precedence
119
+ ## Writing crumbs
117
120
 
118
- For any page, the first of these that applies builds the trail:
121
+ A crumb calls `crumb label, url = nil, parent: nil, links: []`.
119
122
 
120
- 1. The view's `breadcrumb`.
121
- 2. The namespace's crumb named after the controller: `posts` in `Admin::PostsController#index`, and under a
122
- nested route the whole nesting, called with the parents' records (`order_messages(order)` for
123
- `/admin/orders/42/messages`). On `show` and `edit`, the crumb named after the record's model (`post`).
124
- 3. The derived trail, whose parent levels follow the same order: your crumb for the parent's model, or else
125
- the derived level.
123
+ `url` can be a string, a record or a polymorphic array such as `[:admin, owner, :returns]`. Leave it out for a
124
+ level without a link. A `javascript:`, `vbscript:` or `data:` URL would run a script once your layout links it,
125
+ so Crumbly refuses it, however it is spelled (`" JavaScript:"`, `"java\tscript:"`): see
126
+ [Mistakes in development and in production](#mistakes-in-development-and-in-production).
126
127
 
127
- ## Five real-world cases, side by side
128
+ `links:` is for a level that points to more than one page. It takes extra `link(label, url)` entries, which your
129
+ layout reads from `level.links`.
128
130
 
129
- ### A nested resource
131
+ `crumb_for(record)` finds the crumb of a record from its model. Use it when the parent can be one of several
132
+ models:
130
133
 
131
134
  ```ruby
132
- # gretel, config/breadcrumbs.rb
133
- crumb :order_messages do |order|
134
- link "Messages", admin_order_messages_path(order)
135
- parent :order, order
136
- end
137
- ```
135
+ def returns(owner = nil)
136
+ return crumb("Returns", admin_returns_path) unless owner
138
137
 
139
- ```ruby
140
- # Crumbly, app/breadcrumbs/admin/breadcrumbs.rb: optional, the nested route derives the same trail
141
- def order_messages(order)
142
- crumb "Messages", admin_order_messages_path(order), parent: order(order)
138
+ crumb "Returns", [:admin, owner, :returns], parent: crumb_for(owner)
143
139
  end
144
140
  ```
145
141
 
146
- ### A polymorphic parent
142
+ For a single-table inheritance subclass that has no crumb of its own, `crumb_for` and `breadcrumb @record` use the
143
+ crumb of its parent class.
147
144
 
148
- ```ruby
149
- # gretel
150
- crumb :returns do |owner|
151
- if owner
152
- link "Returns", [:admin, owner, :returns]
153
- parent owner
154
- else
155
- link "Returns", admin_returns_path
156
- end
157
- end
158
- ```
145
+ Private methods are helpers, not crumbs, so you can put shared code in them. View helpers such as `t` or
146
+ `current_user` are reached through `helpers`: `helpers.t(".orders")`.
159
147
 
160
- ```ruby
161
- # Crumbly
162
- def returns(owner = nil)
163
- return crumb("Returns", admin_returns_path) unless owner
148
+ Any public method can be called from a view, so `Crumbly::Trail` keeps its own methods private. Don't name a crumb
149
+ `crumb`, `link`, `crumb_for` or `helpers`.
164
150
 
165
- crumb "Returns", [:admin, owner, :returns], parent: crumb_for(owner)
166
- end
167
- ```
151
+ ## One trail class per namespace
168
152
 
169
- ### A label computed from the record
153
+ `Admin::OrdersController` uses `Admin::Breadcrumbs`. If there is none, Crumbly looks in the enclosing modules,
154
+ then for a top-level `Breadcrumbs`. An admin area and a storefront can each have an `orders` crumb, and they
155
+ don't clash.
170
156
 
171
- ```ruby
172
- # gretel
173
- crumb :order do |order|
174
- link "Order #{order.number}", admin_order_path(order)
175
- if order.customer
176
- parent :customer_orders, order.customer
177
- else
178
- parent :orders
179
- end
180
- end
181
- ```
157
+ A controller outside the namespace picks its class with `breadcrumbs_with`:
182
158
 
183
159
  ```ruby
184
- # Crumbly
185
- def order(order)
186
- crumb "Order #{order.number}", admin_order_path(order),
187
- parent: order.customer ? customer_orders(order.customer) : orders
160
+ class CheckoutController < ApplicationController
161
+ breadcrumbs_with Storefront::Breadcrumbs
188
162
  end
189
163
  ```
190
164
 
191
- ### A recursive tree
165
+ ## Trails Crumbly works out on its own
192
166
 
193
- The ancestors are loaded once, in one query, and handed down the recursion:
167
+ When a view doesn't call `breadcrumb`, Crumbly builds the trail from the action:
194
168
 
195
- ```ruby
196
- # gretel
197
- crumb :category do |category, ancestors = category.ancestors.to_a|
198
- link category.name, admin_category_path(category)
199
- *grandparents, parent_category = ancestors
200
- parent_category ? parent(:category, parent_category, grandparents) : parent(:categories)
201
- end
202
- ```
169
+ | Action | Trail |
170
+ |---|---|
171
+ | `index` | the collection: your `posts` crumb if you wrote one, or else the model's plural name linked to the `index` route |
172
+ | `show` | the record: your `post` crumb, or else its label linked to the `show` route, under the collection |
173
+ | `new`, `create` | "New" under the collection |
174
+ | `edit`, `update` | "Edit" under the record |
203
175
 
204
- ```ruby
205
- # Crumbly
206
- def category(category, ancestors = category.ancestors.to_a)
207
- *grandparents, parent_category = ancestors
208
- crumb category.name, admin_category_path(category),
209
- parent: parent_category ? category(parent_category, grandparents) : categories
210
- end
211
- ```
176
+ The record is the one the controller has already loaded, `@post` in `PostsController`. Crumbly never runs a query
177
+ to find it. "New" and "Edit" come from the `crumbly.new` and `crumbly.edit` translations, so you can translate
178
+ them. A record's label is its `to_s`. A model without a `to_s` of its own gets its translated model name and id
179
+ instead ("Post 5"), not `#<Post:0x000...>`.
180
+
181
+ Nested routes work too. On `/admin/posts/5/comments`, the trail is Posts › Post 5 › Comments, and the post is
182
+ the `@post` the controller loaded. If the controller didn't load it, Crumbly skips that level and keeps Posts.
212
183
 
213
- ### A form
184
+ To change how these trails are built, override the private methods `collection_crumb`, `record_crumb`,
185
+ `new_record_crumb` or `edit_record_crumb` in your trail class.
186
+
187
+ To turn them off, set `derive_trails false` in the trail class. A view that doesn't call `breadcrumb` then has no
188
+ trail, as with gretel: `breadcrumb_trail` returns `[]` and `breadcrumb_json_ld` returns `nil`.
214
189
 
215
190
  ```ruby
216
- # gretel: one generic crumb, called from each new and edit view
217
- crumb :generic_form do |model|
218
- if model.new_record?
219
- link "New", nil
220
- parent model.class.model_name.plural.to_sym
221
- else
222
- link "Edit", nil
223
- parent model
191
+ module Admin
192
+ class Breadcrumbs < Crumbly::Trail
193
+ derive_trails false
224
194
  end
225
195
  end
226
196
  ```
227
197
 
228
- ```erb
229
- <%# app/views/admin/posts/edit.html.erb %>
230
- <% breadcrumb :generic_form, @post %>
231
- ```
198
+ Subclasses inherit the setting, and `derive_trails true` turns it back on in one of them.
232
199
 
233
- ```ruby
234
- # Crumbly: nothing to write. new and edit derive "New" under the collection, "Edit" under the record.
235
- ```
200
+ ### Which crumb wins
201
+
202
+ Crumbly takes the first of these that applies:
236
203
 
237
- ## Checked in tests
204
+ 1. The crumb the view names with `breadcrumb`.
205
+ 2. Your crumb named after the controller: `posts` in `Admin::PostsController#index`. Under a nested route it is
206
+ named after the whole nesting and gets the parent records, so `/admin/orders/42/messages` calls
207
+ `order_messages(order)`. On `show` and `edit`, it is the crumb named after the record's model (`post`).
208
+ 3. The trail Crumbly works out. Its parent levels follow the same rule: your crumb for the parent's model if there
209
+ is one, or else a level Crumbly builds.
238
210
 
239
- A crumb defined twice already raises when its class loads. One test checks the rest, without running a crumb
240
- or loading a record:
211
+ With `derive_trails false`, only the first applies.
212
+
213
+ ## Testing your trails
214
+
215
+ Add one test:
241
216
 
242
217
  ```ruby
243
218
  # test/breadcrumbs_test.rb
@@ -251,24 +226,51 @@ class BreadcrumbsTest < ActiveSupport::TestCase
251
226
  end
252
227
  ```
253
228
 
254
- It eager-loads the app and reads the source of every crumb (and of the private helpers next to it) with Prism:
229
+ It loads the whole app and reads the source of every crumb, without running them or touching the database. It
230
+ fails when:
231
+
232
+ - a crumb's parent is not a crumb, or a `_path` or `_url` it calls is not a route helper;
233
+ - a `breadcrumb :name` in `app/views` or `app/controllers` names a crumb that no trail class defines;
234
+ - a view or another crumb calls a crumb with the wrong number of arguments (calls spread over several lines, or
235
+ with a splat, are skipped);
236
+ - a crumb is never used. A crumb is used when another crumb, a view or a controller calls it, when a trail
237
+ Crumbly works out reads it (unless its class sets `derive_trails false`), or when it is named after a model.
255
238
 
256
- - every parent a crumb calls is a crumb, and every `_path` or `_url` it calls is a route helper;
257
- - every `breadcrumb :name` in `app/views` and `app/controllers` names a crumb some trail defines;
258
- - every crumb is called with as many arguments as it takes, by its views and by other crumbs: gretel ignored
259
- extra arguments and passed `nil` for missing ones, a method raises `ArgumentError` (a view call spread over
260
- several lines, or with a splat, is not counted);
261
- - every crumb is reachable: called by another crumb, by a view or controller (`breadcrumb :name`,
262
- `breadcrumb @record`), by a derived trail (the collection and record of a routed controller), or named after
263
- a model. The others are dead, and fail the test.
239
+ A crumb defined twice in the same class is caught even earlier: the class raises `Crumbly::DuplicateCrumb` when it
240
+ loads.
264
241
 
265
- `Crumbly.verify!` does the same outside Minitest: it raises `Crumbly::InvalidTrail` with every problem
266
- in one message, and returns the dead crumbs (`["Admin::Breadcrumbs#drafts"]`). Both take `trail_classes:`,
267
- `routes:` and `sources:` (the directories scanned for `breadcrumb` calls).
242
+ Outside Minitest, `Crumbly.verify!` runs the same checks. It raises `Crumbly::InvalidTrail` with every problem in
243
+ one message, and returns the unused crumbs (`["Admin::Breadcrumbs#drafts"]`). Both accept `trail_classes:`,
244
+ `routes:` and `sources:`, the directories it scans for `breadcrumb` calls.
268
245
 
269
- ## Storefronts
246
+ ## Mistakes in development and in production
270
247
 
271
- The trail is data, so absolute URLs are just `_url` helpers in that namespace's crumbs:
248
+ A view that asks for a crumb that doesn't exist raises `Crumbly::UnknownCrumb` in development and test. So does
249
+ `breadcrumb @order` when `@order` is `nil`. In production the error goes to `Rails.error`, and the page renders
250
+ without a trail instead of failing.
251
+
252
+ A crumb whose URL a browser would run as a script raises `Crumbly::UnsafeUrl` in development and test. In
253
+ production the error goes to `Rails.error`, and the level keeps its label without the link.
254
+
255
+ To raise in production too, on a staging server for example, set either in an initializer:
256
+
257
+ ```ruby
258
+ # config/initializers/crumbly.rb
259
+ Crumbly.raise_on_unknown_crumb = true # on staging too
260
+ Crumbly.raise_on_unsafe_url = true
261
+ ```
262
+
263
+ ## Breadcrumbs for search engines
264
+
265
+ Google can show a page's trail in its results when the page describes it as schema.org structured data.
266
+ `breadcrumb_json_ld` writes that description for the current trail. Put it in the `<head>`:
267
+
268
+ ```erb
269
+ <%# app/views/layouts/storefront.html.erb %>
270
+ <%= breadcrumb_json_ld %>
271
+ ```
272
+
273
+ Google needs absolute URLs, so use `_url` helpers in the crumbs of that namespace:
272
274
 
273
275
  ```ruby
274
276
  module Storefront
@@ -281,129 +283,48 @@ module Storefront
281
283
  end
282
284
  ```
283
285
 
284
- `breadcrumb_json_ld` renders the same trail as a schema.org `BreadcrumbList`, the structured data Google reads
285
- for its breadcrumb rich result:
286
+ A relative URL raises `Crumbly::RelativeUrl` in development and test. In production it is reported to
287
+ `Rails.error` and the page has no structured data. `Crumbly.raise_on_relative_url` changes this.
286
288
 
287
- ```erb
288
- <%# app/views/layouts/storefront.html.erb, in <head> %>
289
- <%= breadcrumb_json_ld %>
290
- ```
289
+ Some details of the output:
291
290
 
292
- - Positions start at 1, and the current level may have no URL. A level above it without a URL is not a page,
293
- so it is left out.
294
- - A name is plain text: an `html_safe` label (an icon, a `<b>`) has its markup stripped and its entities decoded.
295
- - The JSON is escaped for a `<script>` tag, so a label cannot close it.
296
- - Google only takes absolute URLs: a relative one raises `Crumbly::RelativeUrl` in development and test.
297
- In production it is reported and the page renders without a `BreadcrumbList`. Set
298
- `Crumbly.raise_on_relative_url` to choose.
299
- - `Crumbly::JsonLd.call(levels)` returns the `BreadcrumbList` as a hash, for a page that builds its own
300
- structured data.
291
+ - Positions start at 1. The last level may have no URL. A level above it without a URL isn't a page, so it is
292
+ left out.
293
+ - Names are plain text. If a label is `html_safe` (an icon, a `<b>`), its tags are removed.
294
+ - The JSON is escaped for a `<script>` tag, so a label can't close it.
295
+ - `Crumbly::JsonLd.call(levels)` returns the same data as a hash, if you build the structured data of the page
296
+ yourself.
301
297
 
302
- ## Migrating from gretel
298
+ ## Switching from gretel, loaf or breadcrumbs_on_rails
303
299
 
304
- An app switches in one go: there is no compatibility layer, and the two gems do not run side by side in
305
- production. gretel stays in the Gemfile of the migration branch only, for the comparison test below.
300
+ Crumbly uses the same view helper names as these gems, so an app switches in one go: there is no compatibility
301
+ layer, and the old gem leaves the Gemfile once the migration is merged.
306
302
 
307
- ### 1. Convert the breadcrumbs file
303
+ From gretel, the calls in your views barely change (`breadcrumb :order, @order` and `breadcrumb @order` work as
304
+ before), and `crumbly-convert` turns `config/breadcrumbs.rb` into a trail class:
308
305
 
309
306
  ```sh
310
307
  bundle exec crumbly-convert config/breadcrumbs.rb --namespace Admin \
311
308
  --output app/breadcrumbs/admin/breadcrumbs.rb --views app/views/admin
312
309
  ```
313
310
 
314
- It writes `Admin::Breadcrumbs` and prints, with their line, what it left out or converted with a loss. Several
315
- files (`config/breadcrumbs/*.rb`) make one class, the later definition of a crumb winning as in gretel.
316
-
317
- | gretel | Crumbly |
318
- |---|---|
319
- | `crumb :key do \|order\| ... end` | `def key(order) ... end`, a parameter tested for nil getting `= nil` |
320
- | `link label, url` | `crumb label, url`; `link label` or `link label, nil` give a level without a URL |
321
- | a second `link` | `links: [link(label, url)]` on the same level |
322
- | `parent :other, order` | `parent: other(order)` |
323
- | `parent record` | `parent: crumb_for(record)` |
324
- | `parent :a` and `parent :b` in an `if`/`else` | `parent: condition ? a : b` |
325
- | `parent :a`, then `parent :b if condition` | `parent: condition ? b : a` |
326
- | `link` and `parent` inside an `if`, `elsif`, `unless` or `case`, modifiers included | one `crumb` call per branch, the statements after the conditional copied into each |
327
- | `t(".x")`, `current_user`: view helpers | `helpers.t(".x")`, `helpers.current_user`; route helpers stay bare |
328
- | `%i[a b].each { \|name\| crumb name do ... end }`, `{a: [:post, Comment]}.each { \|name, (parent, model)\| ... }` | one method per element |
329
- | a local assigned before a crumb reads it: `path = :"admin_#{name}_path"` | copied into each crumb reading it, a literal written in place |
330
- | `label = ->(record) { ... }` at the top of the file, reading no other local | a private method, `label.call(post)` becoming `label(post)` |
331
-
332
- It lists, without converting them: a loop over anything but a literal array or hash (of symbols, strings,
333
- numbers and constants), `link` or `parent` inside anything but a conditional (a loop, a block), `link` options
334
- (`title:`, `class:`), crumbs whose name is a Ruby keyword or an existing method (`display`, `test`), and any
335
- statement that is not a crumb, a loop or a local. Comments are kept above the method they precede.
336
-
337
- The codemod is built on Prism 1.2 or later: Ruby 3.4 ships it, and on Ruby 3.3 add `gem "prism"` to the
338
- development group.
339
-
340
- ### 2. Compare the trails
341
-
342
- While gretel is still bundled, the tests draw each trail with both gems and list the differences in labels and
343
- URLs. gretel shows a crumb's extra links as levels of their own: the comparison does the same with `links`. Keep
344
- gretel in the test group with `require: false`: `crumbly/oracle` loads it, without the view helpers whose
345
- `breadcrumb` would replace Crumbly's.
346
-
347
- ```ruby
348
- # Gemfile, on the migration branch
349
- gem "gretel", require: false, group: :test
350
- ```
351
-
352
- The views already call `breadcrumb` the way Crumbly expects, so the app's own controller, integration and system
353
- tests can do the comparing. With `Crumbly::Oracle.watch` in the test helper, every page they render is drawn by
354
- gretel too, from the same `breadcrumb` call:
355
-
356
- ```ruby
357
- # test/test_helper.rb, once the app is loaded
358
- require "crumbly/oracle"
359
-
360
- Crumbly::Oracle.watch
361
- Minitest.after_run do
362
- puts Crumbly::Oracle.differences.to_a, Crumbly::Oracle.redundant_calls.to_a
363
- end
364
- ```
365
-
366
- `differences` holds each page whose trail changed, gretel's and Crumbly's side by side, including the pages
367
- without a `breadcrumb` call, which gretel left without a trail and which now derive one. `redundant_calls`
368
- holds the calls whose trail the action derives anyway. `watch { ... }` watches a block only. Parallel test
369
- workers each fill their own lists, which `after_run` in the parent process never sees: run the watched suite
370
- with `PARALLEL_WORKERS=1`. A call gretel cannot draw shows as a difference, with gretel's error.
371
-
372
- For the crumbs no test renders, `compare` takes the calls to check:
373
-
374
- ```ruby
375
- class BreadcrumbsMigrationTest < ActionView::TestCase
376
- test "Crumbly draws the trails gretel drew" do
377
- differences = Crumbly::Oracle.compare(view, Admin::Breadcrumbs, [
378
- [:orders], [:order, orders(:alice)], [orders(:alice)], [:returns], [:returns, customers(:alice)]
379
- ])
380
-
381
- assert_empty differences, differences.join("\n")
382
- end
383
- end
384
- ```
385
-
386
- ### 3. Review the call sites
311
+ It prints each line it left out or couldn't convert exactly, and with `--views`, the `breadcrumb` calls that
312
+ Crumbly may now make unnecessary. It needs Prism 1.2 or later: Ruby 3.4 comes with it, and on Ruby 3.3 you add
313
+ `gem "prism"` to the development group. While gretel is still installed on the migration branch,
314
+ `Crumbly::Oracle` draws each trail your tests render with both gems and lists where the labels or URLs differ.
315
+ To keep gretel's empty trail on pages whose views name no crumb, set `derive_trails false` in the trail class.
387
316
 
388
- `--views` lists the `breadcrumb` calls that a derived trail may now cover: `:generic_form` (or `:new`,
389
- `:edit`) in new and edit views, `breadcrumb @order` in a show view, `breadcrumb :orders` in an index view.
390
- Nothing is deleted: a call goes once its view shows the same trail without it, which is what
391
- `Crumbly::Oracle.redundant_calls` lists for the pages the tests render.
392
-
393
- ### 4. Remove gretel
394
-
395
- Drop gretel and `config/breadcrumbs.rb`, and render `breadcrumb_trail` in the layout where `breadcrumbs` was.
396
-
397
- ## Requirements
398
-
399
- Ruby 3.3 or later, and Rails 8.0 or later (Action Pack and Active Support).
317
+ The [migration guide](https://levups.github.io/crumbly/migration.html) has every step: what the converter maps to
318
+ what, what it leaves to you, the comparison in your tests, and the same walk-through for loaf and
319
+ breadcrumbs_on_rails. The [home page](https://levups.github.io/crumbly/) shows five crumbs from a real gretel app
320
+ next to their Crumbly version.
400
321
 
401
322
  ## Performance
402
323
 
403
324
  `bench/render.rb` renders the same five-level trail (Home > Customers > Alice > Orders > Order 2026-0042) with
404
- gretel and with Crumbly, and checks that both produce the same output. The `<ol>` is gretel's
405
- `breadcrumbs(style: :ol)` against a ten-line helper over `breadcrumb_trail`. The JSON-LD is gretel's
406
- `structured_data(url_base:)` (paths behind a prefix) against `breadcrumb_json_ld` (`_url` helpers), both
325
+ gretel and with Crumbly, and checks that both give the same output. The `<ol>` row compares gretel's
326
+ `breadcrumbs(style: :ol)` with a ten-line helper over `breadcrumb_trail`. The JSON-LD row compares gretel's
327
+ `structured_data(url_base:)`, with paths behind a prefix, and `breadcrumb_json_ld` with `_url` helpers. Both are
407
328
  encoded and escaped the same way.
408
329
 
409
330
  Ruby 4.0.9, Rails 8.1.4, gretel 5.1.0, Apple M5 (arm64 macOS), median of three runs of benchmark-ips:
@@ -415,14 +336,21 @@ Ruby 4.0.9, Rails 8.1.4, gretel 5.1.0, Apple M5 (arm64 macOS), median of three r
415
336
  | gretel JSON-LD | 268 | 41.3 µs | 25.4 µs |
416
337
  | Crumbly JSON-LD | 287 | 43.3 µs | 29.5 µs |
417
338
 
418
- Most of the JSON-LD gap comes from Rails' `_url` helpers, which are slower than `_path` ones: building the
419
- `BreadcrumbList` from the levels accounts for 1.7 µs of it.
339
+ Crumbly's JSON-LD is a little slower, mostly because Rails' `_url` helpers are slower than `_path` ones. Building
340
+ the `BreadcrumbList` from the levels takes 1.7 µs of the difference.
420
341
 
421
342
  ```sh
422
343
  bundle exec ruby bench/render.rb
423
344
  bundle exec ruby --yjit bench/render.rb
424
345
  ```
425
346
 
347
+ ## How Crumbly is tested
348
+
349
+ CI runs the test suite on Ruby 3.3, 3.4 and 4.0, each against Rails 8.0 and 8.1, and on `ruby-head`. The
350
+ tests convert a sample gretel file, compare the result with the expected class line for line, then draw its trails
351
+ with gretel and with the converted class and check that the labels and URLs match. The production paths (an unknown crumb, a relative JSON-LD URL) are tested
352
+ as well as the raising ones.
353
+
426
354
  ## Development
427
355
 
428
356
  ```sh
@@ -430,26 +358,27 @@ bundle install
430
358
  bundle exec rake test # latest Rails
431
359
  BUNDLE_GEMFILE=gemfiles/rails_8_0.gemfile bundle exec rake test # Rails 8.0
432
360
  bundle exec rubocop
361
+ bundle exec rake docs:highlight # after editing a code block in docs/
433
362
  ```
434
363
 
364
+ [CONTRIBUTING.md](CONTRIBUTING.md) says what a pull request needs.
365
+
435
366
  ### Releasing
436
367
 
437
- Pull requests leave `CHANGELOG.md` alone: a release starts by writing its notes under `## [Unreleased]`, from the
438
- pull requests merged since the last tag, without committing them. Then, from an up-to-date `main` whose CI is
439
- green:
368
+ Pull requests don't touch `CHANGELOG.md`. A release starts by writing its notes under `## [Unreleased]`, from the
369
+ pull requests merged since the last tag, without committing them. Then, from an up-to-date `main` with green CI:
440
370
 
441
371
  ```sh
442
- bin/release minor --dry-run # the notes and the changes, nothing written
372
+ bin/release minor --dry-run # shows the notes and the changes, writes nothing
443
373
  bin/release minor # or patch, major, or an exact version such as 1.2.0
444
374
  ```
445
375
 
446
- `main` takes no direct push, so `bin/release` dates the Unreleased section and bumps the version on a branch
447
- `release/vX.Y.Z`, opens its pull request, which merges itself once CI is green, and waits for it. It then pushes a
448
- signed tag `vX.Y.Z` on the merge commit (`bin/release --tag X.Y.Z` does it if you stopped waiting). The tag starts
449
- the Release workflow, which publishes the gem to RubyGems through trusted publishing and creates the GitHub release
450
- with the version's notes and the `.gem`.
376
+ `bin/release` bumps the version on a `release/vX.Y.Z` branch, opens its pull request, waits for it to merge
377
+ itself once CI is green, and pushes a signed tag `vX.Y.Z` on the merge commit (`bin/release --tag X.Y.Z` resumes
378
+ this step if you stopped it). The tag starts the Release workflow, which publishes the gem to RubyGems through
379
+ trusted publishing and creates the GitHub release.
451
380
 
452
381
  ## License
453
382
 
454
- MIT, by Level UP Solutions. Crumbly keeps the idea of [gretel](https://github.com/kzkn/gretel), by Lasse Bunk and
455
- Kazuki Nishikawa: a crumb names its parent.
383
+ MIT, by Level UP Solutions. The idea of a crumb that names its parent comes from
384
+ [gretel](https://github.com/kzkn/gretel), by Lasse Bunk and Kazuki Nishikawa.
@@ -450,12 +450,12 @@ module Crumbly
450
450
  end
451
451
 
452
452
  def loose_comments
453
- source.comments.filter_map do |comment|
453
+ source.comments.flat_map do |comment|
454
454
  offset = comment.location.start_offset
455
- next unless offset.between?(block.location.start_offset, block.location.end_offset)
456
- next if copied_ranges.any? { |range| range.cover?(offset) }
455
+ next [] unless offset.between?(block.location.start_offset, block.location.end_offset)
456
+ next [] if copied_ranges.any? { |range| range.cover?(offset) }
457
457
 
458
- comment.slice.rstrip
458
+ Source.comment_text(comment)
459
459
  end
460
460
  end
461
461
 
@@ -35,9 +35,16 @@ module Crumbly
35
35
  end
36
36
 
37
37
  def comment_lines(from_offset, to_offset)
38
- comments.filter_map do |comment|
39
- comment.slice.rstrip if comment.location.start_offset.between?(from_offset, to_offset - 1)
40
- end
38
+ comments.select { |comment| comment.location.start_offset.between?(from_offset, to_offset - 1) }
39
+ .flat_map { |comment| self.class.comment_text(comment) }
40
+ end
41
+
42
+ # The lines of a comment. An =begin block must start at column 0, which the class body indents: its lines
43
+ # become # comments.
44
+ def self.comment_text(comment)
45
+ return [comment.slice.rstrip] unless comment.is_a?(Prism::EmbDocComment)
46
+
47
+ comment.slice.lines[1...-1].map { |line| "# #{line.rstrip}".rstrip }
41
48
  end
42
49
 
43
50
  # Blanks everything before the expanded text, so that its lines and columns stay those of this file.
@@ -224,7 +224,11 @@ module Crumbly
224
224
  end
225
225
  end
226
226
 
227
- def substitutions(node, value_by_name, depth = 0, edits = [])
227
+ # A string's interpolated value is written as text when only a plain string or symbol reads it: in a regexp,
228
+ # a command, a %W array or after a delimiter such as %Q/, the same text would mean something else.
229
+ INLINE_OPENING = /\A(?::?"|<<|%Q?[(\[{<])/
230
+
231
+ def substitutions(node, value_by_name, depth = 0, edits = [], inline: false)
228
232
  case node
229
233
  when Prism::LocalVariableReadNode
230
234
  value = value_by_name[node.name] if node.depth == depth
@@ -236,17 +240,21 @@ module Crumbly
236
240
  return edits << [node.location.start_offset, node.location.end_offset, text.inspect]
237
241
  end
238
242
  when Prism::EmbeddedStatementsNode
239
- if node in {statements: {body: [Prism::LocalVariableReadNode[depth: ^depth, name:]]}}
243
+ if inline && (node in {statements: {body: [Prism::LocalVariableReadNode[depth: ^depth, name:]]}})
240
244
  text = value_by_name[name]&.text
241
245
  if text&.match?(%r{\A[\w ./-]*\z})
242
246
  edits << [node.location.start_offset, node.location.end_offset, text]
243
247
  return edits
244
248
  end
245
249
  end
250
+ when Prism::InterpolatedStringNode, Prism::InterpolatedSymbolNode
251
+ inline = INLINE_OPENING.match?(node.opening.to_s)
252
+ when Prism::InterpolatedRegularExpressionNode, Prism::InterpolatedMatchLastLineNode, Prism::InterpolatedXStringNode
253
+ inline = false
246
254
  when Prism::BlockNode, Prism::LambdaNode then depth += 1
247
255
  when Prism::DefNode then return edits
248
256
  end
249
- node&.compact_child_nodes&.each { |child| substitutions(child, value_by_name, depth, edits) }
257
+ node&.compact_child_nodes&.each { |child| substitutions(child, value_by_name, depth, edits, inline:) }
250
258
  edits
251
259
  end
252
260
 
@@ -25,8 +25,8 @@ module Crumbly
25
25
  def self.call_sites(path)
26
26
  action = File.basename(path).split(".").first
27
27
  controller_name = File.basename(File.dirname(path))
28
- File.foreach(path).with_index(1).filter_map do |line, number|
29
- match = BREADCRUMB_CALL.match(line)
28
+ File.foreach(path, encoding: Encoding::UTF_8).with_index(1).filter_map do |line, number|
29
+ match = BREADCRUMB_CALL.match(line.scrub)
30
30
  reason = match && reason(match[:target], match[:arguments].strip.delete_suffix(")").strip, action, controller_name)
31
31
  CallSite.new(path:, line: number, code: match[0].strip, reason:) if reason
32
32
  end
@@ -12,4 +12,6 @@ module Crumbly
12
12
  class InvalidTrail < Error; end
13
13
 
14
14
  class RelativeUrl < Error; end
15
+
16
+ class UnsafeUrl < Error; end
15
17
  end
@@ -8,7 +8,8 @@ require "loofah"
8
8
  module Crumbly
9
9
  # A schema.org BreadcrumbList, as Google's Rich Results test reads it.
10
10
  module JsonLd
11
- ABSOLUTE_URL_PREFIXES = ["https://", "http://"].freeze
11
+ # A scheme is case-insensitive: HTTPS://example.com is absolute too.
12
+ ABSOLUTE_URL = %r{\Ahttps?://}i
12
13
 
13
14
  class << self
14
15
  def call(levels)
@@ -19,7 +20,7 @@ module Crumbly
19
20
 
20
21
  list_item = {"@type" => "ListItem", "position" => list_items.size + 1, "name" => plain_text(level.label)}
21
22
  if level.url
22
- return relative_url(level) unless level.url.start_with?(*ABSOLUTE_URL_PREFIXES)
23
+ return relative_url(level) unless ABSOLUTE_URL.match?(level.url)
23
24
 
24
25
  list_item["item"] = level.url
25
26
  end
@@ -32,10 +33,13 @@ module Crumbly
32
33
 
33
34
  private
34
35
 
36
+ # A label read from bytes that are not UTF-8 gets replacement characters, instead of failing the page.
35
37
  def plain_text(label)
36
- return label.to_s.squish unless label.html_safe?
38
+ text = label.to_s
39
+ text = text.scrub unless text.valid_encoding?
40
+ return text.squish unless label.html_safe?
37
41
 
38
- Loofah.html5_fragment(label).scrub!(:prune).text(encode_special_chars: false).squish
42
+ Loofah.html5_fragment(text).scrub!(:prune).text(encode_special_chars: false).squish
39
43
  end
40
44
 
41
45
  def relative_url(level)
data/lib/crumbly/trail.rb CHANGED
@@ -4,6 +4,9 @@ module Crumbly
4
4
  # One subclass per namespace (Admin::Breadcrumbs < Crumbly::Trail): each public method defined there is a crumb.
5
5
  class Trail
6
6
  RouteParent = Data.define(:name, :id, :record)
7
+ # Browsers drop leading spaces and control characters, and tabs and newlines anywhere: "java\tscript:" runs.
8
+ IGNORED_URL_CHARACTERS = /\A[\x00-\x20]+|[\t\n\r]/
9
+ UNSAFE_URL_SCHEME = /\A(?:javascript|vbscript|data):/i
7
10
 
8
11
  # Included after the routes' url_helpers, whose own url_options would otherwise win.
9
12
  module UrlOptionsFromView
@@ -34,6 +37,18 @@ module Crumbly
34
37
  raise DuplicateCrumb, "#{self}##{name} is defined twice: the second definition would replace the first"
35
38
  end
36
39
 
40
+ def derive_trails(derive)
41
+ raise ArgumentError, "derive_trails takes true or false, not #{derive.inspect}" unless derive in true | false
42
+
43
+ @derive_trails = derive
44
+ end
45
+
46
+ def derive_trails?
47
+ return @derive_trails unless @derive_trails.nil?
48
+
49
+ self == Trail || superclass.derive_trails?
50
+ end
51
+
37
52
  def crumb?(name)
38
53
  trail_class = self
39
54
  while trail_class < Trail
@@ -49,6 +64,8 @@ module Crumbly
49
64
  end
50
65
 
51
66
  def derive(helpers)
67
+ return [] unless derive_trails?
68
+
52
69
  new(helpers).send(:derived_levels)
53
70
  end
54
71
  end
@@ -62,6 +79,10 @@ module Crumbly
62
79
  attr_reader :helpers
63
80
 
64
81
  def crumb(label, url = nil, parent: nil, links: [])
82
+ unless parent.nil? || parent.is_a?(Crumb)
83
+ raise ArgumentError, "parent: takes a crumb, such as parent: orders, not #{parent.inspect}"
84
+ end
85
+
65
86
  Crumb.new(label:, url: path_for(url), links:, parent:)
66
87
  end
67
88
 
@@ -74,16 +95,39 @@ module Crumbly
74
95
  name = crumb_name_for(record)
75
96
  return public_send(name, record, *) if name
76
97
 
77
- unknown_crumb("#{self.class} has no crumb for #{record.class}: define ##{record.model_name.singular}")
98
+ unknown_crumb(unknown_record_message(record))
99
+ end
100
+
101
+ # `breadcrumb @order` before the controller loads @order passes nil: it is reported like an unknown crumb.
102
+ def unknown_record_message(record)
103
+ if record.class.respond_to?(:model_name)
104
+ "#{self.class} has no crumb for #{record.class}: define ##{record.model_name.singular}"
105
+ else
106
+ "#{self.class} has no crumb for #{record.nil? ? "nil" : "a #{record.class}"}: pass a crumb name or a record"
107
+ end
78
108
  end
79
109
 
80
110
  def path_for(url)
81
111
  case url
82
- when nil, String then url
112
+ when nil then nil
113
+ when String then safe_url(url)
83
114
  else polymorphic_path(url)
84
115
  end
85
116
  end
86
117
 
118
+ # A URL built from user input can run a script once a layout links it: the level keeps its label, not the link.
119
+ def safe_url(url)
120
+ return url if url.start_with?("/", "https://", "http://") || !url.include?(":")
121
+ return url unless UNSAFE_URL_SCHEME.match?(url.gsub(IGNORED_URL_CHARACTERS, ""))
122
+
123
+ exception = UnsafeUrl.new("#{self.class} links to #{url.inspect}, which a browser runs as a script: " \
124
+ "check its scheme before passing it to a crumb")
125
+ raise exception if Crumbly.raise_on_unsafe_url?
126
+
127
+ ActiveSupport.error_reporter.report(exception, handled: true)
128
+ nil
129
+ end
130
+
87
131
  def levels_for(target, arguments)
88
132
  levels(target_crumb(target, arguments))
89
133
  end
@@ -121,6 +165,8 @@ module Crumbly
121
165
  # STI: a subclass without a crumb of its own falls back on its parent class's.
122
166
  def crumb_name_for(record)
123
167
  model_class = record.class
168
+ return unless model_class.respond_to?(:model_name)
169
+
124
170
  loop do
125
171
  name = model_class.model_name.singular.to_sym
126
172
  return name if self.class.crumb?(name)
@@ -164,7 +210,14 @@ module Crumbly
164
210
  def record_crumb(record)
165
211
  return crumb_for(record) if crumb_name_for(record)
166
212
 
167
- crumb(record.to_s, route_path(action: "show", id: record), parent: collection_crumb)
213
+ crumb(record_label(record), route_path(action: "show", id: record), parent: collection_crumb)
214
+ end
215
+
216
+ # Kernel#to_s would label the level "#<Invoice:0x000...>".
217
+ def record_label(record)
218
+ return record.to_s unless record.class.instance_method(:to_s).owner == Kernel && record.class.respond_to?(:model_name)
219
+
220
+ "#{record.model_name.human} #{record.to_param}"
168
221
  end
169
222
 
170
223
  def new_record_crumb
@@ -203,7 +256,7 @@ module Crumbly
203
256
  return crumb_for(parent.record) if crumb_name_for(parent.record)
204
257
 
205
258
  name = parent.name.pluralize
206
- crumb(parent.record.to_s, route_path(resources: name, action: "show", id: parent.id, **route_parent_ids(ancestors)),
259
+ crumb(record_label(parent.record), route_path(resources: name, action: "show", id: parent.id, **route_parent_ids(ancestors)),
207
260
  parent: nested_collection_crumb(name, ancestors))
208
261
  end
209
262
 
@@ -88,7 +88,9 @@ module Crumbly
88
88
  def verify_sources
89
89
  defined_names = trail_classes.flat_map { |trail_class| crumb_names(trail_class) }.to_set
90
90
  source_files.each do |path|
91
- File.foreach(path).with_index(1) do |line, number|
91
+ # An image or a Latin-1 template is read too: an invalid byte cannot fail the verification.
92
+ File.foreach(path, encoding: Encoding::UTF_8).with_index(1) do |line, number|
93
+ line = line.scrub
92
94
  line.to_enum(:scan, BREADCRUMB_CALL).each do
93
95
  match = Regexp.last_match
94
96
  symbol, string, instance_variable = match.captures
@@ -163,8 +165,9 @@ module Crumbly
163
165
  end
164
166
 
165
167
  def dead_crumbs
166
- reachable_names = called_names + derived_names
168
+ reachable_names_with_derivation = called_names + derived_names
167
169
  trail_classes.flat_map do |trail_class|
170
+ reachable_names = trail_class.derive_trails? ? reachable_names_with_derivation : called_names
168
171
  dead_names = crumb_names(trail_class).reject do |name|
169
172
  reachable_names.include?(name) || model_name?(name)
170
173
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Crumbly
4
- VERSION = "2.0.0"
4
+ VERSION = "2.2.0"
5
5
  end
@@ -2,7 +2,8 @@
2
2
 
3
3
  module Crumbly
4
4
  module ViewHelpers
5
- # The view names its crumb; a view that says nothing gets the trail derived from its controller and action.
5
+ # The view names its crumb; a view that says nothing gets the trail derived from its controller and action,
6
+ # or none under `derive_trails false`.
6
7
  def breadcrumb(target, *arguments)
7
8
  @crumbly_breadcrumb = [target, arguments]
8
9
  @crumbly_trail = nil
data/lib/crumbly.rb CHANGED
@@ -20,7 +20,7 @@ require_relative "crumbly/railtie" if defined?(Rails::Railtie)
20
20
 
21
21
  module Crumbly
22
22
  class << self
23
- attr_writer :routes, :raise_on_unknown_crumb, :raise_on_relative_url
23
+ attr_writer :routes, :raise_on_unknown_crumb, :raise_on_relative_url, :raise_on_unsafe_url
24
24
 
25
25
  def routes
26
26
  @routes || (Rails.application&.routes if defined?(Rails.application))
@@ -38,6 +38,12 @@ module Crumbly
38
38
  !production?
39
39
  end
40
40
 
41
+ def raise_on_unsafe_url?
42
+ return @raise_on_unsafe_url unless @raise_on_unsafe_url.nil?
43
+
44
+ !production?
45
+ end
46
+
41
47
  # Raises InvalidTrail with every problem found, and returns the dead crumbs ("Admin::Breadcrumbs#drafts").
42
48
  def verify!(trail_classes: nil, routes: Crumbly.routes, sources: default_sources)
43
49
  Rails.application.eager_load! if trail_classes.nil? && defined?(Rails.application) && Rails.application
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: crumbly
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.0.0
4
+ version: 2.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Level UP Solutions
@@ -43,17 +43,18 @@ dependencies:
43
43
  requirements:
44
44
  - - ">="
45
45
  - !ruby/object:Gem::Version
46
- version: '2.21'
46
+ version: 2.25.3
47
47
  type: :runtime
48
48
  prerelease: false
49
49
  version_requirements: !ruby/object:Gem::Requirement
50
50
  requirements:
51
51
  - - ">="
52
52
  - !ruby/object:Gem::Version
53
- version: '2.21'
54
- description: One class of plain Ruby methods per namespace, a trail derived from the
55
- controller and the routes when a view says nothing, mistakes raised when the class
56
- loads, and the trail returned as data for your own components.
53
+ version: 2.25.3
54
+ description: Each level of a breadcrumb trail is a Ruby method that names its parent.
55
+ When a view names no crumb, Crumbly works the trail out from the controller and
56
+ the routes, and one test checks every trail in the app. The trail comes back as
57
+ data, so your layout writes the HTML.
57
58
  executables:
58
59
  - crumbly-convert
59
60
  extensions: []
@@ -103,8 +104,8 @@ required_rubygems_version: !ruby/object:Gem::Requirement
103
104
  - !ruby/object:Gem::Version
104
105
  version: '0'
105
106
  requirements: []
106
- rubygems_version: 4.0.24
107
+ rubygems_version: 4.0.20
107
108
  specification_version: 4
108
- summary: 'Breadcrumbs for Rails: namespaced, derived from your routes, checked in
109
- tests'
109
+ summary: Breadcrumb trails for Rails, written as plain Ruby methods and checked in
110
+ tests
110
111
  test_files: []