ruby2html 2.1.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: 7c3bc5f1d40d12683edafbe453a291165275d9dc1b2552007a0d757954793a6a
4
- data.tar.gz: 2fd1df901225789e4327576d414dd16be60bea5b9c2f11020c16a6ce0e7ef1cb
3
+ metadata.gz: 8c9414914d7c75eb9597a47b12bb7f2c7b9a8ca32d61080d729fa404bf0ab287
4
+ data.tar.gz: f789e9ad4275dcf7a560ec8666f3768a82d34108a9673eb36897a8ee47fe1cc6
5
5
  SHA512:
6
- metadata.gz: bc63552f617578a8d98938490e564a7c483e7f6179faefa5800452b8ad90d6cc1dfa921f0626bfa2c1a4046e79f298facdef9c7fb337a1e3a481f46049c0fd7a
7
- data.tar.gz: 2e25baa9f3ecce618f5eac307767e66ee9592216d441444e4fb1da39def3a7a454ac97f6a1b3fc007a3f402ac50eb5e2cdfee42bdb81719b44fe60376205c17c
6
+ metadata.gz: 86c7d10f052c651d73d9b10f7136df9a46f426775157cb2aaab91e41685d3176e69d8f6e90547daed3f9ba8395b98df51e72cda34e2f7dfe897f4b5662256203
7
+ data.tar.gz: 74d0d49bc5280d5eb27549bf732888ce04ef31b3fd453225142b4d3eb4ffb4329742717cc64631c2478937b3c37aa02a871c7355fd7ce05787cfb1aa21988efd
data/CHANGELOG.md CHANGED
@@ -6,6 +6,25 @@ 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
+
9
28
  ## [2.1.0] - 2026-10-31
10
29
 
11
30
  ### Added
@@ -183,7 +202,8 @@ Published to RubyGems; no separate commits in the repository history.
183
202
  ### Added
184
203
  - Initial release: `Ruby2html::Render` DSL, `Ruby2html::RailsHelper#html` for ERB.
185
204
 
186
- [Unreleased]: https://github.com/sebyx07/ruby2html/compare/v2.1.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
187
207
  [2.1.0]: https://github.com/sebyx07/ruby2html/compare/v2.0.0...v2.1.0
188
208
  [2.0.0]: https://github.com/sebyx07/ruby2html/releases/tag/v2.0.0
189
209
  [1.6.6]: https://rubygems.org/gems/ruby2html/versions/1.6.6
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), JRuby with a Java escaper over the pure-Ruby implementation, and TruffleRuby on pure Ruby (faster there than the C extension) — all byte-identical. 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; CI currently covers 3.3, 3.4 and 4.0), JRuby (pure Ruby plus a Java escaper), TruffleRuby (pure Ruby), and Rails 7.2+; the CI matrix is generated automatically, so new Ruby releases are picked up without edits.
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, no C extension; CRuby) | ~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)
@@ -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
 
@@ -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
  }
@@ -106,15 +106,38 @@ module Ruby2html
106
106
  end
107
107
 
108
108
  # Renders another component into this buffer, or anything Rails can
109
- # 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).
110
111
  def render(*args, **options, &block)
111
112
  first = args.first
112
113
  if args.size == 1 && options.empty? && first.is_a?(Component)
113
- 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)
114
117
  else
115
- plain(helpers.render(*args, **options, &block))
118
+ plain(helpers.render(*args, **options))
116
119
  end
117
120
  nil
118
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
119
142
  end
120
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
@@ -62,7 +62,7 @@ module Ruby2html
62
62
 
63
63
  # Like Native.escape_html: never hands back the caller's mutable string.
64
64
  def escape_html(obj)
65
- str = obj.to_s
65
+ str = as_string(obj)
66
66
  escaped = escape(str)
67
67
  escaped.equal?(str) && !str.frozen? ? str.dup : escaped
68
68
  end
@@ -70,12 +70,35 @@ module Ruby2html
70
70
  # See r2h_utf8_compatible in html_escape.c.
71
71
  def utf8_compatible(str)
72
72
  case str.encoding
73
- 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)
74
75
  when Encoding::BINARY then str.dup.force_encoding(Encoding::UTF_8)
75
76
  else str.ascii_only? ? str : str.encode(Encoding::UTF_8)
76
77
  end
77
78
  end
78
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
+
79
102
  def define_tag(method_name, tag, void)
80
103
  source = void ? void_tag_source(method_name, tag) : tag_source(method_name, tag)
81
104
  # The magic comment is per eval: without it every tag literal allocates.
@@ -87,7 +110,15 @@ module Ruby2html
87
110
  <<~RUBY
88
111
  def #{method_name}(content = nil, **attributes)
89
112
  buffer = @current_output
113
+ buffer = __r2h_output(buffer) unless buffer && buffer.equal?(@__r2h_output)
90
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
91
122
  buffer << '<#{tag}>'
92
123
  else
93
124
  __r2h_open_tag(buffer, '<#{tag}', attributes)
@@ -97,8 +128,6 @@ module Ruby2html
97
128
  size = buffer.bytesize
98
129
  result = yield
99
130
  __r2h_block_result(buffer, result) if buffer.bytesize == size
100
- elsif content.instance_of?(String)
101
- buffer << PureRuby.escape(content)
102
131
  else
