ruby2html 2.0.0 → 2.1.1

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: 5ba119a7769924fec25bf5a7b80128f2086dd82fc3c81bd60b0d817e19a8232f
4
- data.tar.gz: b4decdfd8c01b34813e0d092de84d90abc64bbf78417ab38f4ff3e44719e3ac5
3
+ metadata.gz: 8c9414914d7c75eb9597a47b12bb7f2c7b9a8ca32d61080d729fa404bf0ab287
4
+ data.tar.gz: f789e9ad4275dcf7a560ec8666f3768a82d34108a9673eb36897a8ee47fe1cc6
5
5
  SHA512:
6
- metadata.gz: 3e93a318476275d137fab0f8149df9ac26a9bdf78e6ddd23b63b630ee662d1e4f87aaa039b22f7f8dd3ebef1a38c334423714ebc3544e2d8cd02869574da5d69
7
- data.tar.gz: 5b57bb1eda59d05452e12c7b43161d3b210fd063c597f7ad42c3ccb1320b48fc5378ea2771ebc9a1185384e4ed29eb97e2e7372c697d235d33cbb1c6e93a979a
6
+ metadata.gz: 86c7d10f052c651d73d9b10f7136df9a46f426775157cb2aaab91e41685d3176e69d8f6e90547daed3f9ba8395b98df51e72cda34e2f7dfe897f4b5662256203
7
+ data.tar.gz: 74d0d49bc5280d5eb27549bf732888ce04ef31b3fd453225142b4d3eb4ffb4329742717cc64631c2478937b3c37aa02a871c7355fd7ce05787cfb1aa21988efd
data/CHANGELOG.md CHANGED
@@ -6,6 +6,38 @@ Entries before 1.6.6 were reconstructed from `git log` and RubyGems release date
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [2.1.1] - 2026-11-23
10
+
11
+ ### Changed
12
+
13
+ - Documentation: the performance claims now say what the CI benchmarks measure. The README, `llms.txt` and earlier release notes called ruby2html faster than ERB; on the standalone page render Erubi (compiled ERB) is about 1.3x to 1.5x faster than ruby2html, in a full Rails request ERB, Slim and ruby2html are within runner noise of each other, and ruby2html is ahead of Phlex in both. The README also gains an "Escaping and security" section and a CI-backed compatibility table (CRuby 3.1 and later, not only 3.3+; JRuby and TruffleRuby run the renderer specs, not the Rails ones), and `llms.txt` follows the llmstxt.org layout and no longer shows `Render.new(ctx) { h1 title }`, where `title` is the `<title>` tag rather than the context method.
14
+ - CI now audits every matrix entry's resolved dependency set against the Ruby advisory database — the `audit` job only checked the committed root `Gemfile.lock`, which keeps its own `bundle-audit` job. The matrix jobs install an unlocked gemfile, so Bundler resolves it during the job and writes the lockfile next to it (`gemfiles/standalone.gemfile.lock`, `gemfiles/rails.gemfile.lock`); the audit of that resolved lockfile rides on `rake compile` (`audit:advisories` → `bin/audit-advisories`), the task every matrix entry already runs, so each entry audits the set it actually installed, in the job that installed it. An advisory now fails the matrix entry and, with it, the aggregate `CI OK` job — except the advisories of the floor lines the matrix resolves on purpose (Rails 7.2.x, Active Support 7.2.x on Ruby 3.1, where Active Support 8 does not install): upstream patches those lines no more, so they are listed by advisory id in `bin/audit-advisories` and accepted only when the lockfile resolves the exact reviewed version (the five Rails-line components at 7.2.3, pinned by the rails 7.2 gem; Active Support, which the standalone gemfile on Ruby 3.1 resolves unlocked, additionally at 7.2.4 — that patch fixes three of its four advisories, while the `safe_constantize` DoS (`GHSA-8474-xrp6-wh69`) is fixed only in the 8.x lines) — a moved resolution drops every exception and fails the audit until the list is re-reviewed. The audit also rides on the `spec` tasks, so `SKIP_COMPILE=1` (strict extension builds, the pure-Ruby fallback) cannot drop it, and a signal-killed `bundle-audit` is reported as killed instead of looking like an advisory result. Every other line (Rails 8.0, 8.1, Active Support 8) is audited without any exception, and an advisory that is not listed still fails the entry.
15
+ - CI runs the Rails integration specs on the pure-Ruby renderer too (`RUBY2HTML_DISABLE_EXT=1`, every Rails line) and on JRuby (job `rails-jruby`, one Rails line: `activerecord-jdbcsqlite3-adapter` replaces sqlite3 and has no release for newer lines yet; view_component stays below 4.16 there, which calls `Ractor` at boot).
16
+ - The gem's RubyGems summary and description now describe what it does (block DSL, escaping by default, Rails/ViewComponent integration, C extension with a pure-Ruby fallback) instead of "C-optimized performance" and "automatic HTML beautification" (only an optional development middleware).
17
+
18
+ ### Fixed
19
+
20
+ - Appending a renderer's own output buffer to itself (`plain(current_output)`, `component(current_output)`) could read freed memory with the C extension: growing the buffer while its own bytes were still being read moved them out from under the read, which aborted under ASAN in the sanitizer CI job and could crash or corrupt output anywhere. Escaped and raw appends (`r2h_append_escaped`, `r2h_append_raw`) now duplicate the string first when it is the buffer; the pure-Ruby renderer was never affected, and output stays byte-identical (pinned by the new "can append the output buffer to itself" example, which runs against both implementations).
21
+ - Attribute names had the same hole: writing a name that is the output buffer itself (`div current_output => true`) could read the name after the buffer moved while it was copied; the name is now duplicated first too.
22
+ - Strict-locals `.html.rb` templates (`# locals: (title:)`) rendered locals named like tags as empty tags: `h2 title` became `<title></title><h2></h2>`, because ActionView reports no locals for them and the compiler then rewrote `title` into the `<title>` tag. The local names now come from the magic comment's parameter list.
23
+ - A block given to `render` from Ruby2html code landed outside the rendered output: `render(SomeViewComponent.new) { b 'x' }` inside a `Ruby2html::Component` or a `ComponentHelper#html` block emitted `<b>x</b>` before the component's markup, and `render(SomeRuby2htmlComponent.new) { ... }` inside `html { }` did the same. The block is now captured into the component, as in `.html.rb` templates. Blocks given to a `Ruby2html::Component` from `.html.rb` templates or other components now also follow ActionView's capture rule: they receive the component, a String they only return becomes (escaped) content instead of being dropped, and their markup lands where the component calls `content`, even inside its own `link_to` block.
24
+ - Fragment-cache digests ignored the partials an `.html.rb` template renders (no dependency tracker was registered for the `.rb` handler), so editing such a partial left stale `cache` fragments behind. The handler now registers ActionView's `RubyTracker`.
25
+ - The pure-Ruby renderer (JRuby, TruffleRuby, `RUBY2HTML_DISABLE_EXT=1`) diverged from the C extension on hostile or unusual input; a new differential fuzz spec (`spec/gem/render_fuzz_spec.rb`: random bytes in six encodings, markup characters in attribute names, nested `data:` hashes, odd `#to_s`/`#html_safe?` objects, raising blocks, swapped buffers) now requires byte-identical output, encodings and error messages. Fixed on the pure-Ruby side: an object whose `#to_s` returns no String (or is private) raised `NoMethodError` instead of rendering like string interpolation does; a `BasicObject` returned from a block, given as an attribute value or a token raised a different error; `true`/`false` attributes whose names hold invalid UTF-8 raised `ArgumentError`; US-ASCII strings holding UTF-8 bytes (strings read under `LANG=C`) could switch the output buffer to US-ASCII and then fail with `Encoding::CompatibilityError`; a swapped-in `current_output` is now checked like the C extension does (a binary or US-ASCII buffer is relabelled UTF-8, another encoding or a non-String raises); `li text` with an untranscodable string no longer leaves `<li>` behind. On the C side: an invalid nested attribute name with invalid UTF-8 bytes raised "invalid byte sequence" instead of "invalid attribute name", and `Ruby2html.escape_html` labels US-ASCII input with non-ASCII bytes UTF-8, as it already did for binary input.
26
+ - `plain`, `component` and `Ruby2html.escape_html` raised `Ractor::UnsafeError` in a non-main Ractor with the C extension; they are now declared Ractor-safe (the tag methods already were).
27
+
28
+ ## [2.1.0] - 2026-10-31
29
+
30
+ ### Added
31
+
32
+ - JRuby now ships a small Java extension (`Ruby2html::JavaNative`) that accelerates HTML escaping — the renderer's hot path — over the pure-Ruby implementation. About 1.9x faster end-to-end rendering on JRuby; output is byte-identical. Distributed as a `ruby2html-<version>-java` platform gem with the jar prebuilt (no JDK needed to install); everything else stays pure Ruby.
33
+
34
+ ### Changed
35
+
36
+ - `Ruby2html::Component#render_in` accepts Rails' keyword options (`locals:`), as Rails main (8.2) passes them and deprecates `render_in` without options.
37
+ - TruffleRuby now uses the pure-Ruby implementation instead of the C extension. TruffleRuby runs C extensions through Sulong but JITs pure Ruby with Graal, which here renders ~28x faster; `Ruby2html.native?` is now `false` on TruffleRuby.
38
+ - On CRuby, a C extension that fails to load now prints one warning with the reason (`ruby2html: C extension not loaded (...); using the pure-Ruby renderer`) instead of silently rendering about 3x slower. JRuby/TruffleRuby and `RUBY2HTML_DISABLE_EXT=1` stay silent.
39
+ - Development and single-version CI jobs now run on the latest stable Ruby (4.0). The CRuby test matrix already tracks the official maintained-versions list automatically (currently 3.3, 3.4, 4.0).
40
+
9
41
  ## [2.0.0] - 2026-10-31
