From 9cc6c37513c4b77dbd0265b32837ffb915d85c62 Mon Sep 17 00:00:00 2001 From: Jackson Pires Date: Thu, 12 Nov 2026 22:47:48 -0300 Subject: [PATCH] Fix model generation, decimal inputs and Badge variants; use ruby_ui from RubyGems - Railtie no longer requires generator classes in its `generators` block. Rails runs those blocks before `Rails::Generators.configure!`, so loading Rails' ModelGenerator there froze its `:orm` hook as `false` and `rails g ruby_ui_scaffold` (and plain `rails g model`) skipped the model and migration. The entry generator now requires its sub-generators, since Rails' hook lookup only loads the first matching candidate file. - Stringify decimal input values: Phlex 2 rejects BigDecimal attributes, which crashed the edit form. - Pass Badge variants as symbols; RubyUI::Badge::COLORS is symbol-keyed, so string variants rendered without colors. - Installer adds `gem "ruby_ui", "~> 1.6"` from RubyGems instead of the GitHub main branch. Verified end-to-end against ruby_ui 1.6.0. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 23 ++++++ CLAUDE.md | 4 +- README.md | 7 +- .../install/install_generator.rb | 15 ++-- .../ruby_ui_scaffold_generator.rb | 11 +++ .../scaffold/templates/index.rb.tt | 2 +- .../scaffold/templates/index_data_table.rb.tt | 2 +- .../scaffold/templates/show.rb.tt | 2 +- .../scaffold_controller_generator.rb | 4 + lib/ruby_ui_scaffold/field_type_mapper.rb | 5 +- lib/ruby_ui_scaffold/railtie.rb | 26 ++++--- test/field_type_mapper_test.rb | 11 ++- test/generators/install_generator_test.rb | 3 +- test/generators/scaffold_generator_test.rb | 5 +- test/railtie_test.rb | 73 +++++++++++++++++++ 15 files changed, 163 insertions(+), 30 deletions(-) create mode 100644 test/railtie_test.rb diff --git a/CHANGELOG.md b/CHANGELOG.md index 1ec95b3..ba02acf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,29 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Fixed + +- **`rails g ruby_ui_scaffold` generated no model or migration** (and having + the gem in the Gemfile broke plain `rails g model` too). The Railtie's + `generators` block required the generator classes, which loaded Rails' + `ModelGenerator` before `Rails::Generators.configure!` and froze its `:orm` + hook as `false`. The Railtie now only sets option defaults; generator + classes load lazily, after configuration. +- **Edit form crashed for `decimal` columns** with + `Phlex::ArgumentError (Invalid attribute value for value: 0.58206e3)` — + Phlex 2 rejects `BigDecimal` attribute values. The input value is now + stringified (`@record.price&.to_s` → `"582.06"`). +- **Boolean `Badge` rendered without colors.** Templates passed the variant + as a string (`"success"`), but `RubyUI::Badge::COLORS` is symbol-keyed and + Badge doesn't `to_sym` it. Variants are now symbols (`:success` / `:outline`). + +### Changed + +- **`ruby_ui` now comes from RubyGems.** The installer adds + `gem "ruby_ui", "~> 1.6", require: false` instead of tracking the GitHub + `main` branch. Verified end-to-end against ruby_ui 1.6.0. Existing GitHub + entries in a Gemfile are still detected and left alone. + ### Added - **Ruby × Rails compatibility matrix** in the README and a GitHub Actions CI diff --git a/CLAUDE.md b/CLAUDE.md index 238ca6e..9dc91f2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -39,7 +39,7 @@ A single `rails g ruby_ui_scaffold User ...` fans out through three cooperating 3. **`ScaffoldGenerator`** (`.../scaffold/`) — the "template engine." Emits the Phlex view classes (`index`, `show`, `new`, `edit`, `form`) under the `Views::` namespace, runs preflight warnings, and injects required Phlex helpers into `app/components/base.rb`. -`Railtie#generators` (`lib/ruby_ui_scaffold/railtie.rb`) sets `Rails::Generators.options[:ruby_ui_scaffold][:template_engine] = "ruby_ui_scaffold"` **before** requiring the generator classes — `hook_for`/`class_option` freeze option defaults at class-definition time, so order matters. +`Railtie#generators` (`lib/ruby_ui_scaffold/railtie.rb`) only sets `Rails::Generators.options[:ruby_ui_scaffold][:template_engine] = "ruby_ui_scaffold"` — it must **not** require any generator class. Rails runs `generators` blocks *before* `Rails::Generators.configure!`, and `hook_for`/`class_option` freeze option defaults at class-definition time: requiring generators there loads Rails' `ModelGenerator` early and freezes its `:orm` as `false`, silently skipping the model + migration (for plain `rails g model` too). Our classes are loaded lazily by Rails' namespace lookup instead. Because that lookup requires only the **first** existing candidate file, the entry generator (`ruby_ui_scaffold_generator.rb`) eagerly requires its sub-generators — otherwise the views hook resolves to the already-loaded entry file and reports `ruby_ui_scaffold [not found]`. `test/railtie_test.rb` guards both in a subprocess through the real `load_generators` path. When editing any generator, the three `class_option` declarations (`--datatable`, `--literal`, `--phlex_layout`) must stay in sync across all three generators, since options propagate down the hook chain. @@ -61,7 +61,7 @@ When editing any generator, the three `class_option` declarations (`--datatable` ### The `install` generator and `seed` command -- **`InstallGenerator`** (`.../install/`) is a one-shot, fully idempotent installer that runs `phlex:install`, `ruby_ui:install`, then installs the `ComponentResolver::BASE` component set (the always-used scaffold shell). It deliberately does **not** run `ruby_ui:component:all` — column/flag-specific components are installed on demand by the scaffold generator (see below), so apps only carry what they use. It shells out via `run_rails_generator!` (not Thor's `generate`) because Thor's `abort_on_failure` doesn't reliably propagate exit codes from the inner Rails command. Also injects Tailwind `@source` directives so Tailwind v4 scans `.rb` view/component files. `ensure_ruby_ui_gem` runs first: since `ruby_ui` is a GitHub-distributed gem (can't be a gemspec dependency), when it isn't loadable the installer **adds it to the Gemfile and runs `bundle install`** rather than aborting. This works even when the install is itself a subprocess of the scaffold generator — the later `run_rails_generator!` steps spawn fresh subprocesses that boot with the updated bundle, so they see `ruby_ui` even though the current process never loaded it. `phlex-rails` (a declared runtime dependency) keeps the abort-with-instructions behavior, since auto-editing our own dependency would be odd. +- **`InstallGenerator`** (`.../install/`) is a one-shot, fully idempotent installer that runs `phlex:install`, `ruby_ui:install`, then installs the `ComponentResolver::BASE` component set (the always-used scaffold shell). It deliberately does **not** run `ruby_ui:component:all` — column/flag-specific components are installed on demand by the scaffold generator (see below), so apps only carry what they use. It shells out via `run_rails_generator!` (not Thor's `generate`) because Thor's `abort_on_failure` doesn't reliably propagate exit codes from the inner Rails command. Also injects Tailwind `@source` directives so Tailwind v4 scans `.rb` view/component files. `ensure_ruby_ui_gem` runs first: `ruby_ui` is published on RubyGems but deliberately left to the host app's Gemfile (not a gemspec dependency) so the app controls its version/group; when it isn't loadable the installer **adds `gem "ruby_ui", RUBY_UI_REQUIREMENT, require: false` (`"~> 1.6"`) to the Gemfile and runs `bundle install`** rather than aborting. This works even when the install is itself a subprocess of the scaffold generator — the later `run_rails_generator!` steps spawn fresh subprocesses that boot with the updated bundle, so they see `ruby_ui` even though the current process never loaded it. `phlex-rails` (a declared runtime dependency) keeps the abort-with-instructions behavior, since auto-editing our own dependency would be odd. - **On-demand components**: after writing the views, `ScaffoldGenerator#install_required_components` shells out `ruby_ui:component NAME` for each component from `ComponentResolver.call(...)` not already present. Gated identically to the auto-install (`--skip-install` or no app `bin/rails` → skip). Failure is **non-fatal** (warn and continue — the views already exist), unlike the installer's abort-on-failure, so one missing component doesn't tear down the scaffold run. - **`SeedCommand`** (`lib/rails/commands/ruby_ui_scaffold/seed_command.rb`) is a `Rails::Command::Base` (not a generator) — registered by file-path convention, invoked as `rails ruby_ui_scaffold:seed MODEL`. diff --git a/README.md b/README.md index 24122a2..5b1a9d5 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,7 @@ On a fresh Rails app, add **both** gems to your `Gemfile` — `ruby_ui` (the com ```ruby # Gemfile -gem "ruby_ui", github: "ruby-ui/ruby_ui", branch: "main", require: false +gem "ruby_ui", "~> 1.6", require: false group :development do gem "ruby_ui_scaffold" @@ -74,7 +74,7 @@ That's it. The installer wires up phlex, ruby_ui, and the base scaffold componen
What the installer does -0. **ruby_ui gem bootstrap** — if `ruby_ui` isn't loadable, adds `gem "ruby_ui", github: "ruby-ui/ruby_ui", branch: "main", require: false` to the Gemfile (unless an entry already exists) and runs `bundle install`. Skipped entirely once the gem loads. +0. **ruby_ui gem bootstrap** — if `ruby_ui` isn't loadable, adds `gem "ruby_ui", "~> 1.6", require: false` (from RubyGems) to the Gemfile (unless an entry already exists) and runs `bundle install`. Skipped entirely once the gem loads. 1. **`phlex:install`** — creates `app/views/base.rb` (`Views::Base`), `app/components/base.rb` (`Components::Base`), and `config/initializers/phlex.rb` (wires the `Views::` autoloader). Skipped if `app/views/base.rb` already exists. 2. **`ruby_ui:install`** — mixes `include RubyUI` into `Components::Base`, adds `config/initializers/ruby_ui.rb`, and the Tailwind preset. Skipped if `Components::Base` already includes RubyUI. 3. **Base components** — installs the components every scaffold's shell uses regardless of columns/flags: `table`, `link`, `button`, `card`, `typography`, `dropdown_menu`, `alert_dialog`, `form`, `input`. Each is skipped if already present. The installer does **not** run `ruby_ui:component:all` — column/flag-specific components are installed on demand (see below). @@ -454,7 +454,8 @@ Controllers render via the fully-qualified constant — `render ::Views::Buddies | `string` | `Input(type: "text")` | | `text` | `Textarea(rows: 4)` | | `integer` | `Input(type: "number", step: 1)` | -| `float`, `decimal` | `Input(type: "number", step: "any")` | +| `float` | `Input(type: "number", step: "any")` | +| `decimal` | `Input(type: "number", step: "any")` — value stringified (`&.to_s`) | | `boolean` | `Checkbox` + hidden `"0"` | | `date` | `DatePicker` (ruby_ui — Popover + Calendar over a submittable input) | | `time` | `Input(type: "time")` | diff --git a/lib/generators/ruby_ui_scaffold/install/install_generator.rb b/lib/generators/ruby_ui_scaffold/install/install_generator.rb index b06f038..be74681 100644 --- a/lib/generators/ruby_ui_scaffold/install/install_generator.rb +++ b/lib/generators/ruby_ui_scaffold/install/install_generator.rb @@ -21,6 +21,11 @@ module Generators class InstallGenerator < ::Rails::Generators::Base include ::RubyUiScaffold::ComponentInstaller + # Version constraint for the `ruby_ui` Gemfile entry the installer adds. + # ruby_ui is published on RubyGems; 1.6 is the oldest release this gem's + # generated views and component set were verified against. + RUBY_UI_REQUIREMENT = "~> 1.6" + desc "Install the ruby_ui gem, phlex, ruby_ui, and the base scaffold components." def check_phlex_rails_gem @@ -37,9 +42,9 @@ def check_phlex_rails_gem end # Ensure the `ruby_ui` gem is available. Unlike `phlex-rails` (a declared - # runtime dependency of this gem), `ruby_ui` is distributed via GitHub and - # can't be a gemspec dependency — so on a fresh app it usually isn't - # bundled yet. Rather than abort, add it to the Gemfile and `bundle + # runtime dependency of this gem), `ruby_ui` is left to the host app's + # Gemfile (so the app controls its version and group, as ruby_ui's own + # docs recommend) — so on a fresh app it usually isn't bundled yet. Rather than abort, add it to the Gemfile and `bundle # install` automatically, then let the rest of the installer proceed: # the subsequent `ruby_ui:install` / `ruby_ui:component` steps run in # subprocesses (via run_rails_generator!) that boot with the freshly @@ -56,7 +61,7 @@ def ensure_ruby_ui_gem say "\n → ruby_ui is in the Gemfile but not bundled yet — running `bundle install`.", :cyan else say "\n → ruby_ui gem not found — adding it to your Gemfile.", :cyan - gem "ruby_ui", github: "ruby-ui/ruby_ui", branch: "main", require: false + gem "ruby_ui", RUBY_UI_REQUIREMENT, require: false end run_bundle_install! @@ -137,7 +142,7 @@ def done def abort_ruby_ui_unavailable! say "\n ❌ The `ruby_ui` gem isn't available and no Gemfile was found to add it to.", :red say " Add it to your Gemfile, then bundle and retry:\n", :red - say %( gem "ruby_ui", github: "ruby-ui/ruby_ui", branch: "main", require: false), :cyan + say %( gem "ruby_ui", "#{RUBY_UI_REQUIREMENT}", require: false), :cyan say " bundle install" say " bin/rails g ruby_ui_scaffold:install\n", :cyan exit(1) diff --git a/lib/generators/ruby_ui_scaffold/ruby_ui_scaffold_generator.rb b/lib/generators/ruby_ui_scaffold/ruby_ui_scaffold_generator.rb index 1e88067..5d5df0f 100644 --- a/lib/generators/ruby_ui_scaffold/ruby_ui_scaffold_generator.rb +++ b/lib/generators/ruby_ui_scaffold/ruby_ui_scaffold_generator.rb @@ -3,6 +3,17 @@ require "rails/generators" require "rails/generators/rails/scaffold/scaffold_generator" +# Load our sub-generators eagerly, together with this entry point. Rails' +# hook lookup (Rails::Command::Behavior#lookup) requires only the FIRST +# existing candidate file: for the views hook (`find_by_namespace( +# "ruby_ui_scaffold", "ruby_ui_scaffold", "scaffold")`) that is THIS file, +# so `scaffold/scaffold_generator.rb` would never be loaded and the hook +# reports "ruby_ui_scaffold [not found]". This file itself is loaded lazily +# by the namespace lookup — after `Rails::Generators.configure!` — so these +# requires can't freeze option defaults too early (see Railtie). +require "generators/ruby_ui_scaffold/scaffold_controller/scaffold_controller_generator" +require "generators/ruby_ui_scaffold/scaffold/scaffold_generator" + module RubyUiScaffold module Generators # Entry point: `rails g ruby_ui_scaffold User name:string ...` diff --git a/lib/generators/ruby_ui_scaffold/scaffold/templates/index.rb.tt b/lib/generators/ruby_ui_scaffold/scaffold/templates/index.rb.tt index 8b6ce7a..62bb685 100644 --- a/lib/generators/ruby_ui_scaffold/scaffold/templates/index.rb.tt +++ b/lib/generators/ruby_ui_scaffold/scaffold/templates/index.rb.tt @@ -43,7 +43,7 @@ class Views::<%= controller_class_name %>::Index < Views::Base <% attributes.reject { |a| a.respond_to?(:password_digest?) && a.password_digest? }.each do |attribute| -%> <% if attribute.type == :boolean -%> TableCell do - Badge(variant: <%= singular_table_name %>.<%= attribute.column_name %>? ? "success" : "outline") do + Badge(variant: <%= singular_table_name %>.<%= attribute.column_name %>? ? :success : :outline) do <%= singular_table_name %>.<%= attribute.column_name %>? ? "Yes" : "No" end end diff --git a/lib/generators/ruby_ui_scaffold/scaffold/templates/index_data_table.rb.tt b/lib/generators/ruby_ui_scaffold/scaffold/templates/index_data_table.rb.tt index e7462a7..f7cf652 100644 --- a/lib/generators/ruby_ui_scaffold/scaffold/templates/index_data_table.rb.tt +++ b/lib/generators/ruby_ui_scaffold/scaffold/templates/index_data_table.rb.tt @@ -86,7 +86,7 @@ class Views::<%= controller_class_name %>::Index < Views::Base <% attributes.reject { |a| a.respond_to?(:password_digest?) && a.password_digest? }.each do |attribute| -%> <% if attribute.type == :boolean -%> TableCell do - Badge(variant: <%= singular_table_name %>.<%= attribute.column_name %>? ? "success" : "outline") do + Badge(variant: <%= singular_table_name %>.<%= attribute.column_name %>? ? :success : :outline) do <%= singular_table_name %>.<%= attribute.column_name %>? ? "Yes" : "No" end end diff --git a/lib/generators/ruby_ui_scaffold/scaffold/templates/show.rb.tt b/lib/generators/ruby_ui_scaffold/scaffold/templates/show.rb.tt index 64c8300..bf828e9 100644 --- a/lib/generators/ruby_ui_scaffold/scaffold/templates/show.rb.tt +++ b/lib/generators/ruby_ui_scaffold/scaffold/templates/show.rb.tt @@ -35,7 +35,7 @@ class Views::<%= controller_class_name %>::Show < Views::Base div do Text(weight: "medium") { "<%= attribute.human_name %>:" } <% if attribute.type == :boolean -%> - Badge(variant: @<%= singular_table_name %>.<%= attribute.column_name %>? ? "success" : "outline") do + Badge(variant: @<%= singular_table_name %>.<%= attribute.column_name %>? ? :success : :outline) do @<%= singular_table_name %>.<%= attribute.column_name %>? ? "Yes" : "No" end <% elsif reference_associations.include?(attribute.name.to_sym) -%> diff --git a/lib/generators/ruby_ui_scaffold/scaffold_controller/scaffold_controller_generator.rb b/lib/generators/ruby_ui_scaffold/scaffold_controller/scaffold_controller_generator.rb index ec9d0b6..66a4b63 100644 --- a/lib/generators/ruby_ui_scaffold/scaffold_controller/scaffold_controller_generator.rb +++ b/lib/generators/ruby_ui_scaffold/scaffold_controller/scaffold_controller_generator.rb @@ -3,6 +3,10 @@ require "rails/generators" require "rails/generators/rails/scaffold_controller/scaffold_controller_generator" require "ruby_ui_scaffold/attribute_helpers" +# Our template_engine hook target. Required directly so a standalone +# `rails g ruby_ui_scaffold:scaffold_controller` resolves it too (see the +# note in ruby_ui_scaffold_generator.rb on Rails' first-match lookup). +require "generators/ruby_ui_scaffold/scaffold/scaffold_generator" module RubyUiScaffold module Generators diff --git a/lib/ruby_ui_scaffold/field_type_mapper.rb b/lib/ruby_ui_scaffold/field_type_mapper.rb index ce5c5c9..4dea0e4 100644 --- a/lib/ruby_ui_scaffold/field_type_mapper.rb +++ b/lib/ruby_ui_scaffold/field_type_mapper.rb @@ -38,7 +38,10 @@ def type_input when :text then textarea when :boolean then checkbox when :integer then input("number", step: 1) - when :float, :decimal then input("number", step: "any") + when :float then input("number", step: "any") + # Phlex 2 rejects BigDecimal attribute values (Phlex::ArgumentError), so + # stringify — ActiveSupport makes BigDecimal#to_s plain notation ("582.06"). + when :decimal then input("number", step: "any", value_suffix: "&.to_s") when :date then date_picker when :time then input("time", value_suffix: %q{&.strftime("%H:%M")}) when :datetime, :timestamp then input("datetime-local", value_suffix: %q{&.strftime("%Y-%m-%dT%H:%M")}) diff --git a/lib/ruby_ui_scaffold/railtie.rb b/lib/ruby_ui_scaffold/railtie.rb index b928a7c..6024e54 100644 --- a/lib/ruby_ui_scaffold/railtie.rb +++ b/lib/ruby_ui_scaffold/railtie.rb @@ -6,20 +6,24 @@ class Railtie < ::Rails::Railtie # (i.e. on `rails g`), not at app boot — important because # Rails::Generators isn't loaded at boot. generators do - # IMPORTANT: set option defaults BEFORE requiring the generator - # classes. `class_option(...)` (called by `hook_for`) freezes the - # default at class-definition time via `default_value_for_option`, - # which reads from Rails::Generators.options. + # Only set option defaults here — do NOT require any generator class. # - # We only need to override template_engine — the scaffold_controller - # default falls back to :scaffold_controller (Rails-wide), which - # combined with our base_name routes correctly to ours. + # Rails runs every railtie's `generators` block BEFORE + # `Rails::Generators.configure!(app.config.generators)` (see + # Rails::Engine#load_generators). `hook_for`/`class_option` freeze their + # defaults at class-definition time, so requiring our generators here + # would also load Rails' ScaffoldGenerator → ModelGenerator early, and + # their `:orm` hook would freeze as `false` (the pre-configure default) + # instead of `:active_record` — silently skipping the model + migration + # for `rails g ruby_ui_scaffold` AND plain `rails g model`. + # + # Our generator classes are instead loaded lazily by Rails' namespace + # lookup (`generators/ruby_ui_scaffold/...`), after configure! has run, + # and they read this template_engine default at that point. The + # scaffold_controller default falls back to :scaffold_controller + # (Rails-wide), which combined with our base_name routes to ours. ::Rails::Generators.options[:ruby_ui_scaffold] ||= {} ::Rails::Generators.options[:ruby_ui_scaffold][:template_engine] = "ruby_ui_scaffold" - - require "generators/ruby_ui_scaffold/ruby_ui_scaffold_generator" - require "generators/ruby_ui_scaffold/scaffold_controller/scaffold_controller_generator" - require "generators/ruby_ui_scaffold/scaffold/scaffold_generator" end end end diff --git a/test/field_type_mapper_test.rb b/test/field_type_mapper_test.rb index 8faf45f..7c57ce6 100644 --- a/test/field_type_mapper_test.rb +++ b/test/field_type_mapper_test.rb @@ -27,9 +27,16 @@ def test_integer_renders_number_step_1 assert_equal %{Input(type: "number", id: "user_age", name: "user[age]", value: @user.age, step: 1)}, out end - def test_decimal_renders_number_step_any + # Stringified: Phlex 2 rejects BigDecimal attribute values (Phlex::ArgumentError). + def test_decimal_renders_number_step_any_with_stringified_value out = render("price", "decimal") - assert_equal %{Input(type: "number", id: "user_price", name: "user[price]", value: @user.price, step: "any")}, out + assert_equal %{Input(type: "number", id: "user_price", name: "user[price]", value: @user.price&.to_s, step: "any")}, out + end + + # Float is a valid Phlex attribute value as-is — no stringification needed. + def test_float_renders_number_step_any + out = render("ratio", "float") + assert_equal %{Input(type: "number", id: "user_ratio", name: "user[ratio]", value: @user.ratio, step: "any")}, out end def test_boolean_renders_hidden_plus_checkbox diff --git a/test/generators/install_generator_test.rb b/test/generators/install_generator_test.rb index 65acc18..bacdf4d 100644 --- a/test/generators/install_generator_test.rb +++ b/test/generators/install_generator_test.rb @@ -190,7 +190,8 @@ def test_adds_ruby_ui_to_gemfile_and_bundles_when_not_loadable run_generator gemfile = File.read(File.join(destination_root, "Gemfile")) - assert_match(%r{gem ["']ruby_ui["'].*github: ["']ruby-ui/ruby_ui["']}, gemfile) + assert_match(%r{gem ["']ruby_ui["'], ["']~> 1\.6["'], require: false}, gemfile) + refute_match(/github:/, gemfile, "ruby_ui is on RubyGems — no GitHub source") assert Thread.current[:bundle_installed], "Expected `bundle install` to run" # After bootstrapping the gem, the installer still proceeds to ruby_ui:install assert_invoked "ruby_ui:install" diff --git a/test/generators/scaffold_generator_test.rb b/test/generators/scaffold_generator_test.rb index 6f1fbcc..86bfec1 100644 --- a/test/generators/scaffold_generator_test.rb +++ b/test/generators/scaffold_generator_test.rb @@ -145,7 +145,8 @@ def test_index_renders_data_table_with_ruby_ui_components assert_match(/DataTableSortHead\(/, c) assert_match(/column_key: "name"/, c) # Boolean rendered as Badge in body - assert_match(/Badge\(variant: user\.admin\? \? "success" : "outline"\)/, c) + # Symbol variants — RubyUI::Badge::COLORS is symbol-keyed (no to_sym) + assert_match(/Badge\(variant: user\.admin\? \? :success : :outline\)/, c) # Pagination assert_match(/DataTablePaginationBar do/, c) assert_match(/DataTablePagination\(/, c) @@ -396,7 +397,7 @@ def test_show_renders_card_with_fields_and_centered_layout assert_match(/Card\(class: "[^"]*max-w-prose[^"]*mx-auto/, c) assert_match(/Text\(weight: "medium"\) { "Name:" }/, c) # Boolean as Badge in show too - assert_match(/Badge\(variant: @user\.admin\?/, c) + assert_match(/Badge\(variant: @user\.admin\? \? :success : :outline\)/, c) # Edit link carries a lucide `pencil` icon assert_match(/Link\(href: edit_user_path\(@user\), variant: "outline", class: "gap-2"\) do/, c) assert_match(/lucide_icon\("pencil", class: "size-4"\)/, c) diff --git a/test/railtie_test.rb b/test/railtie_test.rb new file mode 100644 index 0000000..9754669 --- /dev/null +++ b/test/railtie_test.rb @@ -0,0 +1,73 @@ +# frozen_string_literal: true + +require "minitest/autorun" +require "open3" +require "rbconfig" + +# Regression test for the Railtie's `generators` block. +# +# Rails boots generators as: run every railtie's `generators` block, THEN +# `Rails::Generators.configure!(app.config.generators)` (see +# Rails::Engine#load_generators). `hook_for` freezes option defaults at +# class-definition time, so if our block requires Rails' scaffold generator +# classes, `ModelGenerator`'s `:orm` hook freezes as `false` (the pre-configure +# default) instead of `:active_record` — and `rails g ruby_ui_scaffold` (and +# even plain `rails g model`) silently skips the model + migration. +# +# This can't run in-process: test_helper already loads every generator class, +# which is exactly the state we need to avoid. So it boots a minimal app in a +# subprocess, through the real `load_generators` path. +class RailtieTest < Minitest::Test + LIB = File.expand_path("../lib", __dir__) + + SCRIPT = <<~'RUBY' + require "rails" + require "active_record/railtie" + require "action_controller/railtie" + require "ruby_ui_scaffold" + + class RailtieTestApp < Rails::Application + config.eager_load = false + config.logger = Logger.new(nil) + config.secret_key_base = "x" * 64 + end + + Rails.application.load_generators + + model = Rails::Generators.find_by_namespace("model") + scaffold = Rails::Generators.find_by_namespace("ruby_ui_scaffold") + puts "model_orm=#{model.class_options[:orm].default.inspect}" + puts "scaffold_class=#{scaffold}" + puts "scaffold_orm=#{scaffold.class_options[:orm].default.inspect}" + # Resolve the sub-generators exactly as the hook chain does at runtime + # (hook_for → prepare_for_invocation → find_by_namespace(value, base, as)), + # not by a direct namespace lookup: Rails requires only the first existing + # candidate file, which is what broke lazily-loaded hook targets before. + resolve = ->(klass, hook) { klass.send(:prepare_for_invocation, hook, klass.class_options[hook].default) } + controller = resolve.(scaffold, :scaffold_controller) + views = resolve.(controller, :template_engine) + puts "controller_class=#{controller}" + puts "views_class=#{views}" + puts "template_engine=#{controller.class_options[:template_engine].default.inspect}" + RUBY + + def boot_generators + out, err, status = Open3.capture3(RbConfig.ruby, "-rbundler/setup", "-I", LIB, "-e", SCRIPT) + assert status.success?, "subprocess failed:\n#{err}" + out.lines.to_h { |line| line.chomp.split("=", 2) } + end + + def test_generators_block_does_not_freeze_orm_before_configure + result = boot_generators + + assert_equal ":active_record", result["model_orm"], + "Plain `rails g model` lost its ORM — the Railtie loaded Rails' generator classes before configure!" + assert_equal "RubyUiScaffold::Generators::RubyUiScaffoldGenerator", result["scaffold_class"] + assert_equal ":active_record", result["scaffold_orm"], + "`rails g ruby_ui_scaffold` would skip the model + migration" + # The hook chain still resolves to our (lazily loaded) sub-generators. + assert_equal "RubyUiScaffold::Generators::ScaffoldControllerGenerator", result["controller_class"] + assert_equal "RubyUiScaffold::Generators::ScaffoldGenerator", result["views_class"] + assert_equal '"ruby_ui_scaffold"', result["template_engine"] + end +end