103
132
  __r2h_text(buffer, content)
104
133
  end
@@ -111,10 +140,11 @@ module Ruby2html
111
140
  def void_tag_source(method_name, tag)
112
141
  <<~RUBY
113
142
  def #{method_name}(_content = nil, **attributes)
143
+ buffer = @current_output
144
+ buffer = __r2h_output(buffer) unless buffer && buffer.equal?(@__r2h_output)
114
145
  if attributes.empty?
115
- @current_output << '<#{tag} />'
146
+ buffer << '<#{tag} />'
116
147
  else
117
- buffer = @current_output
118
148
  __r2h_open_tag(buffer, '<#{tag}', attributes)
119
149
  buffer << ' />'
120
150
  end
@@ -125,16 +155,29 @@ module Ruby2html
125
155
  end
126
156
 
127
157
  def plain(text)
128
- __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)
129
161
  nil
130
162
  end
131
163
 
132
164
  def component(html)
133
- @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))
134
170
  nil
135
171
  end
136
172
 
137
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
+
138
181
  def __r2h_text(buffer, obj)
139
182
  case obj
140
183
  when nil then nil
@@ -143,16 +186,23 @@ module Ruby2html
143
186
  buffer << (safe ? PureRuby.utf8_compatible(obj) : PureRuby.escape(obj))
144
187
  when Symbol, Integer then buffer << PureRuby.escape(obj.to_s)
145
188
  else
146
- 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))
147
192
  end
148
193
  end
149
194
 
195
+ # Module#===, not is_a?: the result may be a BasicObject.
150
196
  def __r2h_block_result(buffer, result)
151
- __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
152
200
  end
153
201
 
202
+ # rb_respond_to also answers for a BasicObject, which has no respond_to?.
154
203
  def __r2h_html_safe?(obj)
155
- 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?
156
206
  end
157
207
 
158
208
  # Writes `<tag attr="..."`. If an attribute raises and the caller rescues,
@@ -171,28 +221,34 @@ module Ruby2html
171
221
  raise ArgumentError, "attributes nested more than #{MAX_NESTING} levels deep" if depth > MAX_NESTING
172
222
 
173
223
  attributes.each do |key, value|
174
- next if value.nil?
224
+ next if value.equal?(nil) # not nil?: the value may be a BasicObject
175
225
 
176
- name = key.is_a?(Symbol) ? key.name : key.to_s
226
+ name = Symbol === key ? key.name : PureRuby.as_string(key)
177
227
  raise ArgumentError, "attribute name can't be empty" if name.empty?
178
228
 
179
229
  name = PureRuby.utf8_compatible(name)
180
230
  name = "#{prefix}-#{__r2h_dasherize(name)}" if prefix
181
231
  # Match bytes when the name isn't valid UTF-8 (a UTF-8 regex would raise).
182
232
  checked = name.valid_encoding? ? name : name.b
183
- raise ArgumentError, "invalid attribute name: #{name.inspect}" if INVALID_ATTRIBUTE_NAME.match?(checked)
233
+ __r2h_invalid_name(name) if INVALID_ATTRIBUTE_NAME.match?(checked)
184
234
 
185
235
  case value
186
236
  when String then buffer << ' ' << name << '="' << PureRuby.escape(value) << '"'
187
- when true then buffer << ' ' << name << (STRING_BOOLEAN.match?(name) ? '="true"' : '')
188
- 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)
189
239
  when Hash then __r2h_attributes(buffer, value, name, depth + 1)
190
240
  when Array then buffer << ' ' << name << '="' << __r2h_tokens(value) << '"'
191
- else buffer << ' ' << name << '="' << PureRuby.escape(value.to_s) << '"'
241
+ else buffer << ' ' << name << '="' << PureRuby.escape(PureRuby.as_string(value)) << '"'
192
242
  end
193
243
  end
194
244
  end
195
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
+
196
252
  def __r2h_dasherize(name)
197
253
  return name.tr('_', '-') if name.valid_encoding?
198
254
 
@@ -207,10 +263,10 @@ module Ruby2html
207
263
  raise ArgumentError, "attributes nested more than #{MAX_NESTING} levels deep" if depth > MAX_NESTING
208
264
 
209
265
  tokens.each do |token|
210
- if token.is_a?(Array)
266
+ if Array === token
211
267
  __r2h_collect_tokens(token, collected, depth + 1)
212
268
  elsif token
213
- collected << PureRuby.escape(token.to_s)
269
+ collected << PureRuby.escape(PureRuby.as_string(token))
214
270
  end
215
271
  end
216
272
  collected
@@ -76,11 +76,13 @@ module Ruby2html
76
76
 
77
77
  # Without arguments renders the root block and returns the HTML (a
78
78
  # SafeBuffer under ActiveSupport). With arguments it is the context's
79
- # 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).
80
81
  def render(*args, **options, &block)
81
82
  copy_instance_variables if @context && !@__vars_copied
82
83
 
83
- 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?
84
86
 
85
87
  instance_exec(&@root)
86
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.1.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.1.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: []
@@ -76,5 +76,6 @@ required_rubygems_version: !ruby/object:Gem::Requirement
76
76
  requirements: []
77
77
  rubygems_version: 4.0.20
78
78
  specification_version: 4
79
- 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'
80
81
  test_files: []