10
42
 
11
43
  A rewrite of the renderer for speed, memory and correctness, plus a new component class, Rails 8.1 / ViewComponent 4 support, JRuby/TruffleRuby support and full CI/release automation. **Contains breaking changes: read "Upgrading to 2.0" below.**
@@ -170,7 +202,9 @@ Published to RubyGems; no separate commits in the repository history.
170
202
  ### Added
171
203
  - Initial release: `Ruby2html::Render` DSL, `Ruby2html::RailsHelper#html` for ERB.
172
204
 
173
- [Unreleased]: https://github.com/sebyx07/ruby2html/compare/v2.0.0...HEAD
205
+ [Unreleased]: https://github.com/sebyx07/ruby2html/compare/v2.1.1...HEAD
206
+ [2.1.1]: https://github.com/sebyx07/ruby2html/compare/v2.1.0...v2.1.1
207
+ [2.1.0]: https://github.com/sebyx07/ruby2html/compare/v2.0.0...v2.1.0
174
208
  [2.0.0]: https://github.com/sebyx07/ruby2html/releases/tag/v2.0.0
175
209
  [1.6.6]: https://rubygems.org/gems/ruby2html/versions/1.6.6
176
210
  [1.6.4]: https://rubygems.org/gems/ruby2html/versions/1.6.4
data/README.md CHANGED
@@ -2,9 +2,12 @@
2
2
 
3
3
  [![CI](https://github.com/sebyx07/ruby2html/actions/workflows/ci.yml/badge.svg)](https://github.com/sebyx07/ruby2html/actions/workflows/ci.yml)
4
4
  [![Gem Version](https://img.shields.io/gem/v/ruby2html)](https://rubygems.org/gems/ruby2html)
5
+ [![Downloads](https://img.shields.io/gem/dt/ruby2html)](https://rubygems.org/gems/ruby2html)
6
+ [![License: MIT](https://img.shields.io/github/license/sebyx07/ruby2html)](LICENSE)
7
+ [![Ruby >= 3.1](https://img.shields.io/badge/ruby-%3E%3D%203.1-CC342D)](ruby2html.gemspec)
5
8
  [![Maintained by developerz.ai](https://img.shields.io/badge/maintained%20by-developerz.ai-6f42c1)](https://developerz.ai)
6
9
 
7
- Write views in pure Ruby; get escaped, compact HTML. A C extension handles escaping, attribute serialization and tag rendering. Works standalone, as Rails `.html.rb` templates, inside ERB, and in ViewComponent.
10
+ Write views in plain Ruby and get escaped, compact HTML. Every HTML5 tag is a method; a C extension does the escaping, attribute serialization and tag rendering, with a pure-Ruby implementation of the same output where the extension is not available. Works standalone, as Rails `.html.rb` templates, inside ERB, and in ViewComponent.
8
11
 
9
12
  ```ruby
10
13
  div class: 'card', 'data-controller': 'card' do
@@ -18,54 +21,45 @@ end
18
21
  <div class="card" data-controller="card"><h2>Lamp</h2><p>Warm &amp; bright</p><a href="/products/1" class="btn">Details</a></div>
19
22
  ```
20
23
 
21
- ## Why ruby2html
22
-
23
- - **Fastest Ruby HTML renderer we've measured.** The page benchmark renders 1.35x faster than Erubi (Rails' ERB engine) and 2.4–16x faster than Phlex 2, with 40–90% fewer allocations; in a full Rails request it leads ERB, Slim and Phlex ([numbers](#performance)).
24
- - **Light.** No runtime dependencies, a 32 KB gem, and `require 'ruby2html'` costs about 0.4 MB and 19 ms. Prism, the Rails glue and the optional beautifier load only when used, or at boot in eager-loading production apps.
25
- - **Plain Ruby views.** `.html.rb` templates, ERB interop, ViewComponent, or the built-in `Ruby2html::Component`. Escaped by default.
26
- - **Runs everywhere.** CRuby ≥ 3.1 with a C extension (SIMD escaping on x86_64 and arm64), and JRuby/TruffleRuby through a byte-identical pure-Ruby implementation. Rails 7.2+.
24
+ - **Plain Ruby views.** No template language: `if`, `each`, locals and methods are the control flow.
25
+ - **Escaped by default.** Text and attribute values are always escaped; raw HTML only from `html_safe` strings. See [Escaping and security](#escaping-and-security).
26
+ - **Light.** No runtime dependencies. `require 'ruby2html'` loads only the renderer; Prism, the Rails glue and the optional beautifier load on first use (or at boot in eager-loading production apps).
27
+ - **Measured.** Benchmarks against Erubi, Slim, Phlex and ViewComponent run in CI on every pull request. See [Performance](#performance) for what they show.
28
+ - **CRuby, JRuby, TruffleRuby.** All three run the same spec suite in CI. See [Compatibility](#compatibility).
27
29
  - **AI-ready.** One-file reference for coding agents: [`llms.txt`](llms.txt).
28
30
 
29
31
  ## Installation
30
32
 
31
- Supports all maintained CRuby versions (>= 3.1), JRuby (via the pure-Ruby implementation), TruffleRuby, and Rails 7.2+; the CI matrix is generated automatically.
32
-
33
33
  ```ruby
34
34
  # Gemfile
35
35
  gem 'ruby2html'
36
36
  ```
37
37
 
38
38
  ```bash
39
- bundle install # compiles the native extension (needs a C compiler); pure-Ruby fallback otherwise
39
+ bundle install
40
40
  ```
41
41
 
42
- ## AI agents
42
+ On CRuby the install compiles the C extension. Without a working C compiler the install still succeeds and the gem runs on its pure-Ruby renderer, about 2.5x slower on a full page render; `Ruby2html.native?` tells which one is loaded. Requires Ruby >= 3.1; the Rails integration requires Rails >= 7.2.
43
43
 
44
- **This project is maintained by [developerz.ai](https://developerz.ai).** Its maintainer agent triages issues, reviews every pull request, merges every pull request once its author marks it ready and CI passes, watches project health daily, and opens release PRs. The policy is in [`.dz/maintainer/maintainer.yml`](.dz/maintainer/maintainer.yml). Breaking changes and major releases stay with the owner.
44
+ ## Quick start
45
45
 
46
- - **Using ruby2html in your app?** Point your agent at [`llms.txt`](llms.txt), the complete reference in one file (DSL rules, escaping, Rails, components, forms, pitfalls). Paste this into your app's `CLAUDE.md` / `AGENTS.md`:
47
- ```markdown
48
- ## ruby2html views
49
- `*.html.rb` templates and `html do ... end` blocks use the ruby2html gem. Before editing them read
50
- https://github.com/sebyx07/ruby2html/blob/main/llms.txt
51
- ```
52
- - **Working on this repo?** [`AGENTS.md`](AGENTS.md) is the only agent-instructions file (`CLAUDE.md` is a symlink to it): commands, code map, invariants, how to verify a change, CI/release automation.
53
- - **Claude Code**: project skills in `.claude/skills/` (`release`, `benchmark`, `add-html-tag`, `review`, `debug-render`, `upgrade-deps`), read-only reviewer subagents in `.claude/agents/` (`perf-reviewer`, `xss-auditor`), and `.claude/settings.json` with a safe permission allowlist and a non-blocking recompile-reminder hook.
54
-
55
- ## Usage
56
-
57
- ### DSL basics
46
+ ### Standalone
58
47
 
59
- - Every HTML5 tag is a method (`div`, `p`, `ul`, `li`, `img`, `input`, ...), plus `turbo_frame` / `turbo_stream`.
60
- - `tag content, **attrs` or `tag(**attrs) { nested tags }`. Text and attribute values are HTML-escaped; numbers and symbols are converted (`td 42`).
61
- - Raw HTML only from `html_safe` strings (Rails helpers, `'<hr>'.html_safe`), as content or via `plain`. `plain 'text'` escapes.
62
- - Attributes: `'data-id': 1` or `data: { id: 1 }`, `class: ['btn', active && 'on']`, `disabled: true` → bare `disabled`, `nil`/`false` omitted.
48
+ ```ruby
49
+ require 'ruby2html'
63
50
 
64
- Full rules and pitfalls: [`llms.txt`](llms.txt).
51
+ Ruby2html::Render.new do # optional context object: its public methods and ivars become available
52
+ html do
53
+ head { title 'Ruby2html Example' }
54
+ body { h1 'Hello, World!' }
55
+ end
56
+ end.render
57
+ # => "<html><head><title>Ruby2html Example</title></head><body><h1>Hello, World!</h1></body></html>"
58
+ ```
65
59
 
66
60
  ### Rails views (`.html.rb`)
67
61
 
68
- File: `app/views/products/index.html.rb`
62
+ No setup beyond the Gemfile line. File: `app/views/products/index.html.rb`
69
63
 
70
64
  ```ruby
71
65
  div class: 'container' do
@@ -82,7 +76,19 @@ plain '<div>Inline html</div>'.html_safe
82
76
  render partial: 'shared/navbar'
83
77
  ```
84
78
 
85
- Controller instance variables are available. Partials can be `.html.rb` too. `link_to`, `image_tag`, `button_to`, `form_with` and `render` write their output directly; other helpers return a value you must output (`h1 t('.title')`, `plain some_safe_html_helper`).
79
+ The template runs in the view, so controller instance variables, locals, helpers and routes are available. Partials can be `.html.rb` too; layouts can stay ERB or Slim.
80
+
81
+ `link_to`, `button_to`, `image_tag`, `form_with`, `render`, `capture`, `content_for` and `provide` write their output themselves. Any other helper only returns a value, which you output: `h1 t('.title')`, `plain content_tag(:em, 'x')`. A bare `t('.title')` line renders nothing.
82
+
83
+ Forms use Rails' own `form_with` and `FormBuilder`:
84
+
85
+ ```ruby
86
+ form_with model: @user do |f|
87
+ f.label :email
88
+ f.text_field :email
89
+ f.submit 'Save'
90
+ end
91
+ ```
86
92
 
87
93
  ### Inside ERB
88
94
 
@@ -102,7 +108,7 @@ end
102
108
  end %>
103
109
  ```
104
110
 
105
- ERB, Slim and Ruby2html views, partials and components can be mixed freely, so adoption can be gradual.
111
+ ERB, Slim and Ruby2html views, partials and components can be mixed, so adoption can be gradual.
106
112
 
107
113
  ### ViewComponent
108
114
 
@@ -162,29 +168,14 @@ render CardComponent.new(title: 'Hi')
162
168
 
163
169
  Tag methods run on the component itself (no instance-variable copying); nested ruby2html components write into the parent's buffer.
164
170
 
165
- ### Forms
171
+ ### DSL in brief
166
172
 
167
- ```ruby
168
- form_with model: @user do |f|
169
- f.label :email
170
- f.text_field :email
171
- f.submit 'Save'
172
- end
173
- ```
174
-
175
- ### Without Rails
173
+ - Every HTML5 tag is a method (`div`, `p`, `ul`, `li`, `img`, `input`, ...), plus `turbo_frame` / `turbo_stream`. There are no SVG or MathML tag methods.
174
+ - `tag content, **attrs` or `tag(**attrs) { nested tags }`. Numbers and symbols are converted (`td 42`); `nil` renders nothing.
175
+ - Attributes: `'data-id': 1` or `data: { id: 1 }`, `class: ['btn', active && 'on']`, `disabled: true` → bare `disabled`, `nil`/`false` omitted.
176
+ - Void tags self-close: `img src: 'a.png'` → `<img src="a.png" />`.
176
177
 
177
- ```ruby
178
- require 'ruby2html'
179
-
180
- Ruby2html::Render.new do # optional context object: its public methods and ivars become available
181
- html do
182
- head { title 'Ruby2html Example' }
183
- body { h1 'Hello, World!' }
184
- end
185
- end.render
186
- # => "<html><head><title>Ruby2html Example</title></head><body><h1>Hello, World!</h1></body></html>"
187
- ```
178
+ Full rules, the Rails helper list and the pitfalls table: [`llms.txt`](llms.txt).
188
179
 
189
180
  ### Pretty HTML in development
190
181
 
@@ -194,59 +185,79 @@ end.render
194
185
  config.middleware.use Ruby2html::HtmlBeautifierMiddleware
195
186
  ```
196
187
 
188
+ ## Escaping and security
189
+
190
+ - **Text content is escaped**: `h1 '<b>'` → `<h1>&lt;b&gt;</h1>`. The five characters `& < > " '` become `&amp; &lt; &gt; &quot; &#39;`.
191
+ - **Attribute values are always escaped**: `div title: %q("><x>)` → `title="&quot;&gt;&lt;x&gt;"`.
192
+ - **Attribute names are validated**: a name with a space, quote, `=`, `<`, `>`, `/` or a control character raises `ArgumentError`.
193
+ - **Raw HTML is opt-in.** Only `html_safe` strings (Rails helpers' `SafeBuffer`, or `'<hr>'.html_safe`) are inserted unescaped, as content or through `plain`. `plain 'text'` escapes. `component(html)` appends its argument raw, always: pass it trusted HTML only, never user input.
194
+
195
+ What the gem does not do for you:
196
+
197
+ - **URLs are not checked.** `a 'x', href: user_url` renders a `javascript:` URL as given. Validate the scheme yourself.
198
+ - **Attribute names are not a safe place for user input.** `div(**params)` lets a user set `onclick`.
199
+ - **`script` and `style` content is escaped like any other text**, so inline JavaScript containing `<` or `&` comes out entity-encoded and will not run as written. Use `plain javascript_tag(...)`, or `plain` with trusted `html_safe` code.
200
+
201
+ The C extension and the pure-Ruby implementation are compared output for output by parity specs, JRuby (with its Java escaper) and TruffleRuby run the same renderer specs, and the C extension runs under ASAN and UBSAN in CI. To report a vulnerability, see [SECURITY.md](SECURITY.md).
202
+
197
203
  ## Performance
198
204
 
199
- Benchmarks run in CI on every push to `main` and every pull request ([`.github/workflows/benchmark.yml`](.github/workflows/benchmark.yml)): the latest run's summary page has the current table, and PRs get a sticky comment with the delta against `main`. Run them locally with `bundle exec rake bench` (standalone scripts in `bench/`) or `bundle exec rspec spec/benchmarks/` (request-level through the demo app, vs ERB, Slim, Phlex and ViewComponent).
205
+ The numbers are not copied here, because they go stale. The [benchmark workflow](https://github.com/sebyx07/ruby2html/actions/workflows/benchmark.yml) runs on every push to `main` and every pull request, on x86_64 and arm64: open the latest run for the current tables (job summary), and pull requests get a comment with the change against `main`.
206
+
207
+ What recent runs on `main` show, on CRuby without YJIT:
200
208
 
201
- ### Snapshot at 2.0.0 release (2026-10-31)
209
+ - **Standalone page render** ([`bench/render_bench.rb`](bench/render_bench.rb), a 100-item page): Erubi, the engine behind Rails' ERB, is the fastest, with ruby2html about 1.3x to 1.5x behind it. ruby2html is roughly 10x faster than Phlex and allocates the fewest objects per render of the three.
210
+ - **Full Rails requests** ([`spec/benchmarks/requests_spec.rb`](spec/benchmarks/requests_spec.rb), through the demo app): ERB, Slim, `.html.rb` templates, `Ruby2html::Component` and ViewComponent with ruby2html land within 10% to 15% of each other, in an order that changes between runs and architectures: that is the run-to-run noise of the hosted runners. Phlex was last in both, about 15% behind the ruby2html variants.
211
+ - **C extension vs pure Ruby**: about 2.5x on the page render. `escape_html` is 3x to 10x faster on strings with nothing to escape, the gap growing with length, and 1.4x to 2.7x on strings that need escaping.
202
212
 
203
- This is a dated snapshot. CI has the live numbers. Measured on Ruby 3.4.7 x86_64 on a busy machine (load average about 7), so read the ratios rather than the absolute figures.
213
+ So: ruby2html costs about the same as ERB or Slim in a real Rails request, and it is much faster than Phlex. It is not faster than compiled ERB at raw string building.
204
214
 
205
- **Page render** (`bench/render_bench.rb`, no Rails): a header with nav, 100 list items with links, images, attributes and escaped text, about 34 KB of HTML.
215
+ Run them yourself:
206
216
 
207
- | Engine | Renders/s | Time per render | Allocations per render |
208
- |---|---|---|---|
209
- | **ruby2html 2.0 (C extension)** | **2,676** | **0.37 ms** | **419** |
210
- | Erubi 1.x (Rails' ERB engine) | 1,988 (1.35x slower) | 0.50 ms | 713 |
211
- | ruby2html 2.0 (pure Ruby: JRuby, no compiler) | ~820 | ~1.2 ms | 1,029 |
212
- | Phlex 2.4, enlarged attribute cache¹ | ~1,250 (≈2.4x slower) | ~0.8 ms | 831 |
213
- | Phlex 2.4, defaults | 164 (16x slower) | 6.1 ms | 6,410 |
214
- | ruby2html 1.6.6 | ~620 | ~1.6 ms | 3,531 |
217
+ ```bash
218
+ bundle exec rake bench # bench/*.rb: page render, per-tag cost, escaping
219
+ bundle exec rspec spec/benchmarks/ # full Rails requests (several minutes)
220
+ ```
215
221
 
216
- ¹ Phlex 2's default attribute cache (2 KB, FIFO) misses on per-row values such as ids and hrefs. `Phlex::ATTRIBUTE_CACHE.expand(1_000_000)` is its best case. Phlex 2 also checks URLs for `javascript:`; ruby2html leaves URL validation to you.
222
+ `RUBY2HTML_DISABLE_EXT=1` runs the pure-Ruby implementation; rebuilding with `RUBY2HTML_NO_SIMD=1` gives the scalar escaping path.
217
223
 
218
- **Full Rails request** (`spec/benchmarks/requests_spec.rb`; Rails 8.1, a 7 ms request where most of the time is Rails itself; differences are within ±15% error):
224
+ How the C extension keeps the cost down:
219
225
 
220
- | Engine | Requests/s |
226
+ - **Tag methods in C**: each tag writes open tag, content or block output and close tag straight into one shared buffer.
227
+ - **Escaping**: a 16-byte SSE2 (x86_64) or NEON (arm64) scan for `& < > " '`; clean strings are one `memcpy`, dirty strings get their exact size computed once.
228
+ - **Attributes**: written directly into the buffer, with no intermediate strings and no cache.
229
+ - **Templates and components**: `.html.rb` templates are rewritten at compile time (Prism) to run in the view itself, and `Ruby2html::Component` runs tag methods on the component, so neither copies instance variables or goes through `method_missing` per render.
230
+
231
+ ## Compatibility
232
+
233
+ Everything here is a CI job in [`ci.yml`](.github/workflows/ci.yml), and all of them gate merges:
234
+
235
+ | | What CI runs |
221
236
  |---|---|
222
- | **`Ruby2html::Component`** | **144.5** |
223
- | **ViewComponent 4 + ruby2html** | **142.2** |
224
- | **`.html.rb` template** | **139.6** |
225
- | Slim | 128.3 |
226
- | ERB | 122.6 |
227
- | Phlex 2.4 | 116.6 |
237
+ | CRuby | Every release from 3.1 (the gemspec floor) to the latest. The matrix is generated, so new Ruby releases are picked up without edits. |
238
+ | C extension | Linux x86_64 (SSE2), Linux arm64 and macOS arm64 (NEON); gcc and clang with `-Werror`; ASAN + UBSAN. |
239
+ | Pure Ruby | The gem specs and the Rails integration specs with `RUBY2HTML_DISABLE_EXT=1`. |
240
+ | JRuby | The gem specs, the Rails integration specs on one Rails line (the newest `activerecord-jdbcsqlite3-adapter` supports), and an install of the packaged `-java` gem. JRuby runs the pure-Ruby implementation with a prebuilt Java escaper (no JDK needed to install). |
241
+ | TruffleRuby | The gem specs without Rails, and an install of the packaged gem. TruffleRuby runs the pure-Ruby implementation; the C extension is deliberately not built there. |
242
+ | Rails | Every stable minor from 7.2, generated from RubyGems. |
228
243
 
229
- **HTML escaping** (SIMD vs scalar): up to 5.9x faster on 10 KB clean text, about 2x on 200-byte strings; short strings take the scalar path.
244
+ The Rails integration is tested on every Rails line with CRuby, on one line with JRuby, and not on TruffleRuby (its job runs the renderer specs only). `.html.rb` templates are compiled with Prism (in the standard library from Ruby 3.3; add the `prism` gem on older Rubies, or templates run on the slower 1.x path).
230
245
 
231
- **Footprint:**
246
+ ## AI agents
232
247
 
233
- | | Ruby/C lines | Runtime dependencies | `require` cost |
234
- |---|---|---|---|
235
- | **ruby2html** | 1.1k Ruby + 0.8k C | none | ~0.4 MB, ~19 ms |
236
- | phlex + phlex-rails | 6.2k | refract, zeitwerk, railties | ~1.4 MB, ~30 ms (phlex alone) |
237
- | view_component | 5.3k | actionview, activesupport, prism | |
238
- | slim | 7.3k | temple, tilt | |
248
+ **This project is maintained by [developerz.ai](https://developerz.ai).** Its maintainer agent triages issues, reviews every pull request, merges every pull request once its author marks it ready and CI passes, watches project health daily, and opens release PRs. The policy is in [`.dz/maintainer/maintainer.yml`](.dz/maintainer/maintainer.yml). Breaking changes and major releases stay with the owner.
239
249
 
240
- How it is fast:
250
+ - **Using ruby2html in your app?** Point your agent at [`llms.txt`](llms.txt), the complete reference in one file (DSL rules, escaping, Rails, components, forms, pitfalls). Paste this into your app's `CLAUDE.md` / `AGENTS.md`:
251
+ ```markdown
252
+ ## ruby2html views
253
+ `*.html.rb` templates and `html do ... end` blocks use the ruby2html gem. Before editing them read
254
+ https://github.com/sebyx07/ruby2html/blob/main/llms.txt
255
+ ```
256
+ - **Working on this repo?** [`CLAUDE.md`](CLAUDE.md) holds the agent instructions (`AGENTS.md` points at the same file): commands, code map, invariants, how to verify a change. Claude Code skills and reviewer subagents live in `.claude/`.
241
257
 
242
- - **Tag methods in C**: each tag writes open tag, content/block output and close tag straight into one shared buffer (no nested buffers, no `*args`/`**kwargs` allocation without keywords).
243
- - **HTML escaping**: 16-byte SSE2/NEON scan for `& < > " '`; clean strings are one `memcpy`, dirty strings get their exact size computed once.
244
- - **Attributes**: written directly into the buffer, no intermediate strings, no cache to thrash or leak.
245
- - **Lazy loading**: `require 'ruby2html'` loads only the renderer. Production Rails apps load everything at boot, so forked workers share it copy-on-write.
246
- - **Templates and components**: `.html.rb` templates are rewritten at compile time (Prism) to run in the view itself; `Ruby2html::Component` runs tag methods on the component. No instance-variable copying or `method_missing` per render.
247
- - A pure-Ruby implementation with identical output is used when the extension is unavailable.
258
+ ## Contributing
248
259
 
249
- ## Development
260
+ Bug reports and pull requests are welcome. [CONTRIBUTING.md](CONTRIBUTING.md) has the setup, the checks to run and how pull requests get merged; [docs/architecture.md](docs/architecture.md) explains the internals, [docs/release.md](docs/release.md) the release process, and [CHANGELOG.md](CHANGELOG.md) what changed.
250
261
 
251
262
  ```bash
252
263
  bundle install
@@ -256,8 +267,12 @@ bundle exec rubocop
256
267
  bin/rails server # demo app
257
268
  ```
258
269
 
259
- The repository is both the gem (`lib/gem/`, `ext/ruby2html/`) and a Rails demo app (`app/`, `config/`). See [CONTRIBUTING.md](CONTRIBUTING.md), [docs/architecture.md](docs/architecture.md), [docs/release.md](docs/release.md) and [CHANGELOG.md](CHANGELOG.md).
270
+ The repository is both the gem (`lib/gem/`, `ext/ruby2html/`) and a Rails demo app (`app/`, `config/`).
260
271
 
261
272
  ## License
262
273
 
263
274
  MIT. See [LICENSE](LICENSE).
275
+
276
+ ## Star history
277
+
278
+ [![Star History Chart](https://api.star-history.com/svg?repos=sebyx07/ruby2html&type=Date)](https://star-history.com/#sebyx07/ruby2html&Date)
@@ -0,0 +1,95 @@
1
+ // JRuby's only native code: a byte-level HTML escaper, the renderer's hottest
2
+ // primitive. Everything else (tag methods, attributes, content rules) stays in
3
+ // the pure-Ruby twin (lib/gem/ruby2html/render/pure_ruby.rb), which JRuby's JIT
4
+ // optimizes well; on TruffleRuby even the C extension loses to pure Ruby, so
5
+ // only JRuby gets this. The C extension (ext/ruby2html/html_escape.c) is the
6
+ // reference; this must stay byte-identical with it and with PureRuby.escape.
7
+ //
8
+ // require 'ruby2html/ruby2html_jruby' loads this: JRuby maps the base name
9
+ // ruby2html_jruby to the class Ruby2htmlJrubyService (CamelCase + "Service") in
10
+ // the default package, so the name and package here are load-bearing.
11
+ //
12
+ // Built by rake-compiler's Rake::JavaExtensionTask (see Rakefile) into
13
+ // lib/gem/ruby2html/ruby2html_jruby.jar and shipped in the -java platform gem.
14
+
15
+ import org.jruby.Ruby;
16
+ import org.jruby.RubyModule;
17
+ import org.jruby.RubyString;
18
+ import org.jruby.anno.JRubyMethod;
19
+ import org.jruby.runtime.ThreadContext;
20
+ import org.jruby.runtime.builtin.IRubyObject;
21
+ import org.jruby.runtime.load.BasicLibraryService;
22
+ import org.jruby.util.ByteList;
23
+
24
+ public class Ruby2htmlJrubyService implements BasicLibraryService {
25
+ // getOrCreateModule/defineModuleUnder/defineAnnotatedMethods are marked
26
+ // deprecated on JRuby 10 but remain the load-service API and still work; the
27
+ // context-taking replacements are not available on the JRuby versions in CI.
28
+ @SuppressWarnings("deprecation")
29
+ public boolean basicLoad(final Ruby runtime) {
30
+ final RubyModule javaNative =
31
+ runtime.getOrCreateModule("Ruby2html").defineModuleUnder("JavaNative");
32
+ javaNative.defineAnnotatedMethods(Escaper.class);
33
+ return true;
34
+ }
35
+
36
+ public static final class Escaper {
37
+ private static final byte AMP = '&', LT = '<', GT = '>', QUOT = '"', APOS = '\'';
38
+ private static final byte[] E_AMP = bytes("&amp;");
39
+ private static final byte[] E_LT = bytes("&lt;");
40
+ private static final byte[] E_GT = bytes("&gt;");
41
+ private static final byte[] E_QUOT = bytes("&quot;");
42
+ private static final byte[] E_APOS = bytes("&#39;");
43
+
44
+ private static byte[] bytes(final String s) {
45
+ final byte[] b = new byte[s.length()];
46
+ for (int i = 0; i < s.length(); i++) b[i] = (byte) s.charAt(i);
47
+ return b;
48
+ }
49
+
50
+ private static boolean escapable(final byte b) {
51
+ return b == AMP || b == LT || b == GT || b == QUOT || b == APOS;
52
+ }
53
+
54
+ // Ruby2html::JavaNative.escape(str) -> String
55
+ //
56
+ // str has already been run through PureRuby.utf8_compatible, so its
57
+ // encoding is UTF-8, US-ASCII or BINARY. All five escapable characters
58
+ // are ASCII, so escaping byte by byte is identical across those
59
+ // encodings and for bytes that are invalid UTF-8 (the C extension and
60
+ // PureRuby both pass such bytes through). The result keeps the input's
61
+ // encoding. A clean string is returned unchanged (same object), which
62
+ // PureRuby.escape_html relies on to avoid a copy.
63
+ @JRubyMethod(name = "escape", module = true)
64
+ public static IRubyObject escape(final ThreadContext ctx, final IRubyObject self,
65
+ final IRubyObject arg) {
66
+ final RubyString str = (RubyString) arg;
67
+ final ByteList in = str.getByteList();
68
+ final byte[] src = in.getUnsafeBytes();
69
+ final int begin = in.getBegin();
70
+ final int len = in.getRealSize();
71
+
72
+ int first = -1;
73
+ for (int i = 0; i < len; i++) {
74
+ if (escapable(src[begin + i])) { first = i; break; }
75
+ }
76
+ if (first < 0) return str; // nothing to escape: hand back the same string
77
+
78
+ final ByteList out = new ByteList(len + 16);
79
+ out.setEncoding(in.getEncoding());
80
+ out.append(src, begin, first);
81
+ for (int i = first; i < len; i++) {
82
+ final byte b = src[begin + i];
83
+ switch (b) {
84
+ case AMP: out.append(E_AMP); break;
85
+ case LT: out.append(E_LT); break;
86
+ case GT: out.append(E_GT); break;
87
+ case QUOT: out.append(E_QUOT); break;
88
+ case APOS: out.append(E_APOS); break;
89
+ default: out.append(b);
90
+ }
91
+ }
92
+ return RubyString.newString(ctx.runtime, out);
93
+ }
94
+ }
95
+ }
@@ -49,15 +49,30 @@ static VALUE key_to_str(VALUE key)
49
49
  * Writes ` name` (or ` prefix-name` with _ turned into -) and returns the
50
50
  * offset of the name within buf so callers can inspect or roll it back.
51
51
  */
52
- /* Error path only: report the full name as written (`data-x onclick`), like PureRuby. */
52
+ /*
53
+ * Error path only: report the full name as written (`data-x onclick`), like
54
+ * PureRuby. Built from the raw bytes, labelled UTF-8 like the output: the
55
+ * name may hold invalid bytes, which String#tr would raise on.
56
+ */
53
57
  NORETURN(static void raise_invalid_name(const attr_ctx *ctx, VALUE name));
54
58
  static void raise_invalid_name(const attr_ctx *ctx, VALUE name)
55
59
  {
56
- VALUE full = name;
57
- if (!NIL_P(ctx->prefix)) {
58
- VALUE dashed = rb_funcall(name, rb_intern("tr"), 2, rb_str_new_cstr("_"), rb_str_new_cstr("-"));
59
- full = rb_sprintf("%" PRIsVALUE "-%" PRIsVALUE, ctx->prefix, dashed);
60
+ const int nested = !NIL_P(ctx->prefix);
61
+ VALUE full = rb_utf8_str_new(NULL, 0);
62
+
63
+ if (nested) {
64
+ rb_str_cat(full, RSTRING_PTR(ctx->prefix), RSTRING_LEN(ctx->prefix));
65
+ R2H_BUF_CAT_LIT(full, "-");
60
66
  }
67
+ const long offset = RSTRING_LEN(full);
68
+ rb_str_cat(full, RSTRING_PTR(name), RSTRING_LEN(name));
69
+ if (nested) {
70
+ char *p = RSTRING_PTR(full);
71
+ for (long i = offset; i < RSTRING_LEN(full); i++) {
72
+ if (p[i] == '_') p[i] = '-';
73
+ }
74
+ }
75
+ RB_GC_GUARD(name);
61
76
  rb_raise(rb_eArgError, "invalid attribute name: %+" PRIsVALUE, full);
62
77
  }
63
78
 
@@ -180,7 +195,7 @@ static int append_attribute(VALUE key, VALUE value, VALUE data)
180
195
  break;
181
196
  case T_HASH: {
182
197
  /* The name just written becomes the prefix of the nested keys. */
183
- attr_ctx nested = { buf, rb_str_new(RSTRING_PTR(buf) + start, RSTRING_LEN(buf) - start), ctx->depth + 1 };
198
+ attr_ctx nested = { buf, rb_enc_str_new(RSTRING_PTR(buf) + start, RSTRING_LEN(buf) - start, rb_utf8_encoding()), ctx->depth + 1 };
184
199
  rb_str_set_len(buf, start - 1);
185
200
  check_nesting(nested.depth);
186
201
  rb_hash_foreach(value, append_attribute, (VALUE)&nested);
@@ -105,7 +105,11 @@ static VALUE native_plain(VALUE self, VALUE text)
105
105
  /* component(html): already-rendered markup, appended as is. */
106
106
  static VALUE native_component(VALUE self, VALUE html)
107
107
  {
108
- if (!NIL_P(html)) r2h_append_raw(r2h_current_buffer(self), rb_obj_as_string(html));
108
+ if (NIL_P(html)) return Qnil;
109
+
110
+ /* Buffer first, then to_s: the order PureRuby checks them in. */
111
+ VALUE buf = r2h_current_buffer(self);
112
+ r2h_append_raw(buf, rb_obj_as_string(html));
109
113
  return Qnil;
110
114
  }
111
115
 
@@ -12,6 +12,10 @@ end
12
12
 
13
13
  skip_native_extension('RUBY2HTML_DISABLE_EXT=1') if ENV['RUBY2HTML_DISABLE_EXT'] == '1'
14
14
  skip_native_extension('JRuby does not load C extensions') if RUBY_ENGINE == 'jruby'
15
+ # TruffleRuby runs C extensions through Sulong (an LLVM interpreter) but gives
16
+ # pure Ruby the full Graal JIT, which here renders ~28x faster than the
17
+ # extension. Building it would only slow TruffleRuby down, so don't.
18
+ skip_native_extension('TruffleRuby is faster on the pure-Ruby renderer') if RUBY_ENGINE == 'truffleruby'
15
19
 
16
20
  require 'mkmf'
17
21
 
@@ -152,8 +152,9 @@ static char *escape_into(char *out, const char *p, long len)
152
152
 
153
153
  /*
154
154
  * The output buffer is UTF-8. UTF-8, US-ASCII and ASCII-only strings are
155
- * copied byte for byte. Binary strings are assumed to hold UTF-8 bytes
156
- * (what 1.x did). Anything else is transcoded, which raises if it can't be.
155
+ * copied byte for byte. Binary strings, and US-ASCII strings with non-ASCII
156
+ * bytes, are assumed to hold UTF-8 bytes (what 1.x did). Anything else is
157
+ * transcoded, which raises if it can't be.
157
158
  */
158
159
  VALUE r2h_utf8_compatible(VALUE str)
159
160
  {
@@ -205,6 +206,20 @@ void r2h_append_raw(VALUE buf, VALUE str)
205
206
  RB_GC_GUARD(str);
206
207
  }
207
208
 
209
+ /*
210
+ * Binary input, and US-ASCII input with non-ASCII bytes (a read under
211
+ * LANG=C), hold UTF-8 bytes (see r2h_utf8_compatible): escape_html labels
212
+ * the result UTF-8. Kept out of line: inlined (or called only for non-UTF-8
213
+ * input), gcc 16 compiled escape_html's scan of a clean 10KB string about
214
+ * 25% slower.
215
+ */
216
+ NOINLINE(static int holds_utf8_bytes(VALUE str));
217
+ static int holds_utf8_bytes(VALUE str)
218
+ {
219
+ const int index = ENCODING_GET_INLINED(str);
220
+ return index == binary_index || (index == usascii_index && !rb_enc_str_asciionly_p(str));
221
+ }
222
+
208
223
  /*
209
224
  * Ruby2html::Native.escape_html(obj) -> String
210
225
  *
@@ -217,9 +232,7 @@ static VALUE native_escape_html(VALUE mod, VALUE obj)
217
232
  const char *p = RSTRING_PTR(str);
218
233
  const long len = RSTRING_LEN(str);
219
234
  const long first = find_escapable(p, len);
220
-
221
- /* Binary input holds UTF-8 bytes (see r2h_utf8_compatible): label the result UTF-8. */
222
- const int binary = ENCODING_GET_INLINED(str) == binary_index;
235
+ const int binary = holds_utf8_bytes(str);
223
236
 
224
237
  if (first == len) {
225
238
  if (!binary) return OBJ_FROZEN(str) ? str : rb_str_dup(str);
@@ -10,7 +10,19 @@ RUBY_FUNC_EXPORTED void Init_ruby2html(void)
10
10
  VALUE ruby2html = rb_define_module("Ruby2html");
11
11
  VALUE native = rb_define_module_under(ruby2html, "Native");
12
12
 
13
+ /*
14
+ * escape_html, plain and component touch no shared mutable state, so they
15
+ * may run in any Ractor (the tag methods are defined after Init, outside
16
+ * this scope, and are callable from any Ractor already). define_tag
17
+ * writes the shared tag table: main Ractor only.
18
+ */
19
+ #ifdef HAVE_RB_EXT_RACTOR_SAFE
20
+ rb_ext_ractor_safe(true);
21
+ #endif
13
22
  r2h_init_escape(native);
14
23
  r2h_init_content(native);
24
+ #ifdef HAVE_RB_EXT_RACTOR_SAFE
25
+ rb_ext_ractor_safe(false);
26
+ #endif
15
27
  r2h_init_tags(native);
16
28
  }
@@ -64,8 +64,10 @@ module Ruby2html
64
64
  # The buffer currently written to (RailsComponents swap it to capture blocks).
65
65
  attr_accessor :current_output
66
66
 
67
- # Rails' entry point: `render component` in views and controllers.
68
- def render_in(view_context, &block)
67
+ # Rails' entry point: `render component` in views and controllers. Rails 8.2+ passes
68
+ # `locals:` (render_in without options is deprecated there); a component takes its data
69
+ # through #initialize, so options are accepted and ignored.
70
+ def render_in(view_context, **_options, &block)
69
71
  buffer = String.new(capacity: self.class.__r2h_capacity, encoding: Encoding::UTF_8)
70
72
  content = block && -> { plain(view_context.capture(self, &block)) }
71
73
  render_into(buffer, view_context, content)
@@ -104,15 +106,38 @@ module Ruby2html
104
106
  end
105
107
 
106
108
  # Renders another component into this buffer, or anything Rails can
107
- # render (partials, ViewComponents) via the view context.
109
+ # render (partials, ViewComponents) via the view context. A block is
110
+ # captured from this component's buffer (see TemplateHelpers#render).
108
111
  def render(*args, **options, &block)
109
112
  first = args.first
110
113
  if args.size == 1 && options.empty? && first.is_a?(Component)
111
- first.render_into(@current_output, helpers, block)
114
+ first.render_into(@current_output, helpers, block && first.__r2h_block_content(self, block))
115
+ elsif block
116
+ RailsComponents::TemplateHelpers.new(self, helpers).render(*args, **options, &block)
112
117
  else
113
- plain(helpers.render(*args, **options, &block))
118
+ plain(helpers.render(*args, **options))
114
119
  end
115
120
  nil
116
121
  end
122
+
123
+ # A #render_into content callable for a block written in Ruby2html code
124
+ # (`render(card) { em 'x' }`). The block writes through +parent+ (the
125
+ # renderer or component it appears in), so while it runs, parent writes
126
+ # into this component's current buffer, which may be a capture (e.g. a
127
+ # link_to block). As with ActionView's capture, the block gets the
128
+ # component, and a String it returns without writing is the (escaped)
129
+ # content.
130
+ def __r2h_block_content(parent, block)
131
+ lambda do
132
+ buffer = @current_output
133
+ previous = parent.current_output
134
+ parent.current_output = buffer
135
+ size = buffer.bytesize
136
+ value = block.call(self)
137
+ plain(value) if value.is_a?(String) && buffer.bytesize == size
138
+ ensure
139
+ parent.current_output = previous
140
+ end
141
+ end
117
142
  end
118
143
  end
@@ -38,11 +38,16 @@ module Ruby2html
38
38
  renderer.__send__(name, ...)
39
39
  end
40
40
 
41
- # Only claims the renderer's own methods (tags, plain, component, ...).
42
- # Asking the renderer's respond_to? here could recurse back into this
43
- # object, because the renderer delegates respond_to? to its context.
41
+ # Only claims the renderer's own PUBLIC methods (tags, plain, component,
42
+ # ...). Asking the renderer's respond_to? here could recurse back into
43
+ # this object, because the renderer delegates respond_to? to its context.
44
+ #
45
+ # public_method_defined? (not method_defined?) keeps the claimed set
46
+ # equal to what #method_missing can serve: its gate, renderer.respond_to?,
47
+ # reports public methods only, while method_defined? also matches
48
+ # protected ones, which respond_to? omits and method_missing cannot call.
44
49
  def respond_to_missing?(name, include_private = false)
45
- (@__r2h && Ruby2html::Render.method_defined?(name)) || super
50
+ (@__r2h && Ruby2html::Render.public_method_defined?(name)) || super
46
51
  end
47
52
  end
48
53
  end
@@ -61,6 +61,18 @@ module Ruby2html
61
61
  Result.new(apply(source, collector.edits), collector.uses_helpers)
62
62
  end
63
63
 
64
+ # Local names declared by a parameter list such as a strict-locals
65
+ # signature (`title:, label: 'x', **rest`); [] without Prism or when
66
+ # it doesn't parse (ActionView then reports the bad signature).
67
+ def parameter_names(signature)
68
+ return [] unless available?
69
+
70
+ parsed = Prism.parse("def __r2h_locals(#{signature}); end")
71
+ return [] unless parsed.success?
72
+
73
+ parsed.value.statements.body.first.locals
74
+ end
75
+
64
76
  # Ruby2html methods a template may call without a receiver: every
65
77
  # tag method plus plain/component. Resolved lazily (and memoized) so
66
78
  # it reflects Render after it has been fully loaded.
@@ -40,7 +40,7 @@ module Ruby2html
40
40
  def render(*args, **options, &block)
41
41
  first = args.first
42
42
  if args.size == 1 && options.empty? && first.is_a?(Ruby2html::Component)
43
- first.render_into(@render.current_output, @context, block)
43
+ first.render_into(@render.current_output, @context, block && first.__r2h_block_content(@render, block))
44
44
  else
45
45
  @render.plain(@context.render(*args, **options, &capturing(block)))
46
46
  end
@@ -58,8 +58,14 @@ module Ruby2html
58
58
  end
59
59
 
60
60
  private
61
+ # Strict-locals templates (`# locals: (title:)`) report nil locals:
62
+ # their names come from the magic comment's parameter list instead.
61
63
  def template_locals(template)
62
- template.respond_to?(:locals) ? Array(template.locals) : []
64
+ if template.respond_to?(:strict_locals?) && template.strict_locals?
65
+ RailsComponents::TemplateCompiler.parameter_names(template.strict_locals!)
66
+ else
67
+ template.respond_to?(:locals) ? Array(template.locals) : []
68
+ end
63
69
  end
64
70
 
65
71
  def compiled_code(template, compiled)
@@ -109,6 +115,18 @@ module Ruby2html
109
115
  # trying to autoload/eager-load them anywhere under app/.
110
116
  Rails.autoloaders.main.ignore(Rails.root.join('app/**/*.html.rb'))
111
117
  end
118
+
119
+ # Cache digests: find the partials a template renders. RubyTracker parses
120
+ # the handler's compiled output, where they are `__r2h_helpers.render`
121
+ # calls. Not in the :action_view hook: that hook can fire while
122
+ # action_view/dependency_tracker is still loading (its requires load
123
+ # ActionView::Base), and the file then resets the tracker table after us.
124
+ config.after_initialize do
125
+ require 'action_view/dependency_tracker'
126
+ ActiveSupport.on_load(:action_view) do
127
+ ActionView::DependencyTracker.register_tracker :rb, ActionView::DependencyTracker::RubyTracker
128
+ end
129
+ end
112
130
  end
113
131
  end
114
132
  end
@@ -8,6 +8,16 @@ rescue LoadError
8
8
  nil
9
9
  end
10
10
 
11
+ if RUBY_ENGINE == 'jruby' && ENV['RUBY2HTML_DISABLE_EXT'] != '1'
12
+ begin
13
+ # Defines Ruby2html::JavaNative (a byte-level HTML escaper, ext/java).
14
+ # JRuby's only native code; PureRuby.escape uses it when present.
15
+ require 'ruby2html/ruby2html_jruby'
16
+ rescue LoadError
17
+ nil
18
+ end
19
+ end
20
+
11
21
  module Ruby2html
12
22
  # Pure-Ruby twin of the C extension's Ruby2html::Native (ext/ruby2html),
13
23
  # used on JRuby, when the extension isn't built, or with
@@ -33,6 +43,13 @@ module Ruby2html
33
43
  def escape(str)
34
44
  ERB::Escape.html_escape(utf8_compatible(str))
35
45
  end
46
+ elsif defined?(Ruby2html::JavaNative)
47
+ # JRuby: the Java escaper (ext/java). Byte-identical with the regex
48
+ # branch below (and with the C extension); also returns str itself
49
+ # when clean. utf8_compatible first, so it sees UTF-8/US-ASCII/BINARY.
50
+ def escape(str)
51
+ Ruby2html::JavaNative.escape(utf8_compatible(str))
52
+ end
36
53
  else
37
54
  def escape(str)
38
55
  str = utf8_compatible(str)
@@ -45,7 +62,7 @@ module Ruby2html
45
62
 
46
63
  # Like Native.escape_html: never hands back the caller's mutable string.
47
64
  def escape_html(obj)
48
- str = obj.to_s
65
+ str = as_string(obj)
49
66
  escaped = escape(str)
50
67
  escaped.equal?(str) && !str.frozen? ? str.dup : escaped
51
68
  end
@@ -53,12 +70,35 @@ module Ruby2html
53
70
  # See r2h_utf8_compatible in html_escape.c.
54
71
  def utf8_compatible(str)
55
72
  case str.encoding
56
- when Encoding::UTF_8, Encoding::US_ASCII then str
73
+ when Encoding::UTF_8 then str
74
+ when Encoding::US_ASCII then str.ascii_only? ? str : str.dup.force_encoding(Encoding::UTF_8)
57
75
  when Encoding::BINARY then str.dup.force_encoding(Encoding::UTF_8)
58
76
  else str.ascii_only? ? str : str.encode(Encoding::UTF_8)
59
77
  end
60
78
  end
61
79
 
80
+ # rb_obj_as_string, as the C extension uses: a String as is, else #to_s
81
+ # (even a private one), else Kernel#to_s when #to_s returns no String.
82
+ def as_string(obj)
83
+ return obj if String === obj
84
+
85
+ str = obj.__send__(:to_s)
86
+ String === str ? str : Kernel.instance_method(:to_s).bind_call(obj)
87
+ end
88
+
89
+ # See r2h_current_buffer in content.c.
90
+ def output_buffer(buffer)
91
+ raise TypeError, 'ruby2html: @current_output must be a String' unless String === buffer
92
+
93
+ encoding = buffer.encoding
94
+ return buffer if encoding == Encoding::UTF_8
95
+ unless encoding == Encoding::BINARY || encoding == Encoding::US_ASCII
96
+ raise Encoding::CompatibilityError, "ruby2html: output buffer must be UTF-8, not #{encoding}"
97
+ end
98
+
99
+ buffer.force_encoding(Encoding::UTF_8)
100
+ end
101
+
62
102
  def define_tag(method_name, tag, void)
63
103
  source = void ? void_tag_source(method_name, tag) : tag_source(method_name, tag)
64
104
  # The magic comment is per eval: without it every tag literal allocates.
@@ -70,7 +110,15 @@ module Ruby2html
70
110
  <<~RUBY
71
111
  def #{method_name}(content = nil, **attributes)
72
112
  buffer = @current_output
113
+ buffer = __r2h_output(buffer) unless buffer && buffer.equal?(@__r2h_output)
73
114
  if attributes.empty?
115
+ # `li "text"` (Native's fast path): escaping may raise (an
116
+ # untranscodable string), so do it before writing anything.
117
+ if !block_given? && String === content && content.instance_of?(String)
118
+ text = PureRuby.escape(content)
119
+ buffer << '<#{tag}>' << text << '</#{tag}>'
120
+ return
121
+ end
74
122
  buffer << '<#{tag}>'
75
123
  else
76
124
  __r2h_open_tag(buffer, '<#{tag}', attributes)
@@ -80,8 +128,6 @@ module Ruby2html
80
128
  size = buffer.bytesize
81
129
  result = yield
82
130
  __r2h_block_result(buffer, result) if buffer.bytesize == size
83
- elsif content.instance_of?(String)
84
- buffer << PureRuby.escape(content)
85
131
  else
86
132
  __r2h_text(buffer, content)
87
133
  end
@@ -94,10 +140,11 @@ module Ruby2html
94
140
  def void_tag_source(method_name, tag)
95
141
  <<~RUBY
96
142
  def #{method_name}(_content = nil, **attributes)
143
+ buffer = @current_output
144
+ buffer = __r2h_output(buffer) unless buffer && buffer.equal?(@__r2h_output)
97
145
  if attributes.empty?
98
- @current_output << '<#{tag} />'
146
+ buffer << '<#{tag} />'
99
147
  else
100
- buffer = @current_output
101
148
  __r2h_open_tag(buffer, '<#{tag}', attributes)
102
149
  buffer << ' />'
103
150
  end
@@ -108,16 +155,29 @@ module Ruby2html
108
155
  end
109
156
 
110
157
  def plain(text)
111
- __r2h_text(@current_output, text)
158
+ buffer = @current_output
159
+ buffer = __r2h_output(buffer) unless buffer && buffer.equal?(@__r2h_output)
160
+ __r2h_text(buffer, text)
112
161
  nil
113
162
  end
114
163
 
115
164
  def component(html)
116
- @current_output << PureRuby.utf8_compatible(html.to_s) unless html.nil?
165
+ return if html.equal?(nil)
166
+
167
+ buffer = @current_output
168
+ buffer = __r2h_output(buffer) unless buffer && buffer.equal?(@__r2h_output)
169
+ buffer << PureRuby.utf8_compatible(PureRuby.as_string(html))
117
170
  nil
118
171
  end
119
172
 
120
173
  private
174
+ # Validates (and relabels) a newly swapped-in @current_output once, then
175
+ # remembers it: checking its class and encoding on every call costs the
176
+ # pure-Ruby renderer a few percent. (`buffer &&`: the memo starts as nil.)
177
+ def __r2h_output(buffer)
178
+ @__r2h_output = PureRuby.output_buffer(buffer)
179
+ end
180
+
121
181
  def __r2h_text(buffer, obj)
122
182
  case obj
123
183
  when nil then nil
@@ -126,16 +186,23 @@ module Ruby2html
126
186
  buffer << (safe ? PureRuby.utf8_compatible(obj) : PureRuby.escape(obj))
127
187
  when Symbol, Integer then buffer << PureRuby.escape(obj.to_s)
128
188
  else
129
- buffer << (__r2h_html_safe?(obj) ? PureRuby.utf8_compatible(obj.to_s) : PureRuby.escape(obj.to_s))
189
+ safe = __r2h_html_safe?(obj)
190
+ str = PureRuby.as_string(obj)
191
+ buffer << (safe ? PureRuby.utf8_compatible(str) : PureRuby.escape(str))
130
192
  end
131
193
  end
132
194
 
195
+ # Module#===, not is_a?: the result may be a BasicObject.
133
196
  def __r2h_block_result(buffer, result)
134
- __r2h_text(buffer, result) if result.is_a?(String) || result.is_a?(Symbol) || result.is_a?(Numeric)
197
+ case result
198
+ when String, Symbol, Numeric then __r2h_text(buffer, result)
199
+ end
135
200
  end
136
201
 
202
+ # rb_respond_to also answers for a BasicObject, which has no respond_to?.
137
203
  def __r2h_html_safe?(obj)
138
- obj.respond_to?(:html_safe?) && obj.html_safe?
204
+ responds = Kernel === obj ? obj.respond_to?(:html_safe?) : Kernel.instance_method(:respond_to?).bind_call(obj, :html_safe?)
205
+ responds && obj.html_safe?
139
206
  end
140
207
 
141
208
  # Writes `<tag attr="..."`. If an attribute raises and the caller rescues,
@@ -154,28 +221,34 @@ module Ruby2html
154
221
  raise ArgumentError, "attributes nested more than #{MAX_NESTING} levels deep" if depth > MAX_NESTING
155
222
 
156
223
  attributes.each do |key, value|
157
- next if value.nil?
224
+ next if value.equal?(nil) # not nil?: the value may be a BasicObject
158
225
 
159
- name = key.is_a?(Symbol) ? key.name : key.to_s
226
+ name = Symbol === key ? key.name : PureRuby.as_string(key)
160
227
  raise ArgumentError, "attribute name can't be empty" if name.empty?
161
228
 
162
229
  name = PureRuby.utf8_compatible(name)
163
230
  name = "#{prefix}-#{__r2h_dasherize(name)}" if prefix
164
231
  # Match bytes when the name isn't valid UTF-8 (a UTF-8 regex would raise).
165
232
  checked = name.valid_encoding? ? name : name.b
166
- raise ArgumentError, "invalid attribute name: #{name.inspect}" if INVALID_ATTRIBUTE_NAME.match?(checked)
233
+ __r2h_invalid_name(name) if INVALID_ATTRIBUTE_NAME.match?(checked)
167
234
 
168
235
  case value
169
236
  when String then buffer << ' ' << name << '="' << PureRuby.escape(value) << '"'
170
- when true then buffer << ' ' << name << (STRING_BOOLEAN.match?(name) ? '="true"' : '')
171
- when false then buffer << ' ' << name << '="false"' if STRING_BOOLEAN.match?(name)
237
+ when true then buffer << ' ' << name << (STRING_BOOLEAN.match?(checked) ? '="true"' : '')
238
+ when false then buffer << ' ' << name << '="false"' if STRING_BOOLEAN.match?(checked)
172
239
  when Hash then __r2h_attributes(buffer, value, name, depth + 1)
173
240
  when Array then buffer << ' ' << name << '="' << __r2h_tokens(value) << '"'
174
- else buffer << ' ' << name << '="' << PureRuby.escape(value.to_s) << '"'
241
+ else buffer << ' ' << name << '="' << PureRuby.escape(PureRuby.as_string(value)) << '"'
175
242
  end
176
243
  end
177
244
  end
178
245
 
246
+ # Shows the name's bytes as UTF-8, whatever encoding interpolation gave it
247
+ # (see raise_invalid_name in attributes.c).
248
+ def __r2h_invalid_name(name)
249
+ raise ArgumentError, "invalid attribute name: #{name.dup.force_encoding(Encoding::UTF_8).inspect}"
250
+ end
251
+
179
252
  def __r2h_dasherize(name)
180
253
  return name.tr('_', '-') if name.valid_encoding?
181
254
 
@@ -190,10 +263,10 @@ module Ruby2html
190
263
  raise ArgumentError, "attributes nested more than #{MAX_NESTING} levels deep" if depth > MAX_NESTING
191
264
 
192
265
  tokens.each do |token|
193
- if token.is_a?(Array)
266
+ if Array === token
194
267
  __r2h_collect_tokens(token, collected, depth + 1)
195
268
  elsif token
196
- collected << PureRuby.escape(token.to_s)
269
+ collected << PureRuby.escape(PureRuby.as_string(token))
197
270
  end
198
271
  end
199
272
  collected
@@ -9,6 +9,10 @@ module Ruby2html
9
9
  # into lib/ruby2html.
10
10
  def self.load_native_extension
11
11
  return false if ENV['RUBY2HTML_DISABLE_EXT'] == '1'
12
+ # JRuby has no C extension (it uses a Java escaper over the pure-Ruby twin,
13
+ # see load_java_escaper). TruffleRuby *can* load it via Sulong, but renders
14
+ # ~28x slower that way than on pure Ruby under the Graal JIT, so never do.
15
+ return false if RUBY_ENGINE == 'jruby' || RUBY_ENGINE == 'truffleruby'
12
16
 
13
17
  begin
14
18
  require 'ruby2html/ruby2html'
@@ -16,7 +20,10 @@ module Ruby2html
16
20
  require_relative '../../ruby2html/ruby2html'
17
21
  end
18
22
  defined?(Native) ? true : false
19
- rescue LoadError
23
+ rescue LoadError => e
24
+ # On CRuby a missing extension means a broken build: say so instead of
25
+ # silently rendering about 3x slower.
26
+ warn "ruby2html: C extension not loaded (#{e.message}); using the pure-Ruby renderer"
20
27
  false
21
28
  end
22
29
  private_class_method :load_native_extension
@@ -69,11 +76,13 @@ module Ruby2html
69
76
 
70
77
  # Without arguments renders the root block and returns the HTML (a
71
78
  # SafeBuffer under ActiveSupport). With arguments it is the context's
72
- # render (partials, components), appended to the output.
79
+ # render (partials, components), appended to the output; a block is
80
+ # captured from this renderer's buffer (see TemplateHelpers#render).
73
81
  def render(*args, **options, &block)
74
82
  copy_instance_variables if @context && !@__vars_copied
75
83
 
76
- return plain @context.render(*args, **options, &block) if !args.empty? || !options.empty? || block
84
+ return RailsComponents::TemplateHelpers.new(self, @context).render(*args, **options, &block) if block
85
+ return plain @context.render(*args, **options) if !args.empty? || !options.empty?
77
86
 
78
87
  instance_exec(&@root)
79
88
  defined?(ActiveSupport::SafeBuffer) ? ActiveSupport::SafeBuffer.new(@output) : @output
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Ruby2html
4
- VERSION = '2.0.0'
4
+ VERSION = '2.1.1'
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: ruby2html
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.0.0
4
+ version: 2.1.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - sebi
@@ -9,11 +9,11 @@ bindir: bin
9
9
  cert_chain: []
10
10
  date: 1980-01-02 00:00:00.000000000 Z
11
11
  dependencies: []
12
- description: Ruby2HTML empowers developers to write view logic in pure Ruby, seamlessly
13
- converting it into clean, well-formatted HTML. Enhance your templating workflow,
14
- improve readability, and leverage the full power of Ruby in your views. Features
15
- include Rails integration, custom component support, automatic HTML beautification,
16
- and C-optimized rendering performance.
12
+ description: 'ruby2html renders HTML from a pure-Ruby block DSL (div class: "card"
13
+ do h2 @title end). Text and attribute values are escaped by default. Works standalone,
14
+ as Rails .html.rb templates and partials, inside ERB, in ViewComponent, and as lightweight
15
+ Ruby2html::Component classes. Tag rendering is a C extension on CRuby, with an output-identical
16
+ pure-Ruby fallback for JRuby and TruffleRuby. No runtime dependencies.'
17
17
  email:
18
18
  - gore.sebyx@yahoo.com
19
19
  executables: []
@@ -24,6 +24,7 @@ files:
24
24
  - CHANGELOG.md
25
25
  - LICENSE
26
26
  - README.md
27
+ - ext/java/Ruby2htmlJrubyService.java
27
28
  - ext/ruby2html/attributes.c
28
29
  - ext/ruby2html/buffer.h
29
30
  - ext/ruby2html/content.c
@@ -73,7 +74,8 @@ required_rubygems_version: !ruby/object:Gem::Requirement
73
74
  - !ruby/object:Gem::Version
74
75
  version: '0'
75
76
  requirements: []
76
- rubygems_version: 3.6.9
77
+ rubygems_version: 4.0.20
77
78
  specification_version: 4
78
- summary: Transform Ruby code into beautiful, structured HTML with C-optimized performance
79
+ summary: 'HTML views in plain Ruby: a block DSL with escaping by default, Rails templates
80
+ and components'
79
81
  test_files: []