chore: Upgrade to ActiveAdmin 4.0.0.beta20 and simplify test matrix

- Update ActiveAdmin from beta16 to beta20
- Drop support for Rails 6.1, 7.0, 7.1 and ActiveAdmin 2.x/3.x
- Minimum requirements now: Rails 7.2+, Ruby 3.2+, ActiveAdmin 4.x
- Reduce CI jobs from 22+ to 6 (2 gemfiles × 3 Ruby versions)
- Clean up obsolete documentation files

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Этот коммит содержится в:
Gleb Tv
2026-02-09 17:41:29 +03:00
родитель 0a12969370
Коммит 39380e7276
28 изменённых файлов: 1429 добавлений и 3998 удалений

27
.github/workflows/ci.yml поставляемый
Просмотреть файл

@@ -14,29 +14,10 @@ jobs:
strategy:
fail-fast: false
matrix:
ruby: ['3.0', '3.1', '3.2', '3.3']
ruby: ['3.2', '3.3', '3.4']
gemfile:
- rails_6.1_active_admin_2.9
- rails_7.0_active_admin_2.x
- rails_7.0_active_admin_3.x
- rails_7.1_active_admin_3.x
- rails_7.2_active_admin_3.x
- rails_7.2_active_admin_4.x
- rails_8.0_active_admin_4.x
exclude:
# Rails 8 requires Ruby 3.2+
- ruby: '3.0'
gemfile: rails_8.0_active_admin_4.x
- ruby: '3.1'
gemfile: rails_8.0_active_admin_4.x
# Rails 7.2 requires Ruby 3.1+
- ruby: '3.0'
gemfile: rails_7.2_active_admin_3.x
# ActiveAdmin 4 requires Ruby 3.2+
- ruby: '3.0'
gemfile: rails_7.2_active_admin_4.x
- ruby: '3.1'
gemfile: rails_7.2_active_admin_4.x
env:
BUNDLE_GEMFILE: ${{ github.workspace }}/gemfiles/${{ matrix.gemfile }}.gemfile
@@ -68,10 +49,8 @@ jobs:
cd spec/dummy
# Build JavaScript with esbuild
npm run build:js || true
# Build CSS with Tailwind for AA4
if [[ "${{ matrix.gemfile }}" == *"4.x"* ]]; then
# Build CSS with Tailwind
npm run build:css || true
fi
- name: Database setup
run: |
@@ -98,7 +77,7 @@ jobs:
- name: Set up Ruby
uses: ruby/setup-ruby@v1
with:
ruby-version: '3.3'
ruby-version: '3.4'
bundler-cache: true
- name: Run RuboCop

Просмотреть файл

@@ -1,64 +1,9 @@
# frozen_string_literal: true
# Rails 6.1 with ActiveAdmin 2.9
appraise 'rails-6.1-active-admin-2.9' do
gem 'rails', '~> 6.1.0'
gem 'activeadmin', '~> 2.9.0'
gem 'sqlite3', '~> 1.4'
gem 'sassc'
gem 'sprockets-rails'
remove_gem 'propshaft'
remove_gem 'importmap-rails'
end
# Rails 7.0 with ActiveAdmin 2.x
appraise 'rails-7.0-active-admin-2.x' do
gem 'rails', '~> 7.0.0'
gem 'activeadmin', '~> 2.14'
gem 'sqlite3', '~> 1.4'
gem 'sassc'
gem 'sprockets-rails'
remove_gem 'propshaft'
remove_gem 'importmap-rails'
end
# Rails 7.0 with ActiveAdmin 3.x
appraise 'rails-7.0-active-admin-3.x' do
gem 'rails', '~> 7.0.0'
gem 'activeadmin', '~> 3.2'
gem 'sqlite3', '~> 1.4'
gem 'sassc'
gem 'sprockets-rails'
remove_gem 'propshaft'
remove_gem 'importmap-rails'
end
# Rails 7.1 with ActiveAdmin 3.x
appraise 'rails-7.1-active-admin-3.x' do
gem 'rails', '~> 7.1.0'
gem 'activeadmin', '~> 3.2'
gem 'sqlite3', '~> 1.4'
gem 'sassc'
gem 'sprockets-rails'
remove_gem 'propshaft'
remove_gem 'importmap-rails'
end
# Rails 7.2 with ActiveAdmin 3.x
appraise 'rails-7.2-active-admin-3.x' do
gem 'rails', '~> 7.2.0'
gem 'activeadmin', '~> 3.2'
gem 'sqlite3' # 7.2 can use newer sqlite3
gem 'sassc'
gem 'sprockets-rails'
remove_gem 'propshaft'
remove_gem 'importmap-rails'
end
# Rails 7.2 with ActiveAdmin 4.x beta
appraise 'rails-7.2-active-admin-4.x' do
gem 'rails', '~> 7.2.0'
gem 'activeadmin', '4.0.0.beta16'
gem 'activeadmin', '4.0.0.beta20'
gem 'sqlite3' # 7.2 can use newer sqlite3
gem 'importmap-rails'
gem 'propshaft'
@@ -67,7 +12,7 @@ end
# Rails 8.0 with ActiveAdmin 4.x beta
appraise 'rails-8.0-active-admin-4.x' do
gem 'rails', '~> 8.0.0'
gem 'activeadmin', '4.0.0.beta16'
gem 'activeadmin', '4.0.0.beta20'
gem 'sqlite3' # Rails 8 needs latest sqlite3
gem 'importmap-rails'
gem 'propshaft'

Просмотреть файл

@@ -1,13 +1,7 @@
# ActiveAdmin Quill Editor
[![gem version](https://badge.fury.io/rb/activeadmin_quill_editor.svg)](https://badge.fury.io/rb/activeadmin_quill_editor)
[![gem downloads](https://badgen.net/rubygems/dt/activeadmin_quill_editor)](https://rubygems.org/gems/activeadmin_quill_editor)
[![linters](https://github.com/blocknotes/activeadmin_quill_editor/actions/workflows/linters.yml/badge.svg)](https://github.com/blocknotes/activeadmin_quill_editor/actions/workflows/linters.yml)
[![specs Rails 6.1](https://github.com/blocknotes/activeadmin_quill_editor/actions/workflows/specs_rails61.yml/badge.svg)](https://github.com/blocknotes/activeadmin_quill_editor/actions/workflows/specs_rails61.yml)
[![specs Rails 7.0](https://github.com/blocknotes/activeadmin_quill_editor/actions/workflows/specs_rails70.yml/badge.svg)](https://github.com/blocknotes/activeadmin_quill_editor/actions/workflows/specs_rails70.yml)
[![Specs Rails 7.1](https://github.com/blocknotes/activeadmin_quill_editor/actions/workflows/specs_rails71.yml/badge.svg)](https://github.com/blocknotes/activeadmin_quill_editor/actions/workflows/specs_rails71.yml)
[![Specs Rails 7.2](https://github.com/blocknotes/activeadmin_quill_editor/actions/workflows/specs_rails72.yml/badge.svg)](https://github.com/blocknotes/activeadmin_quill_editor/actions/workflows/specs_rails72.yml)
[![Specs Rails 8.0](https://github.com/blocknotes/activeadmin_quill_editor/actions/workflows/specs_rails80.yml/badge.svg)](https://github.com/blocknotes/activeadmin_quill_editor/actions/workflows/specs_rails80.yml)
[![CI](https://github.com/blocknotes/activeadmin_quill_editor/actions/workflows/ci.yml/badge.svg)](https://github.com/blocknotes/activeadmin_quill_editor/actions/workflows/ci.yml)
An Active Admin plugin to use [Quill Rich Text Editor](https://github.com/quilljs/quill) in form fields.

Просмотреть файл

@@ -14,7 +14,7 @@ Gem::Specification.new do |spec|
spec.email = 'mat@blocknot.es'
spec.homepage = 'https://github.com/rs-pro/activeadmin-quill_editor'
spec.required_ruby_version = '>= 3.0'
spec.required_ruby_version = '>= 3.2'
spec.metadata['homepage_uri'] = spec.homepage
spec.metadata['changelog_uri'] = 'https://github.com/rs-pro/activeadmin-quill_editor/blob/main/CHANGELOG.md'
@@ -25,6 +25,6 @@ Gem::Specification.new do |spec|
spec.files = Dir['{app,lib,vendor}/**/*', 'LICENSE.txt', 'Rakefile', 'README.md']
spec.require_paths = ['lib']
spec.add_dependency 'activeadmin', '>= 2.9', '< 5'
spec.add_dependency 'rails', '>= 6.0'
spec.add_dependency 'activeadmin', '>= 4.0', '< 5'
spec.add_dependency 'rails', '>= 7.2'
end

171
docs/activeadmin-4-asset-setup.md Обычный файл
Просмотреть файл

@@ -0,0 +1,171 @@
# ActiveAdmin 4 Asset Setup (Tailwind CSS v4)
## Overview
This guide documents the current, working setup for ActiveAdmin 4.0.0.beta19 with Tailwind CSS v4 and Tom Select (no jQuery).
## Requirements
- ActiveAdmin 4.0.0.beta19
- Tailwind CSS v4 via `tailwindcss-rails` (ships `bin/tailwindcss`)
- ESBuild (or other JS bundler) for ActiveAdmin JS + Tom Select
## 1. Gemfile
```ruby
# ActiveAdmin 4 beta
gem "activeadmin", "4.0.0.beta19"
gem "activeadmin-tom_select"
# Tailwind CSS v4 (bundled CLI)
gem "tailwindcss-rails", "~> 4.4.0"
```
## 2. package.json
```json
{
"dependencies": {
"@activeadmin/activeadmin": "^4.0.0-beta19",
"tom-select": "^2.4.3",
"activeadmin-tom_select": "^4.1.0"
},
"devDependencies": {
"esbuild": "^0.27.2"
},
"scripts": {
"build:js": "node esbuild-active_admin.config.js",
"build:css": "bundle exec rake active_admin:build",
"build": "npm run build:js && npm run build:css",
"watch:js": "node esbuild-active_admin.config.js --watch",
"watch:css": "bundle exec rake active_admin:watch",
"dev": "npm run watch:js & npm run watch:css"
}
}
```
## 3. JavaScript Entry (app/javascript/active_admin.js)
```javascript
import "@activeadmin/activeadmin";
import TomSelect from "tom-select";
window.TomSelect = TomSelect;
import { setupAutoInit, initSearchableSelects } from "activeadmin-tom_select";
window.initSearchableSelects = initSearchableSelects;
setupAutoInit();
```
## 4. Tailwind Input (app/assets/stylesheets/active_admin.tailwind.css)
```css
@import "tailwindcss";
@config "../../../tailwind-active_admin.config.mjs";
@import "activeadmin-tom_select/css";
```
## 5. Tailwind Config (tailwind-active_admin.config.mjs)
```javascript
import { execSync } from "child_process";
import activeAdminPlugin from "@activeadmin/activeadmin/plugin";
const activeAdminPath = execSync("bundle show activeadmin", {
encoding: "utf-8"
}).trim();
export default {
content: [
`${activeAdminPath}/vendor/javascript/flowbite.js`,
`${activeAdminPath}/plugin.js`,
`${activeAdminPath}/app/views/**/*.{arb,erb,html,rb}`,
"./app/admin/**/*.{arb,erb,html,rb}",
"./app/views/active_admin/**/*.{arb,erb,html,rb}",
"./app/views/admin/**/*.{arb,erb,html,rb}",
"./app/views/layouts/active_admin*.{erb,html}",
"./app/javascript/**/*.js"
],
darkMode: "selector",
plugins: [activeAdminPlugin]
};
```
## 6. Tailwind Build Tasks (lib/tasks/active_admin.rake)
```ruby
namespace :active_admin do
desc "Build Active Admin Tailwind stylesheets"
task build: :environment do
command = [
Rails.root.join("bin/tailwindcss").to_s,
"-i", Rails.root.join("app/assets/stylesheets/active_admin.tailwind.css").to_s,
"-o", Rails.root.join("app/assets/builds/active_admin.css").to_s,
"-m"
]
system(*command, exception: true)
end
desc "Watch Active Admin Tailwind stylesheets"
task watch: :environment do
command = [
Rails.root.join("bin/tailwindcss").to_s,
"--watch",
"-i", Rails.root.join("app/assets/stylesheets/active_admin.tailwind.css").to_s,
"-o", Rails.root.join("app/assets/builds/active_admin.css").to_s,
"-m"
]
system(*command, exception: true)
end
end
Rake::Task["assets:precompile"].enhance(["active_admin:build"])
Rake::Task["test:prepare"].enhance(["active_admin:build"]) if Rake::Task.task_defined?("test:prepare")
Rake::Task["spec:prepare"].enhance(["active_admin:build"]) if Rake::Task.task_defined?("spec:prepare")
Rake::Task["db:test:prepare"].enhance(["active_admin:build"]) if Rake::Task.task_defined?("db:test:prepare")
```
## 7. Tailwind CLI Binstub
```bash
bundle binstubs tailwindcss-ruby --force
```
## 8. Upgrade Notes (ActiveAdmin 4.0.0.beta19)
From ActiveAdmin's upgrade guide:
- `_site_header.html.erb` container class changed from `sticky` to `fixed`.
- `active_admin.html.erb` adds the `pt-16` utility class.
- Tailwind v4 uses `@import "tailwindcss"` and `@config` (no `@tailwind` directives).
- The Tailwind config file is ESM. Use `tailwind-active_admin.config.mjs`.
- jQuery/jQuery UI removed; `columns` and `tabs` components removed.
- Replace `default_main_content` with `render "show_default"`.
- Replace `as: :datepicker` with `as: :date_picker`.
- Replace `active_admin_comments` with `active_admin_comments_for(resource)`.
- Replace `attributes_table` with `attributes_table_for(resource)` in sidebars.
## Troubleshooting
### CSS not building
- Ensure `tailwindcss-rails` is pinned to `~> 4.4.0`.
- Run `bundle binstubs tailwindcss-ruby --force`.
- Confirm `bin/tailwindcss` exists.
### ActiveAdmin styles not loading
- Verify `app/assets/builds/active_admin.css` exists.
- Check that `active_admin.tailwind.css` imports `activeadmin-tom_select/css`.
### Tom Select not initializing
- Verify `window.TomSelect` in the console.
- Ensure `setupAutoInit()` is called.
## Migration Checklist
- [ ] Update ActiveAdmin to 4.0.0.beta19
- [ ] Use Tailwind v4 `@import` + `@config`
- [ ] Add `tailwindcss-rails` (~> 4.4.0) and binstub
- [ ] Create `tailwind-active_admin.config.mjs` (ESM)
- [ ] Update rake tasks to use `bin/tailwindcss` (no `-c`)
- [ ] Rebuild assets and verify UI

371
docs/activeadmin-4-changelog.md Обычный файл
Просмотреть файл

@@ -0,0 +1,371 @@
# ActiveAdmin v4.0.0 Beta Changelog
This document contains all the changes from ActiveAdmin v4.0.0 beta releases.
**Source**: [https://github.com/activeadmin/activeadmin/releases](https://github.com/activeadmin/activeadmin/releases)
---
## v4.0.0.beta20 (2025-01-27)
### Breaking Changes 🚨
- Drop support for Rails 7.0 and 7.1 [#8908](https://github.com/activeadmin/activeadmin/pull/8908)
### Template Updates 📝
- Link to parent menu item [#8225](https://github.com/activeadmin/activeadmin/pull/8225)
### Enhancements ✨
- resource: allow resource_class to be passed as a String [#8848](https://github.com/activeadmin/activeadmin/pull/8848)
- Remove horizontal padding on comments pagination [#8925](https://github.com/activeadmin/activeadmin/pull/8925)
- Add page anchor to comments form view [#8926](https://github.com/activeadmin/activeadmin/pull/8926)
- Fix vertical spacing on has-many forms [#8927](https://github.com/activeadmin/activeadmin/pull/8927)
- Remove no-wrap from table columns [#8928](https://github.com/activeadmin/activeadmin/pull/8928)
### Bug Fixes 🐛
- Restore pointer cursor on eligible buttons [#8878](https://github.com/activeadmin/activeadmin/pull/8878)
- Ignore extra bundler output when DEBUG is set [#8895](https://github.com/activeadmin/activeadmin/pull/8895)
### Other Changes 🛠
- Test supported Rails versions against Ruby 4.0 [#8898](https://github.com/activeadmin/activeadmin/pull/8898)
**Full Changelog**: [v4.0.0.beta19...v4.0.0.beta20](https://github.com/activeadmin/activeadmin/compare/v4.0.0.beta19...v4.0.0.beta20)
---
## v4.0.0.beta19 (2024-11-20)
### Breaking Changes 🚨
- Bump tailwind from 3.4.18 to 4.1.17 [#8709](https://github.com/activeadmin/activeadmin/pull/8709)
### Template Updates 📝
- Bump tailwind from 3.4.18 to 4.1.17 [#8709](https://github.com/activeadmin/activeadmin/pull/8709)
### Bug Fixes 🐛
- Remove self-reference to ActiveAdmin node package [#8847](https://github.com/activeadmin/activeadmin/pull/8847)
**Full Changelog**: [v4.0.0.beta18...v4.0.0.beta19](https://github.com/activeadmin/activeadmin/compare/v4.0.0.beta18...v4.0.0.beta19)
---
## v4.0.0.beta18 (2024-11-01)
### Enhancements ✨
- Add Rails 8.1.0 compatibility [#8837](https://github.com/activeadmin/activeadmin/pull/8837)
**Full Changelog**: [v4.0.0.beta17...v4.0.0.beta18](https://github.com/activeadmin/activeadmin/compare/v4.0.0.beta17...v4.0.0.beta18)
---
## v4.0.0.beta17 (2024-10-21)
### Breaking Changes 🚨
- Preserve custom string labels in AttributesTable headers [#8815](https://github.com/activeadmin/activeadmin/pull/8815)
### Enhancements ✨
- Update French locales [#8770](https://github.com/activeadmin/activeadmin/pull/8770)
- Improve text color contrast [#8535](https://github.com/activeadmin/activeadmin/pull/8535)
- Remove unnecessary base CSS styles [#8803](https://github.com/activeadmin/activeadmin/pull/8803)
- Update dark mode CSS styles [#8809](https://github.com/activeadmin/activeadmin/pull/8809)
**Full Changelog**: [v4.0.0.beta16...v4.0.0.beta17](https://github.com/activeadmin/activeadmin/compare/v4.0.0.beta16...v4.0.0.beta17)
---
## v4.0.0.beta16 (2024-07-23)
### Breaking Changes 🚨
- Drop Ruby 3.1 and update dependencies [#8760](https://github.com/activeadmin/activeadmin/pull/8760)
- Remove Tabs component [#8762](https://github.com/activeadmin/activeadmin/pull/8762)
### Template Updates 📝
- Remove `frozen_string_literal` comment from `.arb` templates [#8600](https://github.com/activeadmin/activeadmin/pull/8600)
### Enhancements ✨
- Bump Formtastic to 5.0 and remove legacy code [#8613](https://github.com/activeadmin/activeadmin/pull/8613)
- Add Polish pagination entries translations [#8636](https://github.com/activeadmin/activeadmin/pull/8636)
- Support sortable argument in id_column [#8639](https://github.com/activeadmin/activeadmin/pull/8639)
- Support title for id_column [#8641](https://github.com/activeadmin/activeadmin/pull/8641)
- Update pt-BR translations [#8679](https://github.com/activeadmin/activeadmin/pull/8679)
- Upgrade Flowbite dependency to v3.1.2 [#8692](https://github.com/activeadmin/activeadmin/pull/8692)
- Add some :uk locales [#8732](https://github.com/activeadmin/activeadmin/pull/8732)
### Bug Fixes 🐛
- Fix deprecation warning in Ruby 3.4 [#8593](https://github.com/activeadmin/activeadmin/pull/8593)
- Fix circular require warning in `belongs_to.rb` [#8599](https://github.com/activeadmin/activeadmin/pull/8599)
- Fix pagination truncate translation key [#8678](https://github.com/activeadmin/activeadmin/pull/8678)
- Fix typo in batch_actions locale translation key [#8712](https://github.com/activeadmin/activeadmin/pull/8712)
- Enhance main navbar to improve bouncing on macOS [#8727](https://github.com/activeadmin/activeadmin/pull/8727)
- Remove double bottom border on last table row [#8761](https://github.com/activeadmin/activeadmin/pull/8761)
### Other Changes 🛠
- Normalize i18n locale files [#8715](https://github.com/activeadmin/activeadmin/pull/8715)
**Full Changelog**: [v4.0.0.beta15...v4.0.0.beta16](https://github.com/activeadmin/activeadmin/compare/v4.0.0.beta15...v4.0.0.beta16)
---
## v4.0.0.beta15 (2024-12-07)
### Template Updates 📝
- Use ESM in tailwind config template [#8568](https://github.com/activeadmin/activeadmin/pull/8568)
### Enhancements ✨
- Update Korean locale with new translations [#8554](https://github.com/activeadmin/activeadmin/pull/8554)
- Update Arabic locale translations [#8555](https://github.com/activeadmin/activeadmin/pull/8555)
- Fix an issue with Arabic translation [#8557](https://github.com/activeadmin/activeadmin/pull/8557)
- Update Russian locale with new translations [#8558](https://github.com/activeadmin/activeadmin/pull/8558)
**Full Changelog**: [v4.0.0.beta14...v4.0.0.beta15](https://github.com/activeadmin/activeadmin/compare/v4.0.0.beta14...v4.0.0.beta15)
---
## v4.0.0.beta14 (2024-11-25)
### Breaking Changes 🚨
- Drop support for Rails 6.1 [#8449](https://github.com/activeadmin/activeadmin/pull/8449)
- Drop Ruby 3.0 compatibility [#8489](https://github.com/activeadmin/activeadmin/pull/8489)
### Enhancements ✨
- Add polish translations for search status [#8487](https://github.com/activeadmin/activeadmin/pull/8487)
- Update zh-TW & ja locale with new v4 keys [#8521](https://github.com/activeadmin/activeadmin/pull/8521)
- Update zh-CN locale with new v4 keys [#8546](https://github.com/activeadmin/activeadmin/pull/8546)
- Improve v3 docs regarding compatibility with vite_rails [#8549](https://github.com/activeadmin/activeadmin/pull/8549)
- Remove redundant safe navigation operator [#8528](https://github.com/activeadmin/activeadmin/pull/8528)
- Use safe navigation for `pundit_default_policy` [#8530](https://github.com/activeadmin/activeadmin/pull/8530)
- Use safe navigation operator in layout helper [#8533](https://github.com/activeadmin/activeadmin/pull/8533)
### Bug Fixes 🐛
- run update_resource inside a transaction to avoid autosaving relationships through assign_attributes when the record is invalid [#7437](https://github.com/activeadmin/activeadmin/pull/7437)
- Fix attributes passed to form has_many not being set on new record form items [#8550](https://github.com/activeadmin/activeadmin/pull/8550)
- Convert plugin.js to ESM because package.json has type set to module [#8536](https://github.com/activeadmin/activeadmin/pull/8536)
### Other Changes 🛠
- Migrate docs to VitePress [#8194](https://github.com/activeadmin/activeadmin/pull/8194)
**Full Changelog**: [v4.0.0.beta13...v4.0.0.beta14](https://github.com/activeadmin/activeadmin/compare/v4.0.0.beta13...v4.0.0.beta14)
---
## v4.0.0.beta13 (2024-09-24)
### Enhancements ✨
- Add polish translations for v4 keys [#8481](https://github.com/activeadmin/activeadmin/pull/8481)
- Add spanish translations for v4 keys [#8483](https://github.com/activeadmin/activeadmin/pull/8483)
- Prefer `require_relative` for internal requires [#8482](https://github.com/activeadmin/activeadmin/pull/8482)
**Full Changelog**: [v4.0.0.beta12...v4.0.0.beta13](https://github.com/activeadmin/activeadmin/compare/v4.0.0.beta12...v4.0.0.beta13)
---
## v4.0.0.beta12 (2024-09-15)
### Enhancements ✨
- Bump `inherited_resources` requirement to `~> 2.0` [#8477](https://github.com/activeadmin/activeadmin/pull/8477)
**Full Changelog**: [v4.0.0.beta11...v4.0.0.beta12](https://github.com/activeadmin/activeadmin/compare/v4.0.0.beta11...v4.0.0.beta12)
---
## v4.0.0.beta11 (2024-08-31)
### Enhancements ✨
- Unify specifying label in attributes_table component [#8458](https://github.com/activeadmin/activeadmin/pull/8458)
- Optimize count query for `pagination_total: false` option [#6911](https://github.com/activeadmin/activeadmin/pull/6911)
- Use attribute_types instead of columns_hash to determine type [#8457](https://github.com/activeadmin/activeadmin/pull/8457)
### Bug Fixes 🐛
- Use consistent text-like inputs selector list for CSS styles [#8456](https://github.com/activeadmin/activeadmin/pull/8456)
**Full Changelog**: [v4.0.0.beta10...v4.0.0.beta11](https://github.com/activeadmin/activeadmin/compare/v4.0.0.beta10...v4.0.0.beta11)
---
## v4.0.0.beta10 (2024-08-24)
### Template Updates 📝
- Add host app's layouts/active_admin to tailwind config [#8430](https://github.com/activeadmin/activeadmin/pull/8430)
### Enhancements ✨
- Support async_count for scopes [#8394](https://github.com/activeadmin/activeadmin/pull/8394)
- Add tbody_html and row_html options to TableFor and IndexAsTable [#8423](https://github.com/activeadmin/activeadmin/pull/8423)
### Bug Fixes 🐛
- Improve form f.inputs attributes rendering [#8439](https://github.com/activeadmin/activeadmin/pull/8439), [#8448](https://github.com/activeadmin/activeadmin/pull/8448)
- Fix batch action with partial and no confirm doesn't submit the form on click [#8442](https://github.com/activeadmin/activeadmin/pull/8442)
**Full Changelog**: [v4.0.0.beta9...v4.0.0.beta10](https://github.com/activeadmin/activeadmin/compare/v4.0.0.beta9...v4.0.0.beta10)
---
## v4.0.0.beta9 (2024-08-04)
### Template Updates 📝
- Add accessible names for navigation buttons [#8338](https://github.com/activeadmin/activeadmin/pull/8338)
### Enhancements ✨
- Better implementation of counter-cache-column check [#8411](https://github.com/activeadmin/activeadmin/pull/8411)
### Other Changes 🛠
- Fix url redirects in documentation [#8407](https://github.com/activeadmin/activeadmin/pull/8407)
**Full Changelog**: [v4.0.0.beta8...v4.0.0.beta9](https://github.com/activeadmin/activeadmin/compare/v4.0.0.beta8...v4.0.0.beta9)
---
## v4.0.0.beta8 (2024-07-27)
### Enhancements ✨
- Update Catalan translation [#8356](https://github.com/activeadmin/activeadmin/pull/8356)
- Allow batch actions without a confirmation dialog [#8389](https://github.com/activeadmin/activeadmin/pull/8389)
- Fix styles for select[multiple] form controls [#8406](https://github.com/activeadmin/activeadmin/pull/8406)
**Full Changelog**: [v4.0.0.beta7...v4.0.0.beta8](https://github.com/activeadmin/activeadmin/compare/v4.0.0.beta7...v4.0.0.beta8)
---
## v4.0.0.beta7 (2024-05-31)
### Enhancements ✨
- Update de locale with new v4 keys [#8325](https://github.com/activeadmin/activeadmin/pull/8325)
- Remove de-CH locale [#8326](https://github.com/activeadmin/activeadmin/pull/8326)
### Security Fixes 🔒
- Fix potential XSS issue when rendering form legends [#8348](https://github.com/activeadmin/activeadmin/pull/8348)
**Full Changelog**: [v4.0.0.beta6...v4.0.0.beta7](https://github.com/activeadmin/activeadmin/compare/v4.0.0.beta6...v4.0.0.beta7)
---
## v4.0.0.beta6 (2024-05-03)
### Breaking Changes 🚨
- Drop Ruby 2.7 support [#8259](https://github.com/activeadmin/activeadmin/pull/8259)
### Template Updates 📝
- Use Tailwind's darkMode selector strategy [#8264](https://github.com/activeadmin/activeadmin/pull/8264)
### Enhancements ✨
- Update zh-CN locale with new v4 keys [#8284](https://github.com/activeadmin/activeadmin/pull/8284)
- Update zh-TW locale with new v4 keys [#8297](https://github.com/activeadmin/activeadmin/pull/8297)
### Bug Fixes 🐛
- Add csv dependency to fix Ruby 3.3 warning [#8303](https://github.com/activeadmin/activeadmin/pull/8303)
**Full Changelog**: [v4.0.0.beta5...v4.0.0.beta6](https://github.com/activeadmin/activeadmin/compare/v4.0.0.beta5...v4.0.0.beta6)
---
## v4.0.0.beta5 (2024-02-14)
### Enhancements ✨
- Improve Italian translation [#8235](https://github.com/activeadmin/activeadmin/pull/8235)
- Bump flowbite to v2.3.0 [#8257](https://github.com/activeadmin/activeadmin/pull/8257)
### Bug Fixes 🐛
- Use an anchor for tabs component toggle [#8242](https://github.com/activeadmin/activeadmin/pull/8242)
**Full Changelog**: [v4.0.0.beta4...v4.0.0.beta5](https://github.com/activeadmin/activeadmin/compare/v4.0.0.beta4...v4.0.0.beta5)
---
## v4.0.0.beta4 (2024-01-17)
### Template Updates 📝
- Move pagination translations to active_admin scope [#8218](https://github.com/activeadmin/activeadmin/pull/8218)
### Enhancements ✨
- Vendor rails-ujs ESM JS [#8217](https://github.com/activeadmin/activeadmin/pull/8217)
- Include vendor JS files in NPM package [#8221](https://github.com/activeadmin/activeadmin/pull/8221)
- Remove i18n-tasks.yml from gem release [#8227](https://github.com/activeadmin/activeadmin/pull/8227)
- Make importmap-rails optional [#8228](https://github.com/activeadmin/activeadmin/pull/8228)
- Exclude primary key from generated resource [#8232](https://github.com/activeadmin/activeadmin/pull/8232)
- Make NPM package compatible with tools like vite_rails [#8234](https://github.com/activeadmin/activeadmin/pull/8234)
### Bug Fixes 🐛
- Ensure form presenter is applied on create/update actions [#8238](https://github.com/activeadmin/activeadmin/pull/8238)
**Full Changelog**: [v4.0.0.beta3...v4.0.0.beta4](https://github.com/activeadmin/activeadmin/compare/v4.0.0.beta3...v4.0.0.beta4)
---
## v4.0.0.beta3 (2024-01-06)
- Include additional files in gem release [#8212](https://github.com/activeadmin/activeadmin/pull/8212)
**Full Changelog**: [v4.0.0.beta2...v4.0.0.beta3](https://github.com/activeadmin/activeadmin/compare/v4.0.0.beta2...v4.0.0.beta3)
---
## v4.0.0.beta2 (2024-01-06)
- Include vendor directory in gem release [#8211](https://github.com/activeadmin/activeadmin/pull/8211)
**Full Changelog**: [v4.0.0.beta1...v4.0.0.beta2](https://github.com/activeadmin/activeadmin/compare/v4.0.0.beta1...v4.0.0.beta2)
---
## v4.0.0.beta1 (2024-01-06)
**First beta release of ActiveAdmin v4!**
This release represents a complete redesign using TailwindCSS with **mobile web, dark mode and RTL support** and a default, **customizable theme through partials**.
### Key Features
- **TailwindCSS**: Complete migration to TailwindCSS
- **Mobile Support**: Fully responsive design
- **Dark Mode**: Built-in dark mode support
- **RTL Support**: Right-to-left language support
- **ESM JavaScript**: Modern ES modules
- **importmap-rails**: Uses importmap-rails for JS assets
- **Customizable Theme**: Theme customization through partials
### Breaking Changes 🚨
- Requires `cssbundling-rails` and `importmap-rails`
- Removed all SCSS files (sassc-rails dependency removed)
- Complete UI/UX redesign
### Major Changes
- Prep Tailwind CSS migration (multiple PRs: #8035, #8036, #8037, #8116, #8122, #8139, #8155, #8170)
- Remove old, since replaced JS [#8040](https://github.com/activeadmin/activeadmin/pull/8040)
- Replace html/assets related configs with simple partials [#8156](https://github.com/activeadmin/activeadmin/pull/8156)
- Remove sassc-rails and all SCSS files [#8157](https://github.com/activeadmin/activeadmin/pull/8157)
- Extract headers, menu and sidebar components to partials [#8162](https://github.com/activeadmin/activeadmin/pull/8162)
- Use ES format for JS [#8171](https://github.com/activeadmin/activeadmin/pull/8171)
- Extract layout and pages to partials [#8172](https://github.com/activeadmin/activeadmin/pull/8172)
- Use importmap-rails for JS assets [#8186](https://github.com/activeadmin/activeadmin/pull/8186)
- Move kaminari templates to active_admin folder [#8190](https://github.com/activeadmin/activeadmin/pull/8190)
- Improve RTL support all around [#8196](https://github.com/activeadmin/activeadmin/pull/8196)
- Migrate view helpers to app/helpers path [#8202](https://github.com/activeadmin/activeadmin/pull/8202)
### Enhancements ✨
- Provide detail in DB statement timeout error for filters [#8117](https://github.com/activeadmin/activeadmin/pull/8117)
- Use active_admin_authorization as Ransack auth_object option [#8143](https://github.com/activeadmin/activeadmin/pull/8143)
- Update FR locales [#8193](https://github.com/activeadmin/activeadmin/pull/8193)
- Update nl.yml for v4 [#8195](https://github.com/activeadmin/activeadmin/pull/8195)
### Other Changes 🛠
- Introduce RuboCop Performance [#8024](https://github.com/activeadmin/activeadmin/pull/8024)
- Remove multiline ternary operator [#8034](https://github.com/activeadmin/activeadmin/pull/8034)
- Prefer `match?` over `=~` to avoid MatchData [#8138](https://github.com/activeadmin/activeadmin/pull/8138)
**Full Changelog**: [v3.2.0...v4.0.0.beta1](https://github.com/activeadmin/activeadmin/compare/v3.2.0...v4.0.0.beta1)
---
## Summary
**Minimum Requirements (as of v4.0.0.beta20):**
- Rails 7.2+
- Ruby 3.2+
- cssbundling-rails
- importmap-rails (optional as of beta4)
**Key Migration Path:**
The v4.0.0 beta series represents a complete redesign of ActiveAdmin using TailwindCSS. The migration requires:
1. Installing `cssbundling-rails` and configuring TailwindCSS
2. Installing `importmap-rails` (optional since beta4)
3. Running the assets generator
4. Updating custom CSS/JS from the old SCSS/jQuery patterns
5. Reviewing the [Upgrading guide](https://github.com/activeadmin/activeadmin/blob/master/UPGRADING.md)
See [demo app](https://github.com/activeadmin/demo.activeadmin.info) for a working example.

Просмотреть файл

@@ -1,932 +0,0 @@
# ActiveAdmin 4 Migration Guide for Gem Maintainers
## Overview
This document provides a comprehensive guide for gem maintainers on how to update their gems to support ActiveAdmin 4, based on the changes made to the `activeadmin-searchable_select` gem. The migration involved addressing significant changes in asset handling, JavaScript module systems, dependency management, and CSS selectors.
## Key Migration Steps
### 1. Update Dependency Constraints
#### Ruby Version Requirements
- **Minimum Ruby version**: 3.2 (Ruby 3.0 and 3.1 are dropped in ActiveAdmin 4)
- Update your gemspec: `spec.required_ruby_version = '>= 3.2'`
#### Rails Version Requirements
- **Minimum Rails version**: 7.0 (Rails 6.1 support dropped)
- ActiveAdmin 4 supports Rails 7.x and 8.x
#### ActiveAdmin Version
```ruby
# In gemspec
spec.add_runtime_dependency 'activeadmin', ['>= 1.x', '< 5']
```
### 2. Asset Pipeline Migration
ActiveAdmin 4 moved away from the traditional Rails asset pipeline to modern JavaScript bundlers.
#### Key Changes:
- ActiveAdmin 4 assumes `cssbundling-rails` and `importmap-rails` are installed
- No longer uses `register_stylesheet` or `register_javascript` methods
- Requires explicit JavaScript module initialization
#### CSS bundling pattern (Rails 7 cssbundling + Tailwind)
- Build CSS to `app/assets/builds/active_admin.css` and expose it via `app/assets/config/manifest.js`:
- `//= link_tree ../builds`
- `//= link active_admin.css`
- `//= link active_admin.js`
- `//= link trumbowyg/icons.svg` (when using Trumbowyg)
- Keep a single Tailwind config at the Rails app root (avoid duplicates). Using ESM works well:
- `tailwind.config.mjs` with `import activeAdminPlugin from '@activeadmin/activeadmin/plugin'`
- Source file `app/assets/stylesheets/active_admin_source.css` contains Tailwind directives, gem overrides and imports.
- If Tailwind CLI does not inline vendor `@import` from `node_modules`, concatenate vendor CSS before building. Example build script:
```json
// spec/internal/package.json
{
"scripts": {
"build:css": "node ./build_css.js"
}
}
```
```js
// spec/internal/build_css.js
const fs = require('fs');
const path = require('path');
const { spawnSync } = require('child_process');
const root = __dirname;
const inputPath = path.join(root, 'app/assets/stylesheets/active_admin_source.css');
const vendorCssPath = path.join(root, 'node_modules/trumbowyg/dist/ui/trumbowyg.css');
const tmpPath = path.join(root, 'app/assets/stylesheets/__aa_tmp.css');
const outPath = path.join(root, 'app/assets/builds/active_admin.css');
const src = fs.readFileSync(inputPath, 'utf8').split(/\r?\n/);
const vendorCss = fs.readFileSync(vendorCssPath, 'utf8');
const tailwind = ['@tailwind base;','@tailwind components;','@tailwind utilities;'].join('\n');
const body = src.slice(3).filter(l => !l.includes('trumbowyg.css')).join('\n');
fs.writeFileSync(tmpPath, `${tailwind}\n\n${vendorCss}\n\n${body}`);
spawnSync('npx', ['tailwindcss','-c', path.join(root,'tailwind.config.mjs'),'-i', tmpPath,'-o', outPath], { stdio: 'inherit', cwd: root });
fs.unlinkSync(tmpPath);
```
This ensures vendor CSS (e.g., Trumbowyg) ships inside the built `active_admin.css` while keeping Tailwind at the top of the cascade so overrides behave as expected.
#### JavaScript Module Support
Create multiple module formats to support different bundlers:
1. **ESM Module** (`your_gem.esm.js`):
```javascript
import $ from 'jquery';
import select2 from 'select2'; // Or your jQuery plugin
// Critical: Initialize jQuery plugins on the jQuery object for production builds
// This ensures the plugin methods are available on jQuery selections
select2($);
// Ensure jQuery is globally available for other scripts
window.$ = window.jQuery = $;
// Your initialization code wrapped in a DOM ready handler
$(() => {
// Initialize your plugin on specific selectors
$('.your-selector').yourPlugin({
// plugin options
});
// Listen for Turbo/Turbolinks events for dynamic content
$(document).on('turbo:load turbolinks:load', () => {
$('.your-selector').yourPlugin();
});
// For ActiveAdmin's dynamic content (filters, forms)
$(document).on('has_many_add:after', '.has_many_container', () => {
$('.your-selector').yourPlugin();
});
});
// Export for use as a module
export default function initializeYourGem() {
// Initialization logic
}
```
2. **Traditional Module** (`your_gem.js` for backward compatibility):
```javascript
//= require jquery
//= require select2
(function($) {
'use strict';
$(document).ready(function() {
$('.your-selector').yourPlugin();
});
// Turbolinks/Turbo support
$(document).on('turbo:load turbolinks:load', function() {
$('.your-selector').yourPlugin();
});
})(jQuery);
```
3. **CDN-compatible version** (for importmap users):
```javascript
// Assumes jQuery and plugins are loaded via CDN
(() => {
'use strict';
const $ = window.jQuery || window.$;
if (!$) {
console.error('jQuery is required for YourGem');
return;
}
// Wait for DOM ready
$(() => {
$('.your-selector').yourPlugin();
});
})();
```
### 3. Installation Generator
Create a generator to help users set up your gem with different bundlers:
```ruby
module YourGem
module Generators
class InstallGenerator < Rails::Generators::Base
class_option :bundler,
type: :string,
default: 'esbuild',
enum: %w[esbuild importmap webpack]
def setup_javascript
case options[:bundler]
when 'esbuild'
setup_esbuild
when 'importmap'
setup_importmap
when 'webpack'
setup_webpack
end
end
private
def setup_esbuild
# Add imports to app/javascript/active_admin.js
append_to_file 'app/javascript/active_admin.js' do
<<~JS
import $ from 'jquery';
import yourPlugin from 'your-plugin';
// Initialize plugin on jQuery
yourPlugin($);
window.$ = window.jQuery = $;
import '@your-scope/your-gem';
JS
end
end
def setup_importmap
# Add pins to config/importmap.rb
append_to_file 'config/importmap.rb' do
<<~RUBY
pin "jquery", to: "https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"
pin "your-plugin", to: "https://cdn.jsdelivr.net/npm/your-plugin/dist/plugin.min.js"
pin "your-gem", to: "your-gem.js"
RUBY
end
end
end
end
end
```
### 4. NPM Package Publishing
If your gem includes JavaScript, consider publishing an NPM package:
#### Package.json Configuration
```json
{
"name": "@activeadmin/your-gem",
"version": "1.0.0",
"description": "Your gem description for ActiveAdmin",
"main": "src/index.js",
"module": "src/index.js",
"exports": {
".": {
"import": "./src/index.js",
"require": "./src/index.js",
"default": "./src/index.js"
},
"./css": "./src/styles.scss"
},
"peerDependencies": {
"jquery": ">= 3.0, < 5",
"select2": "^4.0.13" // Add your dependencies here
},
"files": [
"src/**/*",
"app/assets/**/*",
"vendor/assets/**/*"
],
"scripts": {
"prepare_sources": "mkdir -p src && cp -r app/assets/javascripts/active_admin/* src/ && cp -r app/assets/stylesheets/active_admin/* src/",
"prepublishOnly": "npm run prepare_sources"
},
"repository": {
"type": "git",
"url": "https://github.com/your-org/your-gem.git"
},
"keywords": ["activeadmin", "rails", "your-feature"],
"author": "Your Name",
"license": "MIT"
}
```
#### Preparing JavaScript Assets for NPM
Create a script to copy your assets to the NPM package structure:
```bash
#!/bin/bash
# scripts/prepare_npm_package.sh
# Create src directory for NPM
mkdir -p src
# Copy JavaScript files
cp -r app/assets/javascripts/active_admin/* src/
# Copy SCSS files if needed
cp -r app/assets/stylesheets/active_admin/* src/
# Ensure ESM module is included
cp app/assets/javascripts/active_admin/your_gem.esm.js src/index.js
```
### 5. CSS Selector Updates
ActiveAdmin 4 introduced several CSS class changes:
| ActiveAdmin 3.x | ActiveAdmin 4.x |
|----------------|-----------------|
| `.filter_form` | `.filters-form` |
| `.tabs` component | Removed - use divs with Tailwind |
| `.columns` component | Replaced with Tailwind grid |
Update your JavaScript and CSS accordingly:
```javascript
// Old
$('.filter_form select').select2();
// New
$('.filters-form select').select2();
```
### 6. Testing Updates with Combustion
#### Complete Combustion Workflow for ActiveAdmin 4 Gems
**CRITICAL**: This workflow is specifically for testing ActiveAdmin extension gems with Combustion.
##### Step 1: Add Dependencies to Gemfile
```ruby
# Gemfile (for development/testing)
gem 'combustion'
gem 'importmap-rails', '~> 2.0' # Required for ActiveAdmin 4
```
##### Step 2: Run Combustion Generator (MANDATORY!)
```bash
# NEVER manually create spec/internal structure!
bundle exec combust
```
This creates:
- `spec/internal/` - minimal Rails app structure
- `config.ru` - in gem root for `bundle exec rackup`
- Basic Rails directories and config files
##### Step 3: Set Up Test App Structure
After generator, create these files:
```bash
# Create necessary directories
mkdir -p spec/internal/app/models
mkdir -p spec/internal/app/admin
mkdir -p spec/internal/app/assets/stylesheets
mkdir -p spec/internal/app/javascript
mkdir -p spec/internal/config/initializers
```
##### Basic Combustion Configuration
```ruby
# spec/rails_helper.rb
ENV['RAILS_ENV'] ||= 'test'
require 'combustion'
# Initialize Combustion with only needed components
Combustion.path = 'spec/internal'
Combustion.initialize!(:active_record, :action_controller, :action_view) do
config.load_defaults Rails::VERSION::STRING.to_f if Rails::VERSION::MAJOR >= 7
end
require 'rspec/rails'
require 'capybara/rails'
```
##### Step 4: Configure config.ru (CRITICAL Loading Order!)
```ruby
# config.ru - MUST control loading order for ActiveAdmin!
require "rubygems"
require "bundler"
# DON'T use Bundler.require - it loads gems too early!
Bundler.setup(:default, :development)
# Load Rails and combustion first
require 'combustion'
# Initialize Combustion with Rails components
Combustion.initialize! :active_record, :action_controller, :action_view do
config.load_defaults Rails::VERSION::STRING.to_f if Rails::VERSION::MAJOR >= 7
end
# NOW we can load ActiveAdmin and its dependencies after Rails is initialized
require 'importmap-rails'
require 'active_admin'
require 'your_activeadmin_gem'
run Combustion::Application
```
##### Step 5: Configure ActiveAdmin Assets
```ruby
# spec/internal/app/assets/stylesheets/active_admin.css
@tailwind base;
@tailwind components;
@tailwind utilities;
```
```ruby
# spec/internal/config/importmap.rb
pin "@activeadmin/activeadmin", to: "active_admin.js", preload: true
```
```javascript
// spec/internal/app/javascript/active_admin.js
// Placeholder for ActiveAdmin JS
console.log("ActiveAdmin loaded");
```
##### Step 6: Set Up Test Models and Admin Resources
```ruby
# spec/internal/db/schema.rb
ActiveRecord::Schema.define do
create_table :active_admin_comments, force: true do |t|
t.string :namespace
t.text :body
t.references :resource, polymorphic: true
t.references :author, polymorphic: true
t.timestamps
end
create_table :posts, force: true do |t|
t.string :title
t.text :body
t.text :description
t.timestamps
end
end
```
```ruby
# spec/internal/config/routes.rb
Rails.application.routes.draw do
ActiveAdmin.routes(self)
root to: 'admin/dashboard#index'
end
```
```ruby
# spec/internal/config/initializers/active_admin.rb
ActiveAdmin.setup do |config|
config.site_title = "Test App"
config.authentication_method = false
config.current_user_method = false
config.batch_actions = true
end
```
##### Step 7: Configure rails_helper.rb
```ruby
# spec/rails_helper.rb
ENV['RAILS_ENV'] ||= 'test'
require 'combustion'
Combustion.path = 'spec/internal'
Combustion.initialize!(:active_record, :action_controller, :action_view) do
config.load_defaults Rails::VERSION::STRING.to_f if Rails::VERSION::MAJOR >= 7
end
require 'rspec/rails'
require 'capybara/rails'
```
##### Step 8: Running the Test App
```bash
# Start the test app server
bundle exec rackup
# Visit http://localhost:9292/admin
```
#### Critical Testing Pitfall: Model Registration Conflicts
**Problem**: Dynamic ActiveAdmin registrations in tests conflict with static admin files.
**Solution**: Choose ONE approach per model:
1. **Static Registration** (for consistent configs):
```ruby
# spec/internal/app/admin/users.rb
ActiveAdmin.register User do
permit_params :name, :email
# Fixed configuration
end
```
2. **Dynamic Registration** (for varying configs):
```ruby
# spec/support/active_admin_helpers.rb
module ActiveAdminHelpers
module_function
def setup
ActiveAdmin.application = nil
yield # Dynamic registration block
reload_routes!
end
def reload_routes!
Rails.application.reload_routes!
end
end
# In test - NO static admin file for Post model
ActiveAdminHelpers.setup do
ActiveAdmin.register(Post) do
# Test-specific configuration
end
end
```
**Important**: Never mix static and dynamic registration for the same model!
#### Capybara Configuration with Playwright
```ruby
# spec/support/capybara.rb
require 'capybara-playwright-driver'
Capybara.register_driver :playwright do |app|
Capybara::Playwright::Driver.new(
app,
browser_type: :chromium,
headless: true,
viewport: { width: 1920, height: 1080 }
)
end
Capybara.default_driver = :rack_test
Capybara.javascript_driver = :playwright
# Important: Set server for JS tests
Capybara.server = :puma, { Silent: true }
```
#### Waiting for JavaScript/AJAX in Tests
```ruby
# spec/support/wait_helpers.rb
module WaitHelpers
def wait_for_ajax
Timeout.timeout(Capybara.default_max_wait_time) do
sleep 0.1
loop until finished_all_ajax_requests?
end
end
def finished_all_ajax_requests?
page.evaluate_script('jQuery.active').zero?
end
# For Select2 or similar plugins
def wait_for_select2
expect(page).to have_css('.select2-container', wait: 5)
end
end
RSpec.configure do |config|
config.include WaitHelpers, type: :feature
end
```
### 7. Production Build Issues
Common production issues and solutions:
#### Issue: JavaScript plugin not initialized
**Solution**: Explicitly initialize jQuery plugins
```javascript
import select2 from 'select2';
import $ from 'jquery';
// This is critical for production builds
select2($);
```
#### Issue: jQuery not globally available
**Solution**: Ensure global assignment
```javascript
window.$ = window.jQuery = $;
```
#### Issue: Assets not loading in production
**Solution**: Use CDN fallbacks or vendor assets
```ruby
# In your gem's engine.rb
class Engine < ::Rails::Engine
initializer 'your_gem.assets' do |app|
if Rails.env.production?
# Add fallback assets
end
end
end
```
### 8. CI/CD Updates
Update your GitHub Actions workflow:
```yaml
name: CI
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
ruby: ['3.2', '3.3']
rails: ['7.0', '7.1', '7.2', '8.0']
activeadmin: ['4.0.0.beta16']
steps:
- uses: actions/checkout@v4
- name: Set up Ruby
uses: ruby/setup-ruby@v1
with:
ruby-version: ${{ matrix.ruby }}
bundler-cache: true
- name: Install Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install npm dependencies
run: npm install
- name: Install Playwright browsers
run: npx playwright install chromium
- name: Run tests
run: bundle exec rspec
```
### 9. Appraisals Configuration
Use Appraisal gem to test against multiple versions:
```ruby
# Appraisals file
appraise 'rails-7.x-active-admin-4.x' do
gem 'rails', '~> 7.0'
gem 'activeadmin', '~> 4.0.0.beta16'
gem 'propshaft' # Required - Sprockets not supported
end
appraise 'rails-8.x-active-admin-4.x' do
gem 'rails', '~> 8.0'
gem 'activeadmin', '~> 4.0.0.beta16'
# Rails 8 includes Propshaft by default
end
```
### 10. Common Pitfalls and Solutions
#### Pitfall 1: Select2 or similar jQuery plugins not working
**Root Cause**: Plugin not attached to jQuery object in production
**Solution**: Explicitly call `plugin($)` after importing
```javascript
import select2 from 'select2';
import $ from 'jquery';
select2($); // Critical - attaches plugin to jQuery
```
#### Pitfall 2: CSS classes not found
**Root Cause**: ActiveAdmin 4 changed many CSS selectors
**Solution**: Search and replace old selectors with new ones
- `.filter_form``.filters-form`
- `.select2-container` needs explicit initialization in tests
#### Pitfall 3: Tests passing locally but failing in CI
**Root Cause**: Missing JavaScript dependencies or browser drivers
**Solution**:
```yaml
# .github/workflows/ci.yml
- name: Install Playwright browsers
run: npx playwright install chromium
```
#### Pitfall 4: Assets not compiling in production
**Root Cause**: Missing bundler configuration
**Solution**: Provide clear setup instructions for each bundler type in your README
#### Pitfall 5: Model registration conflicts in tests
**Root Cause**: Static admin files override dynamic test registrations
**Solution**:
- Delete static admin files for models that need dynamic config
- Keep static files only for models with consistent config
- Never mix both approaches for the same model
#### Pitfall 6: Input HTML options not passing through
**Root Cause**: Options can be lost during form DSL processing
**Solution**: Test with clean models not affected by other registrations
```ruby
# Test with a model that has no static admin file
ActiveAdmin.register(TestModel) do
form do |f|
f.input :field, as: :searchable_select,
input_html: { class: 'custom-class' }
end
end
```
#### Pitfall 7: Flaky JavaScript tests
**Root Cause**: Not waiting for AJAX/DOM updates
**Solution**: Add proper wait helpers
```ruby
def wait_for_select2
expect(page).to have_css('.select2-container', wait: 5)
end
```
#### Pitfall 8: Rails 8 compatibility issues
**Root Cause**: Formtastic 5.0 changes, Ransack updates
**Solution**:
- Test against multiple Rails versions using Appraisal
- Ensure Ransack methods are defined in models
```ruby
def self.ransackable_attributes(_auth_object = nil)
%w[name title]
end
```
#### Pitfall 9: Combustion and ActiveAdmin Loading Order Issues
**Root Cause**: ActiveAdmin requires Rails components at load time, conflicts with Combustion's initialization
**Critical Issue**: ActiveAdmin's `Bundler.require` loads before Rails is initialized by Combustion
**Symptoms**:
- `uninitialized constant Formtastic::ActionView`
- `uninitialized constant ActiveSupport::Autoload`
- `uninitialized constant #<Class:ActiveAdmin>::Importmap`
- Rackup fails with various Rails component loading errors
**Solution**:
- Use `Bundler.setup` instead of `Bundler.require` in config.ru
- Load ActiveAdmin AFTER Combustion initializes Rails
- Include importmap-rails for ActiveAdmin 4
- Don't require ActiveAdmin components in gem's main file
```ruby
# Bad: In lib/your_gem.rb
require 'active_admin' # This loads too early!
require 'formtastic/inputs/your_input'
# Good: In engine.rb
initializer 'your_gem.setup', after: :load_config_initializers do
require 'active_admin' if defined?(Rails.application)
ActiveSupport.on_load(:active_admin) do
require 'formtastic/inputs/your_input'
end
end
```
#### Pitfall 10: ActiveAdmin 4 Asset Pipeline Requirements (CRITICAL FOR COMBUSTION GEMS)
**Root Cause**: ActiveAdmin 4 uses Tailwind CSS v3 with custom plugin, requires compilation
**Critical Issue**: CSS must be compiled through Tailwind with ActiveAdmin plugin
**Symptoms**:
- Unstyled admin pages (no proper layout, just basic HTML)
- CSS file exists but has 0 bytes or wrong content
- `The asset "active_admin.css" is not present in the asset pipeline`
**Complete Solution for Combustion-based Gems**:
1. **Add Dependencies** (Gemfile):
```ruby
gem 'importmap-rails', '~> 2.0'
gem 'tailwindcss-rails' # For bundled tailwindcss executable
```
2. **Install NPM packages** (in spec/internal):
```bash
cd spec/internal
npm init -y
npm install --save-dev tailwindcss@^3 # Use v3, not v4!
npm install --save-dev @activeadmin/activeadmin # For plugin (optional)
```
3. **Copy ActiveAdmin Plugin** (from Ruby gem):
```bash
cp $(bundle show activeadmin)/plugin.js spec/internal/activeadmin-plugin.js
```
4. **Create Tailwind Config** (spec/internal/tailwind.config.mjs):
```javascript
import activeAdminPlugin from './activeadmin-plugin.js';
import { execSync } from 'child_process';
const activeAdminPath = execSync('bundle show activeadmin', { encoding: 'utf-8' }).trim();
export default {
content: [
`${activeAdminPath}/app/views/**/*.{arb,erb,html,rb}`,
'./app/admin/**/*.{arb,erb,html,rb}',
'./app/views/**/*.{arb,erb,html}',
'./app/javascript/**/*.js'
],
darkMode: 'selector',
plugins: [activeAdminPlugin]
}
```
5. **Create Source CSS** (spec/internal/app/assets/stylesheets/active_admin_source.css):
```css
@tailwind base;
@tailwind components;
@tailwind utilities;
```
6. **Build CSS**:
```bash
cd spec/internal
npx tailwindcss -c tailwind.config.mjs \
-i app/assets/stylesheets/active_admin_source.css \
-o app/assets/stylesheets/active_admin_compiled.css \
--minify
```
7. **Configure Sprockets** (spec/internal/app/assets/stylesheets/active_admin.css):
```css
/*
* This imports the compiled Tailwind CSS with ActiveAdmin styles
*= require ./active_admin_compiled
*/
```
8. **Update Manifest** (spec/internal/app/assets/config/manifest.js):
```javascript
//= link_tree ../builds
//= link active_admin.css
```
9. **Create Build Task** (lib/tasks/active_admin.rake):
```ruby
namespace :active_admin do
desc 'Build Active Admin Tailwind stylesheets'
task :build do
require 'fileutils'
input = File.expand_path('../../spec/internal/app/assets/stylesheets/active_admin_source.css', __dir__)
output = File.expand_path('../../spec/internal/app/assets/stylesheets/active_admin_compiled.css', __dir__)
config = File.expand_path('../../spec/internal/tailwind.config.mjs', __dir__)
FileUtils.mkdir_p(File.dirname(output))
command = ['npx', 'tailwindcss', '-c', config, '-i', input, '-o', output, '--minify']
puts "Building Tailwind CSS: #{command.join(' ')}"
system(*command, exception: true)
puts "Tailwind CSS build complete: #{output}"
end
end
```
#### Pitfall 11: Formtastic Custom Inputs Not Loading in Combustion
**Root Cause**: Loading order issues with ActiveAdmin, Formtastic, and custom inputs
**Symptoms**:
- `Formtastic::UnknownInputError: Unable to find input class YourInput`
- Input works in production but not in Combustion test environment
**Solutions**:
1. **Immediate Fix in config.ru** (for Combustion):
```ruby
# config.ru
require 'combustion'
Combustion.initialize! :active_record, :action_controller, :action_view
require 'importmap-rails'
require 'active_admin'
require 'your_gem'
# Critical: Explicitly require custom inputs after everything else
require 'formtastic/inputs/your_input'
run Combustion::Application
```
2. **Engine Initialization Fix**:
```ruby
# lib/your_gem/engine.rb
initializer 'your_gem.setup', after: :load_config_initializers do
require 'active_admin' if defined?(Rails.application)
# Load immediately AND hook into ActiveAdmin
require 'formtastic/inputs/your_input'
ActiveSupport.on_load(:active_admin) do
require 'formtastic/inputs/your_input'
end
end
```
3. **Workaround Using Standard Inputs**:
```ruby
# If custom input isn't loading, use standard input with same attributes
f.input :field, as: :text, input_html: {
class: 'your-input-class',
'data-your-attribute': true
}
```
**Note**: After making these changes, restart the server for them to take effect.
## Migration Checklist
- [ ] Update Ruby version requirement to >= 3.2
- [ ] Update Rails version requirement to >= 7.0
- [ ] Update ActiveAdmin dependency to support 4.x
- [ ] Create ESM JavaScript modules
- [ ] Add installation generator for different bundlers
- [ ] Publish NPM package (if applicable)
- [ ] Update CSS selectors (`.filter_form``.filters-form`)
- [ ] Fix jQuery plugin initialization for production
- [ ] Update test suite for new asset handling
- [ ] Configure CI for multiple version testing
- [ ] Update documentation with setup instructions
- [ ] Test with esbuild, webpack, and importmap
- [ ] Add CDN fallbacks for JavaScript dependencies
- [ ] Handle both Sprockets and Propshaft
## Example Implementation
See the full implementation in the `activeadmin-searchable_select` gem:
- [Installation Generator](../lib/generators/active_admin/searchable_select/install/install_generator.rb)
- [ESM Module](../app/assets/javascripts/active_admin/searchable_select.esm.js)
- [Package.json](../package.json)
- [CI Configuration](../.github/workflows/ci.yml)
## Resources
- [ActiveAdmin 4.0 Breaking Changes](./activeadmin-4-changes.md)
- [ActiveAdmin 4.0 Release Notes](https://github.com/activeadmin/activeadmin/releases)
- [Rails 7+ Asset Pipeline Guide](https://guides.rubyonrails.org/asset_pipeline.html)
- [esbuild Rails Documentation](https://github.com/rails/jsbundling-rails)
- [Importmap Rails Documentation](https://github.com/rails/importmap-rails)
## Conclusion
Migrating a gem to support ActiveAdmin 4 requires careful attention to:
1. Modern JavaScript module systems
2. Flexible asset pipeline support
3. Updated CSS selectors and components
4. Proper jQuery plugin initialization
5. Comprehensive testing across different setups
The key to success is providing multiple paths for users with different asset pipeline configurations while maintaining backward compatibility where possible.

Просмотреть файл

@@ -1,417 +0,0 @@
# ActiveAdmin 4 Gem Update Guide
This guide documents the process of updating a gem to support ActiveAdmin 4 with Propshaft, Tailwind CSS, and modern Rails 8 asset pipeline.
## Overview
ActiveAdmin 4 represents a significant architectural shift from previous versions:
- **CSS**: From Sprockets/SCSS to Tailwind CSS with custom build process
- **JavaScript**: From jQuery to vanilla JavaScript with ES modules
- **Asset Pipeline**: From Sprockets to Propshaft (Rails 8 default)
- **Styling**: From pre-built CSS to user-built Tailwind CSS
## Key Changes Required
### 1. Gem Structure Changes
#### Remove CSS Assets
ActiveAdmin 4 gems should NOT ship CSS files. Users build their own CSS with Tailwind.
```
# Remove these directories/files:
vendor/assets/stylesheets/
app/assets/stylesheets/*.scss
```
#### JavaScript Assets
Keep only initialization JavaScript in vendor/assets:
```
vendor/assets/javascripts/your_gem_name.js # Vanilla JS, no jQuery
```
### 2. Engine Configuration
Update `lib/your_gem/engine.rb`:
```ruby
module YourGem
class Engine < ::Rails::Engine
# Propshaft automatically includes vendor/assets and app/assets paths
initializer 'your_gem.assets' do |app|
# For Propshaft (Rails 8 default)
if defined?(Propshaft)
app.config.assets.precompile += %w[
your_gem_name.js
]
# For Sprockets (legacy support)
elsif app.config.respond_to?(:assets)
app.config.assets.precompile += %w[
your_gem_name.js
]
end
end
end
end
```
### 3. JavaScript Migration
#### Remove jQuery Dependencies
Convert all jQuery code to vanilla JavaScript:
```javascript
// Old (jQuery)
$(document).ready(function() {
$('.quill-editor').each(function() {
// initialization
});
});
// New (Vanilla JS)
document.addEventListener('DOMContentLoaded', function() {
document.querySelectorAll('.quill-editor').forEach(function(element) {
// initialization
});
});
```
#### Event Handling
Use modern event delegation:
```javascript
// Support both Turbo and non-Turbo apps
['DOMContentLoaded', 'turbo:load', 'turbolinks:load'].forEach(function(eventName) {
document.addEventListener(eventName, initializeEditors);
});
```
### 4. Test/Dummy App Setup
#### Package.json
Create a proper `package.json` for the test app:
```json
{
"name": "your-gem-test-app",
"private": true,
"scripts": {
"build:js": "node esbuild.config.js",
"build:css": "bundle exec rake active_admin:build",
"build": "npm run build:js && npm run build:css"
},
"dependencies": {
"@activeadmin/activeadmin": "^4.0.0-beta16",
"@rails/ujs": "^7.1.3",
"your-required-npm-package": "^x.x.x"
},
"devDependencies": {
"esbuild": "^0.19.0",
"tailwindcss": "^3.4.17"
}
}
```
#### Tailwind Configuration
Create `tailwind.config.js`:
```javascript
const execSync = require('child_process').execSync;
const activeAdminPath = execSync('bundle show activeadmin', { encoding: 'utf-8' }).trim();
module.exports = {
content: [
`${activeAdminPath}/vendor/javascript/flowbite.js`,
`${activeAdminPath}/plugin.js`,
`${activeAdminPath}/app/views/**/*.{arb,erb,html,rb}`,
'./app/admin/**/*.{arb,erb,html,rb}',
'./app/views/active_admin/**/*.{arb,erb,html,rb}',
'./app/views/admin/**/*.{arb,erb,html,rb}',
'./app/javascript/**/*.js'
],
darkMode: "class",
plugins: [
require('@activeadmin/activeadmin/plugin')
]
};
```
#### CSS Source File Structure
Place source CSS OUTSIDE of Rails asset paths to avoid Propshaft conflicts:
```
spec/dummy/
app/
css/ # NOT in assets/
active_admin_source.css # Source file for Tailwind
assets/
builds/
active_admin.css # Built output
config/
manifest.js # Propshaft manifest
```
#### Active Admin CSS Source
Create `app/css/active_admin_source.css` (or `app/assets/stylesheets/active_admin.css` per the gist):
```css
@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";
/* Import vendor styles if needed */
@import "../../../node_modules/your-package/dist/styles.css";
/* Custom component styles */
@layer components {
.your-component {
@apply border border-gray-300 rounded-md;
}
}
```
#### Build Task
Create `lib/tasks/active_admin.rake`:
```ruby
namespace :active_admin do
desc "Build Active Admin Tailwind stylesheets"
task build: :environment do
command = [
"npx", "tailwindcss",
"-i", Rails.root.join("app/assets/stylesheets/active_admin.css").to_s,
"-o", Rails.root.join("app/assets/builds/active_admin.css").to_s,
"-c", Rails.root.join("tailwind.config.js").to_s,
"-m"
]
system(*command, exception: true)
end
desc "Watch Active Admin Tailwind stylesheets"
task watch: :environment do
command = [
"npx", "tailwindcss",
"--watch",
"-i", Rails.root.join("app/assets/stylesheets/active_admin.css").to_s,
"-o", Rails.root.join("app/assets/builds/active_admin.css").to_s,
"-c", Rails.root.join("tailwind.config.js").to_s,
"-m"
]
system(*command)
end
end
Rake::Task["assets:precompile"].enhance(["active_admin:build"])
```
#### ESBuild Configuration
Create `esbuild.config.js`:
```javascript
const esbuild = require('esbuild');
const railsEnv = process.env.RAILS_ENV || 'development';
const config = {
entryPoints: ['app/javascript/active_admin.js'],
bundle: true,
sourcemap: railsEnv !== 'production',
format: 'esm',
outdir: 'app/assets/builds',
publicPath: '/assets',
loader: {
'.js': 'js',
},
minify: railsEnv === 'production',
plugins: [],
};
if (process.argv.includes('--watch')) {
esbuild.context(config).then((ctx) => {
ctx.watch();
console.log('Watching for changes...');
});
} else {
esbuild.build(config).then(() => {
console.log('Build completed');
}).catch(() => process.exit(1));
}
```
### 5. ActiveAdmin Initializer
Update `config/initializers/active_admin.rb`:
```ruby
ActiveAdmin.setup do |config|
# Register CSS (required for AA4 + Propshaft)
config.register_stylesheet 'active_admin.css'
# Register JavaScript files
config.register_javascript 'active_admin.js'
config.register_javascript 'your_gem_name.js'
# ... other configuration
end
```
### 6. Propshaft Manifest
Update `app/assets/config/manifest.js`:
```javascript
//= link_tree ../images
//= link_tree ../builds
//= link active_admin.css
//= link active_admin.js
//= link your_gem_name.js
```
### 7. Common Pitfalls & Solutions
#### Issue: CSS not loading / Only Tailwind directives visible
**Cause**: Propshaft serving source file instead of built file
**Solution**:
- Ensure source CSS is outside `app/assets/` or named differently
- Check that build process outputs to `app/assets/builds/`
- Verify `config.register_stylesheet 'active_admin.css'` in initializer
#### Issue: Missing ActiveAdmin layout styles
**Cause**: ActiveAdmin plugin not loaded or content paths missing
**Solution**:
- Ensure `@activeadmin/activeadmin` npm package is installed
- Add ActiveAdmin gem paths to Tailwind content configuration
- Use `require('@activeadmin/activeadmin/plugin')` in Tailwind config
#### Issue: JavaScript not initializing
**Cause**: Turbo/Turbolinks events not handled
**Solution**: Listen for multiple initialization events:
```javascript
['DOMContentLoaded', 'turbo:load', 'turbolinks:load'].forEach(function(eventName) {
document.addEventListener(eventName, initializeComponents);
});
```
#### Issue: Double asset compilation
**Cause**: Both Sprockets and Propshaft trying to handle same files
**Solution**:
- Remove/rename conflicting files in `app/assets/stylesheets/`
- Use specific file names in manifest instead of `link_tree`
### 8. Testing Setup
#### GitHub Actions Workflow
Create separate workflows for different ActiveAdmin versions:
```yaml
name: Tests
on: [push, pull_request]
jobs:
test-aa4:
runs-on: ubuntu-latest
strategy:
matrix:
ruby: ['3.2', '3.3']
rails: ['7.1', '8.0']
steps:
- uses: actions/checkout@v4
- uses: ruby/setup-ruby@v1
with:
ruby-version: ${{ matrix.ruby }}
bundler-cache: true
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install npm dependencies
run: |
cd spec/dummy
npm install
- name: Build assets
run: |
cd spec/dummy
npm run build
- name: Run tests
run: bundle exec rspec
test-legacy:
runs-on: ubuntu-latest
strategy:
matrix:
ruby: ['3.0', '3.1']
activeadmin: ['2.14', '3.2']
# ... legacy test configuration
```
### 9. Migration Checklist
- [ ] Remove all SCSS/CSS assets from gem
- [ ] Convert JavaScript from jQuery to vanilla JS
- [ ] Create test app package.json with dependencies
- [ ] Set up Tailwind configuration
- [ ] Create CSS build process (rake task)
- [ ] Set up JavaScript build (esbuild)
- [ ] Update engine.rb for Propshaft
- [ ] Configure ActiveAdmin initializer
- [ ] Update Propshaft manifest
- [ ] Test with both Turbo and non-Turbo apps
- [ ] Update CI/CD for asset building
- [ ] Document upgrade path for gem users
### 10. User Migration Guide
Provide clear instructions for gem users:
```markdown
## Upgrading to v2.0 (ActiveAdmin 4 Support)
### Installation
1. Update your Gemfile:
```ruby
gem 'activeadmin', '~> 4.0.0.beta'
gem 'your_gem', '~> 2.0'
```
2. Install npm package:
```bash
npm install your-required-package
```
3. Update your Tailwind config to include gem styles:
```javascript
// In your tailwind.config.js
module.exports = {
content: [
// ... your existing content
'./vendor/bundle/ruby/*/gems/your_gem-*/app/**/*.rb',
]
}
```
4. Import required styles in your CSS:
```css
/* In app/assets/stylesheets/active_admin.css */
@import "your-package/dist/styles.css";
```
5. Build your assets:
```bash
rails assets:precompile
```
```
## References
- [ActiveAdmin 4.0 Beta Documentation](https://github.com/activeadmin/activeadmin/tree/master/docs)
- [Propshaft Documentation](https://github.com/rails/propshaft)
- [Tailwind CSS Rails Integration](https://tailwindcss.com/docs/guides/rails)
- [Working Example Gist](https://gist.github.com/amkisko/c704c1a6462d573dfa4820ae07d807a6)

Просмотреть файл

@@ -1,473 +0,0 @@
# ActiveAdmin Quill Editor - Rails 8 & Propshaft Migration Guide
## Executive Summary
This document outlines the necessary changes to modernize the `activeadmin_quill_editor` gem for compatibility with:
- **Rails 8.x** with Propshaft asset pipeline
- **ActiveAdmin 4.x**
- **Ruby 3.3+**
- Modern JavaScript without jQuery dependencies
**Note**: This gem already has a full test application at `spec/dummy/` and comprehensive system tests. We'll update these existing resources rather than creating new ones from scratch.
## Key Changes Overview
### 1. Asset Pipeline Migration (Propshaft)
Propshaft automatically serves assets from `vendor/assets` and `app/assets` directories in gems. The key changes:
1. **Remove Sprockets directives** - No more `//= require` statements
2. **Place precompiled assets in vendor/assets** - Propshaft serves them directly
3. **Use ES6 modules** for JavaScript initialization
4. **No asset compilation** - Serve Quill.js directly as minified files
### 2. File Structure Changes
```
activeadmin_quill_editor/
├── vendor/assets/ # Static assets served by Propshaft
│ ├── javascripts/
│ │ └── quill.min.js # Quill 2.x minified (no jQuery)
│ └── stylesheets/
│ ├── quill.snow.css # Theme CSS
│ └── quill.bubble.css # Alternative theme
├── app/assets/ # Gem-specific code
│ ├── javascripts/
│ │ └── activeadmin_quill_editor.js # ES6 initializer
│ └── stylesheets/
│ └── activeadmin_quill_editor.css # Custom styles
└── lib/
├── activeadmin/
│ └── quill_editor/
│ └── engine.rb # Rails engine configuration
└── formtastic/
└── inputs/
└── quill_editor_input.rb # Form input class
```
## Detailed Implementation
### 3. JavaScript Modernization
Replace jQuery-dependent code with vanilla JavaScript:
```javascript
// app/assets/javascripts/activeadmin_quill_editor.js
(function() {
'use strict';
const defaultToolbar = [
['bold', 'italic', 'underline'],
['link', 'blockquote', 'code-block'],
[{ 'script': 'sub' }, { 'script': 'super' }],
[{ 'align': [] }, { list: 'ordered' }, { list: 'bullet' }],
[{ 'color': [] }, { 'background': [] }],
['image'],
['clean']
];
function initQuillEditor(container) {
if (!container || container.classList.contains('quill-editor--active')) {
return;
}
const content = container.querySelector('[data-aa-quill-content]');
if (!content) return;
// Parse options from data attributes
const options = JSON.parse(container.dataset.options || '{}');
const theme = options.theme || 'snow';
const modules = options.modules || { toolbar: defaultToolbar };
// Initialize Quill
const editor = new Quill(content, {
theme: theme,
modules: modules
});
// Store reference and mark as active
container._quillEditor = editor;
container.classList.add('quill-editor--active');
// Handle form submission
const form = container.closest('form.formtastic');
if (form && !form._quillSubmitHandler) {
form._quillSubmitHandler = true;
form.addEventListener('submit', function(e) {
updateQuillInputs(form);
});
}
}
function updateQuillInputs(form) {
form.querySelectorAll('[data-aa-quill-editor]').forEach(container => {
const editor = container._quillEditor;
const input = container.querySelector('input[type="hidden"]');
if (editor && input) {
input.value = editor.root.innerHTML;
}
});
}
function initAllEditors() {
document.querySelectorAll('[data-aa-quill-editor]').forEach(initQuillEditor);
}
// Initialize on various events
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initAllEditors);
} else {
initAllEditors();
}
// Support for Turbo/Turbolinks
document.addEventListener('turbo:load', initAllEditors);
document.addEventListener('turbolinks:load', initAllEditors);
// Support for ActiveAdmin has_many fields
document.addEventListener('has_many_add:after', function(e) {
e.detail?.container?.querySelectorAll('[data-aa-quill-editor]').forEach(initQuillEditor);
});
// Public API
window.QuillEditorHelpers = {
initEditor: initQuillEditor,
initAll: initAllEditors,
getEditor: (elementOrId) => {
const element = typeof elementOrId === 'string'
? document.getElementById(elementOrId)
: elementOrId;
return element?._quillEditor;
}
};
})();
```
### 4. Updated Formtastic Input Class
```ruby
# lib/formtastic/inputs/quill_editor_input.rb
module Formtastic
module Inputs
class QuillEditorInput < Formtastic::Inputs::TextInput
def to_html
input_wrapping do
label_html <<
template.content_tag(:div, input_html_options) do
builder.hidden_field(input_name) <<
template.content_tag(:div, 'data-aa-quill-content': '1') do
object.send(method).try(:html_safe)
end
end
end
end
def input_html_options
super.tap do |options|
options['data-aa-quill-editor'] = '1'
# Merge any custom options
if options[:data] && options[:data][:options]
options['data-options'] = options[:data][:options].to_json
end
end
end
end
end
end
```
### 5. Engine Configuration for Propshaft
```ruby
# lib/activeadmin/quill_editor/engine.rb
require 'active_admin'
module ActiveAdmin
module QuillEditor
class Engine < ::Rails::Engine
engine_name 'activeadmin_quill_editor'
# Propshaft automatically includes these paths
# vendor/assets and app/assets are included by default
initializer 'activeadmin_quill_editor.assets' do |app|
# Ensure our assets are in the precompile list
if defined?(Propshaft)
app.config.assets.precompile += %w[
activeadmin_quill_editor.js
activeadmin_quill_editor.css
quill.min.js
quill.snow.css
quill.bubble.css
]
end
end
end
end
end
```
## Test Application Setup (Using Existing spec/dummy)
### 6. Update Existing Test App
The gem already has a full Rails test application at `spec/dummy/`. We need to update it for Rails 8 and Propshaft:
```ruby
# spec/dummy/config/application.rb
require_relative 'boot'
require 'rails/all'
Bundler.require(*Rails.groups)
module Dummy
class Application < Rails::Application
config.load_defaults Rails::VERSION::STRING.to_f
# Add Propshaft configuration for Rails 8
if Rails.version.to_f >= 8.0
# Propshaft is default in Rails 8
config.assets.paths << Rails.root.join("../../vendor/assets/javascripts")
config.assets.paths << Rails.root.join("../../vendor/assets/stylesheets")
else
# For Rails 7.x, explicitly use Propshaft
config.assets = Propshaft::Railtie.config.assets
end
end
end
```
### 7. Update Test App Asset Configuration
```ruby
# spec/dummy/config/initializers/assets.rb
# Add Quill editor assets to precompile list
Rails.application.config.assets.precompile += %w[
quill.min.js
quill.snow.css
quill.bubble.css
activeadmin_quill_editor.js
activeadmin_quill_editor.css
]
```
```javascript
// spec/dummy/app/assets/javascripts/active_admin.js
// For test app, import the gem's assets
//= require activeadmin_quill_editor
```
## CI/CD Configuration
### 8. GitHub Actions Workflow
```yaml
# .github/workflows/tests.yml
name: Tests
on:
push:
branches: [main, master]
pull_request:
branches: [main, master]
jobs:
test:
runs-on: ubuntu-latest
timeout-minutes: 15
strategy:
fail-fast: false
matrix:
ruby: ['3.3', '3.4']
gemfile:
- rails_7.x_active_admin_4.x
- rails_8.x_active_admin_4.x
env:
BUNDLE_GEMFILE: ${{ github.workspace }}/gemfiles/${{ matrix.gemfile }}.gemfile
RAILS_ENV: test
steps:
- uses: actions/checkout@v4
- name: Set up Ruby
uses: ruby/setup-ruby@v1
with:
ruby-version: ${{ matrix.ruby }}
bundler-cache: true
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
cache-dependency-path: spec/dummy/package-lock.json
- name: Install npm dependencies
working-directory: spec/dummy
run: npm ci
- name: Build assets
working-directory: spec/dummy
run: npm run build
- name: Setup test database
run: bundle exec rake db:setup
- name: Run tests
run: bundle exec rspec
- name: Upload coverage
uses: codecov/codecov-action@v3
with:
file: ./coverage/coverage.json
```
### 9. Appraisals Configuration
```ruby
# Appraisals
appraise 'rails-7.x-active-admin-4.x' do
gem 'rails', '~> 7.0'
gem 'activeadmin', '~> 4.0.0.beta'
gem 'sqlite3', '~> 2.0'
gem 'propshaft', '~> 1.0'
end
appraise 'rails-8.x-active-admin-4.x' do
gem 'rails', '~> 8.0'
gem 'activeadmin', '~> 4.0.0.beta'
gem 'sqlite3', '~> 2.0'
# Propshaft is default in Rails 8
end
```
## Migration Steps
### 10. Step-by-Step Migration Process
1. **Update gemspec dependencies**
```ruby
spec.required_ruby_version = '>= 3.3'
spec.add_dependency 'activeadmin', '~> 4.0.0.beta'
spec.add_dependency 'rails', '>= 7.0'
```
2. **Download and place Quill assets**
```bash
# Download Quill 2.x from CDN or npm
curl -o vendor/assets/javascripts/quill.min.js \
https://cdn.jsdelivr.net/npm/quill@2/dist/quill.min.js
curl -o vendor/assets/stylesheets/quill.snow.css \
https://cdn.jsdelivr.net/npm/quill@2/dist/quill.snow.css
```
3. **Update JavaScript initialization**
- Remove jQuery dependencies
- Implement vanilla JS initialization
- Add Turbo/Turbolinks support
4. **Update test suite**
- Migrate to Combustion
- Add modern browser tests
- Configure CI matrix testing
5. **Update documentation**
- Installation instructions for Propshaft
- Usage examples without jQuery
- Migration guide from old versions
## Usage in Rails 8 Application
### Installation
```ruby
# Gemfile
gem 'activeadmin_quill_editor', '~> 2.0'
```
```scss
// app/assets/stylesheets/active_admin.scss
@import 'quill.snow';
@import 'activeadmin_quill_editor';
```
```javascript
// app/javascript/active_admin.js (or equivalent)
import 'activeadmin_quill_editor';
```
### Form Usage
```ruby
form do |f|
f.inputs do
f.input :title
f.input :content, as: :quill_editor, input_html: {
data: {
options: {
theme: 'snow',
modules: {
toolbar: [
['bold', 'italic'],
['link', 'image']
]
}
}
}
}
end
f.actions
end
```
## Benefits of This Approach
1. **No NPM package needed** - Assets served directly from vendor directory
2. **Propshaft compatible** - Works with Rails 8 default asset pipeline
3. **No jQuery dependency** - Modern vanilla JavaScript
4. **Smaller bundle size** - Only ~200KB for Quill vs 450KB+ for alternatives
5. **Simple integration** - Drop-in replacement for text areas
6. **Maintained compatibility** - Works with Rails 7.x and 8.x
## Testing Locally
```bash
# Clone and setup
git clone https://github.com/yourusername/activeadmin_quill_editor.git
cd activeadmin_quill_editor
bundle install
# Run tests for specific Rails version
RAILS_VERSION=8.0 bundle exec rspec
# Or use appraisals
bundle exec appraisal rails-8.x-active-admin-4.x rspec
# Start test app server
cd spec/dummy
bundle install
bundle exec rails server
```
## Existing Test Coverage
The gem already includes comprehensive system tests at `spec/system/`:
- `quill_editor_spec.rb` - Editor functionality tests (formatting, links, etc.)
- `quill_js_spec.rb` - JavaScript API tests
Additional test cases from activeadmin_trumbowyg to consider adding:
- CSS loading verification tests
- Dark mode support tests
- Multiple editors on same page
- Has-many nested forms
- Turbo/Turbolinks compatibility tests
## Notes
- Quill.js file size: ~200KB minified (vs SunEditor's 450KB)
- No compilation step needed with Propshaft
- Assets are fingerprinted automatically by Propshaft
- Compatible with both importmap-rails and jsbundling-rails setups

125
docs/activeadmin-tailwind-4.md Обычный файл
Просмотреть файл

@@ -0,0 +1,125 @@
# ActiveAdmin + Tailwind CSS v4 Guide
This guide consolidates the ActiveAdmin 4.0.0.beta19 upgrade notes with a working Tailwind v4 build setup. Use it as a template when updating other ActiveAdmin extension gems.
## What Changed in ActiveAdmin 4.0.0.beta19 (from UPGRADING.md)
### Template Updates
- `_site_header.html.erb` container class changed from `sticky` to `fixed`.
- `active_admin.html.erb` now includes the `pt-16` utility class.
### Tailwind v4 Updates
Replace the old Tailwind directives with the new v4 import and config:
```diff
-@tailwind base;
-@tailwind components;
-@tailwind utilities;
+@import "tailwindcss";
+
+@config "../../../tailwind-active_admin.config.mjs";
```
Update your CSS build command:
```diff
-"build:css": "tailwindcss -i ./app/assets/stylesheets/active_admin.css -o ./app/assets/builds/active_admin.css --minify -c tailwind-active_admin.config.js"
+"build:css": "npx @tailwindcss/cli -i ./app/assets/stylesheets/active_admin.css -o ./app/assets/builds/active_admin.css --minify"
```
If you use `tailwindcss-rails`, prefer the bundled `bin/tailwindcss` and the `@config` directive instead of passing `-c`.
### ESM Config Warning
Tailwind config now uses ESM. To avoid the warning:
- Rename `tailwind-active_admin.config.js` to `tailwind-active_admin.config.mjs`, or
- Add `"type": "module"` to `package.json`.
### Breaking Changes Summary
- jQuery and jQuery UI removed.
- `columns` component removed (use Tailwind grid).
- `tabs` component removed.
- Replace `default_main_content` with `render "show_default"`.
- Replace `as: :datepicker` with `as: :date_picker`.
- Replace `active_admin_comments` with `active_admin_comments_for(resource)`.
- Replace `attributes_table` with `attributes_table_for(resource)` in sidebars.
- Removed `IndexAsBlog`, `IndexAsBlock`, `IndexAsGrid`.
- Batch action form DSL replaced with partial support.
- Deeply nested submenus removed (only one level supported).
- Removed `Panel#header_action` and `index_column`.
## Recommended Build Setup (tailwindcss-rails)
### 1. Gemfile
```ruby
gem "activeadmin", "4.0.0.beta19"
gem "tailwindcss-rails", "~> 4.4.0"
```
### 2. Tailwind Input
```css
/* app/assets/stylesheets/active_admin.tailwind.css */
@import "tailwindcss";
@config "../../../tailwind-active_admin.config.mjs";
```
### 3. Tailwind Config
```javascript
// tailwind-active_admin.config.mjs
import { execSync } from "child_process";
import activeAdminPlugin from "@activeadmin/activeadmin/plugin";
const activeAdminPath = execSync("bundle show activeadmin", {
encoding: "utf-8"
}).trim();
export default {
content: [
`${activeAdminPath}/vendor/javascript/flowbite.js`,
`${activeAdminPath}/plugin.js`,
`${activeAdminPath}/app/views/**/*.{arb,erb,html,rb}`,
"./app/admin/**/*.{arb,erb,html,rb}",
"./app/views/active_admin/**/*.{arb,erb,html,rb}",
"./app/views/admin/**/*.{arb,erb,html,rb}",
"./app/views/layouts/active_admin*.{erb,html}",
"./app/javascript/**/*.js"
],
darkMode: "selector",
plugins: [activeAdminPlugin]
};
```
### 4. Build Tasks
```ruby
# lib/tasks/active_admin.rake
namespace :active_admin do
desc "Build Active Admin Tailwind stylesheets"
task build: :environment do
command = [
Rails.root.join("bin/tailwindcss").to_s,
"-i", Rails.root.join("app/assets/stylesheets/active_admin.tailwind.css").to_s,
"-o", Rails.root.join("app/assets/builds/active_admin.css").to_s,
"-m"
]
system(*command, exception: true)
end
end
```
### 5. Tailwind CLI Binstub
```bash
bundle binstubs tailwindcss-ruby --force
```
## Notes for Extension Gems
When updating other ActiveAdmin extension gems:
- Keep all JS/CSS inside the gem or npm package; do not copy large files into host apps.
- Add only a thin import to the host app (`import "your_gem"`).
- Use Tailwind v4 `@import` + `@config` and ESM config files.
- Avoid jQuery-based plugins or require them explicitly.

202
docs/guide-update-your-app.md Обычный файл
Просмотреть файл

@@ -0,0 +1,202 @@
# Migration Guide: ActiveAdmin Tom Select (Tailwind v4)
This guide helps you migrate from `activeadmin-searchable_select` to `activeadmin-tom_select` on ActiveAdmin 4.0.0.beta20 with Tailwind CSS v4.
## Quick Start (New Installation)
```bash
# Gem
bundle add activeadmin-tom_select
# NPM
npm install activeadmin-tom_select tom-select
```
## Why Update?
- Tom Select replaces Select2 (no jQuery)
- ActiveAdmin 4.0.0.beta20 compatible (requires Rails 7.2+)
- Tailwind CSS v4 styles included
- Auto-init helpers for searchable selects
- Ruby 3.2+ and 4.0 compatible
## 1. Update Gemfile
```ruby
# Remove legacy gem(s)
# gem "activeadmin-searchable_select"
# gem "rs-activeadmin-searchable_select"
gem "activeadmin-tom_select", "~> 4.1.0"
```
## 2. Update JavaScript Dependencies
```bash
npm uninstall @codevise/activeadmin-searchable_select activeadmin-searchable_select jquery select2
npm install activeadmin-tom_select tom-select
```
## 3. JavaScript Imports
```javascript
import "@activeadmin/activeadmin";
import TomSelect from "tom-select";
window.TomSelect = TomSelect;
import { setupAutoInit } from "activeadmin-tom_select";
setupAutoInit();
```
## 4. Tailwind CSS Build (ActiveAdmin 4.0.0.beta20)
### 4.1 Tailwind Input
```css
/* app/assets/stylesheets/active_admin.tailwind.css */
@import "tailwindcss";
@config "../../../tailwind-active_admin.config.mjs";
@import "activeadmin-tom_select/css";
```
### 4.2 Tailwind Config (ESM)
```javascript
// tailwind-active_admin.config.mjs
import { execSync } from "child_process";
import activeAdminPlugin from "@activeadmin/activeadmin/plugin";
const activeAdminPath = execSync("bundle show activeadmin", {
encoding: "utf-8"
}).trim();
export default {
content: [
`${activeAdminPath}/vendor/javascript/flowbite.js`,
`${activeAdminPath}/plugin.js`,
`${activeAdminPath}/app/views/**/*.{arb,erb,html,rb}`,
"./app/admin/**/*.{arb,erb,html,rb}",
"./app/views/active_admin/**/*.{arb,erb,html,rb}",
"./app/views/admin/**/*.{arb,erb,html,rb}",
"./app/views/layouts/active_admin*.{erb,html}",
"./app/javascript/**/*.js"
],
darkMode: "selector",
plugins: [activeAdminPlugin]
};
```
### 4.3 Tailwind Build Tasks
```ruby
# lib/tasks/active_admin.rake
namespace :active_admin do
desc "Build Active Admin Tailwind stylesheets"
task build: :environment do
command = [
Rails.root.join("bin/tailwindcss").to_s,
"-i", Rails.root.join("app/assets/stylesheets/active_admin.tailwind.css").to_s,
"-o", Rails.root.join("app/assets/builds/active_admin.css").to_s,
"-m"
]
system(*command, exception: true)
end
desc "Watch Active Admin Tailwind stylesheets"
task watch: :environment do
command = [
Rails.root.join("bin/tailwindcss").to_s,
"--watch",
"-i", Rails.root.join("app/assets/stylesheets/active_admin.tailwind.css").to_s,
"-o", Rails.root.join("app/assets/builds/active_admin.css").to_s,
"-m"
]
system(*command, exception: true)
end
end
Rake::Task["assets:precompile"].enhance(["active_admin:build"])
Rake::Task["spec:prepare"].enhance(["active_admin:build"]) if Rake::Task.task_defined?("spec:prepare")
Rake::Task["db:test:prepare"].enhance(["active_admin:build"]) if Rake::Task.task_defined?("db:test:prepare")
```
### 4.4 package.json scripts
```json
{
"scripts": {
"build:js": "esbuild app/javascript/*.* --bundle --sourcemap --format=esm --outdir=app/assets/builds --public-path=/assets",
"build:css": "bundle exec rake active_admin:build",
"build": "npm run build:js && npm run build:css",
"watch:css": "bundle exec rake active_admin:watch"
}
}
```
### 4.5 Tailwind CLI binstub
```bash
bundle binstubs tailwindcss-ruby --force
```
## 5. Importmap (Optional)
```ruby
# config/importmap.rb
pin "tom-select", to: "https://ga.jspm.io/npm:tom-select@2.4.3/dist/js/tom-select.complete.min.js"
pin "activeadmin-tom_select", to: "activeadmin-tom_select.js"
```
## 6. ActiveAdmin Usage
```ruby
ActiveAdmin.register Product do
form do |f|
f.inputs do
f.input :category, as: :searchable_select
f.input :tags, as: :searchable_select, ajax: true, multiple: true
end
f.actions
end
filter :category, as: :searchable_select
filter :tags, as: :searchable_select, ajax: true, multiple: true
end
```
## Troubleshooting
### Styles missing
- Confirm `app/assets/builds/active_admin.css` exists.
- Verify `active_admin.tailwind.css` imports `activeadmin-tom_select/css`.
### Tom Select not initializing
- Ensure `window.TomSelect` is set.
- Ensure `setupAutoInit()` runs.
## ActiveAdmin 4.0.0.beta20 Notes (from upgrade guide)
**Version Requirements:**
- Rails 7.2+ (Rails 7.0 and 7.1 are no longer supported)
- Ruby 3.2+ (Ruby 3.0 and 3.1 are no longer supported)
**Breaking Changes from earlier v4 betas:**
- `_site_header.html.erb` container class changed from `sticky` to `fixed`.
- `active_admin.html.erb` adds the `pt-16` utility class.
- Tailwind v4 requires `@import "tailwindcss"` + `@config`.
- jQuery and jQuery UI removed; `columns` and `tabs` components removed.
- Replace `default_main_content` with `render "show_default"`.
- Replace `as: :datepicker` with `as: :date_picker`.
- Replace `active_admin_comments` with `active_admin_comments_for(resource)`.
- Replace `attributes_table` with `attributes_table_for(resource)` in sidebars.
**New in beta20:**
- Parent menu item linking support
- Improved comments pagination styling
- Better vertical spacing for has-many forms
- Pointer cursor restored on eligible buttons
- Various accessibility improvements

Просмотреть файл

@@ -1,320 +0,0 @@
# Propshaft: A Modern Asset Pipeline for Rails
Propshaft is an asset pipeline library for Rails. It's built for an era where bundling assets to save on HTTP connections is no longer urgent, where JavaScript and CSS are either compiled by dedicated Node.js bundlers or served directly to the browsers, and where increases in bandwidth have made the need for minification less pressing. These factors allow for a dramatically simpler and faster asset pipeline compared to previous options, like [Sprockets](https://github.com/rails/sprockets-rails).
## Table of Contents
1. [Overview](#overview)
2. [Architecture](#architecture)
3. [Asset Serving in Development/Test Mode](#asset-serving-in-developmenttest-mode)
4. [Configuration and Asset Paths](#configuration-and-asset-paths)
5. [Test Environment Specifics](#test-environment-specifics)
6. [JavaScript and CSS Bundling Integration](#javascript-and-css-bundling-integration)
7. [Common Patterns and Best Practices](#common-patterns-and-best-practices)
## Overview
So that's what Propshaft doesn't do. Here's what it does provide:
1. **Configurable load path**: You can register directories from multiple places in your app and gems, and reference assets from all of these paths as though they were one.
1. **Digest stamping**: All assets in the load path will be copied (or compiled) in a precompilation step for production that also stamps all of them with a digest hash, so you can use long-expiry cache headers for better performance. The digested assets can be referred to through their logical path because the processing leaves a manifest file that provides a way to translate.
1. **Development server**: There's no need to precompile the assets in development. You can refer to them via the same asset_path helpers and they'll be served by a development server.
1. **Basic compilers**: Propshaft was explicitly not designed to provide full transpiler capabilities. You can get that better elsewhere. But it does offer a simple input->output compiler setup that by default is used to translate `url(asset)` function calls in CSS to `url(digested-asset)` instead and source mapping comments likewise.
## Architecture
### Core Components
```
Propshaft::Assembly
├── LoadPath # Asset discovery and caching
├── Resolver # Path resolution (Dynamic/Static)
│ ├── Dynamic # Development/test mode
│ └── Static # Production with manifest
├── Server # Rack middleware for asset serving
├── Processor # Precompilation and digesting
├── Compilers # Asset transformation
└── Manifest # Asset mapping and integrity hashes
```
### Key Classes
#### `Propshaft::Assembly`
Central coordinator that manages all components. Created during Rails initialization and accessible via `Rails.application.assets`.
```ruby
# Core assembly configuration
Rails.application.configure do
app.assets = Propshaft::Assembly.new(app.config.assets)
end
```
#### `Propshaft::LoadPath`
Manages asset discovery across multiple directories. Automatically includes:
- `app/assets/**/*` (application assets)
- `lib/assets/**/*` (library assets)
- `vendor/assets/**/*` (third-party assets)
- Engine assets from all loaded gems
#### `Propshaft::Resolver::Dynamic`
Used in development and test environments. Resolves assets on-demand without requiring precompilation.
#### `Propshaft::Resolver::Static`
Used in production. Relies on `.manifest.json` for fast asset resolution.
## Asset Serving in Development/Test Mode
### Dynamic Resolution Process
1. **Request Interception**: `Propshaft::Server` middleware catches requests to `/assets/*`
2. **Asset Discovery**: `LoadPath#find` searches configured paths for matching assets
3. **Compilation**: Assets pass through registered compilers
4. **Cache Headers**: Aggressive caching with ETags and immutable cache-control
5. **Response**: Compiled content served with appropriate MIME type
```ruby
# Server middleware in action (simplified)
def call(env)
if path.start_with?(@assembly.prefix) && (asset = @assembly.load_path.find(path))
[200, {
'Content-Type' => asset.content_type,
'ETag' => "\"#{asset.digest}\"",
'Cache-Control' => 'public, max-age=31536000, immutable'
}, [asset.compiled_content]]
end
end
```
### Cache Sweeping
In development/test, Propshaft monitors file changes:
```ruby
config.assets.sweep_cache = Rails.env.development?
```
When enabled, before each request:
1. File watcher checks for modifications
2. Asset cache cleared if changes detected
3. New assets discovered and cached
## Configuration and Asset Paths
### Default Configuration (from Railtie)
```ruby
config.assets.paths = [] # Auto-populated
config.assets.excluded_paths = [] # Paths to exclude
config.assets.version = "1" # Cache invalidation
config.assets.prefix = "/assets" # URL prefix
config.assets.server = Rails.env.development? || Rails.env.test?
config.assets.sweep_cache = Rails.env.development?
```
### Path Resolution Order
1. **Application paths**: `app/assets/**/*`
2. **Library paths**: `lib/assets/**/*`
3. **Vendor paths**: `vendor/assets/**/*`
4. **Engine paths**: From all loaded Rails engines/gems
Paths are automatically prioritized:
- Application assets take precedence over engine assets
- Later additions to load path have lower priority
## Installation
With Rails 8, Propshaft is the default asset pipeline for new applications. With Rails 7, you can start a new application with propshaft using `rails new myapp -a propshaft`. For existing applications, check the [upgrade guide](https://github.com/rails/propshaft/blob/main/UPGRADING.md) which contains step-by-step instructions.
## Usage
Propshaft makes all the assets from all the paths it's been configured with through `config.assets.paths` available for serving and will copy all of them into `public/assets` when precompiling. This is unlike Sprockets, which did not copy over assets that hadn't been explicitly included in one of the bundled assets.
You can however exempt directories that have been added through the `config.assets.excluded_paths`. This is useful if you're for example using `app/assets/stylesheets` exclusively as a set of inputs to a compiler like Dart Sass for Rails, and you don't want these input files to be part of the load path. (Remember you need to add full paths, like `Rails.root.join("app/assets/stylesheets")`).
These assets can be referenced through their logical path using the normal helpers like `asset_path`, `image_tag`, `javascript_include_tag`, and all the other asset helper tags. These logical references are automatically converted into digest-aware paths in production when `assets:precompile` has been run (through a JSON mapping file found in `public/assets/.manifest.json`).
## Referencing digested assets in CSS and JavaScript
Propshaft will automatically convert asset references in CSS to use the digested file names. So `background: url("/bg/pattern.svg")` is converted to `background: url("/assets/bg/pattern-2169cbef.svg")` before the stylesheet is served.
For JavaScript, you'll have to manually trigger this transformation by using the `RAILS_ASSET_URL` pseudo-method. It's used like this:
```javascript
export default class extends Controller {
init() {
this.img = RAILS_ASSET_URL("/icons/trash.svg")
}
}
```
That'll turn into:
```javascript
export default class extends Controller {
init() {
this.img = "/assets/icons/trash-54g9cbef.svg"
}
}
```
## Bypassing the digest step
If you need to put multiple files that refer to each other through Propshaft, like a JavaScript file and its source map, you have to digest these files in advance to retain stable file names. Propshaft looks for the specific pattern of `-[digest].digested.js` as the postfix to any asset file as an indication that the file has already been digested.
## Subresource Integrity (SRI)
Propshaft supports Subresource Integrity (SRI) to help protect against malicious modifications of assets. SRI allows browsers to verify that resources fetched from CDNs or other sources haven't been tampered with by checking cryptographic hashes.
### Enabling SRI
To enable SRI support, configure the hash algorithm in your Rails application:
```ruby
config.assets.integrity_hash_algorithm = "sha384"
```
Valid hash algorithms include:
- `"sha256"` - SHA-256 (most common)
- `"sha384"` - SHA-384 (recommended for enhanced security)
- `"sha512"` - SHA-512 (strongest)
### Using SRI in your views
Once configured, you can enable SRI by passing the `integrity: true` option to asset helpers:
```erb
<%= stylesheet_link_tag "application", integrity: true %>
<%= javascript_include_tag "application", integrity: true %>
```
This generates HTML with integrity hashes:
```html
<link rel="stylesheet" href="/assets/application-abc123.css"
integrity="sha384-xyz789...">
<script src="/assets/application-def456.js"
integrity="sha384-uvw012..."></script>
```
**Important**: SRI only works in secure contexts (HTTPS) or during local development. The integrity hashes are automatically omitted when serving over HTTP in production for security reasons.
### Bulk stylesheet inclusion with SRI
Propshaft extends `stylesheet_link_tag` with special symbols for bulk inclusion:
```erb
<%= stylesheet_link_tag :all, integrity: true %> <!-- All stylesheets -->
<%= stylesheet_link_tag :app, integrity: true %> <!-- Only app/assets stylesheets -->
```
## Improving performance in development
Before every request Propshaft checks if any asset was updated to decide if a cache sweep is needed. This verification is done using the application's configured file watcher which, by default, is `ActiveSupport::FileUpdateChecker`.
If you have a lot of assets in your project, you can improve performance by adding the `listen` gem to the development group in your Gemfile, and this line to the `development.rb` environment file:
```ruby
config.file_watcher = ActiveSupport::EventedFileUpdateChecker
```
## Migrating from Sprockets
Propshaft does a lot less than Sprockets, by design, so it might well be a fair bit of work to migrate if it's even desirable. This is particularly true if you rely on Sprockets to provide any form of transpiling, like CoffeeScript or Sass, or if you rely on any gems that do. You'll need to either stop transpiling or use a Node-based transpiler, like those in [`jsbundling-rails`](https://github.com/rails/jsbundling-rails) and [`cssbundling-rails`](https://github.com/rails/cssbundling-rails).
On the other hand, if you're already bundling JavaScript and CSS through a Node-based setup, then Propshaft is going to slot in easily. Since you don't need another tool to bundle or transpile. Just to digest and serve.
But for greenfield apps using the default import-map approach, Propshaft can also work well, if you're able to deal with vanilla CSS.
## License
Propshaft is released under the [MIT License](https://opensource.org/licenses/MIT).
## Compilation and Digesting
### Asset Processing Pipeline
1. **Discovery**: `LoadPath` finds all assets matching patterns
2. **Compilation**: Each asset processed through registered compilers
3. **Digesting**: Content hash generated using SHA1 + version string
4. **Output**: Files written to `config.assets.output_path` (default: `public/assets/`)
### Built-in Compilers
#### CSS Asset URL Compiler
Transforms relative URLs to digested versions:
```css
/* Input */
background: url('./hero.jpg');
/* Output */
background: url('/assets/hero-abc123.jpg');
```
#### JavaScript Asset URL Compiler
Processes `RAILS_ASSET_URL()` pseudo-functions:
```javascript
// Input
const icon = RAILS_ASSET_URL('./icon.svg');
// Output
const icon = '/assets/icon-def456.svg';
```
#### Source Map Compiler
Updates source map references to match digested filenames.
### Manifest Generation
The manifest file (`.manifest.json`) maps logical paths to digested paths:
```json
{
"application.js": {
"digested_path": "application-abc123.js",
"integrity": "sha384-xyz789..."
}
}
```
## Asset Organization
```
app/assets/
├── builds/ # jsbundling-rails/cssbundling-rails output
│ ├── application.js
│ └── application.css
├── images/ # Static assets
│ └── logo.svg
├── stylesheets/ # SCSS source (often excluded)
│ └── application.scss
└── javascripts/ # JS source (often excluded)
└── application.js
```
## Error Handling
### Missing Asset Handling
```ruby
# Propshaft raises MissingAssetError for missing assets
begin
asset_path('nonexistent.js')
rescue Propshaft::MissingAssetError => e
Rails.logger.error "Missing asset: #{e.message}"
# Fallback logic
end
```
### Development Debugging
```ruby
# Show all available assets
rake assets:reveal
# Show asset full paths
rake assets:reveal:full
```

Просмотреть файл

@@ -1,484 +0,0 @@
# Upgrading from Sprockets to Propshaft
Propshaft has a smaller scope than Sprockets, therefore migrating to it will also require you to adopt the [jsbundling-rails](https://github.com/rails/jsbundling-rails) and [cssbundling-rails](https://github.com/rails/cssbundling-rails) gems. This guide will assume your project follows Rails 6.1 conventions of using [webpacker](https://github.com/rails/webpacker) to bundle javascript, [sass-rails](https://github.com/rails/sass-rails) to bundle css and [sprockets](https://github.com/rails/sprockets) to digest assets. Finally, you will also need [npx](https://docs.npmjs.com/cli/v7/commands/npx) version 7.1.0 or later installed.
Propshaft depends on Rails 7, so you will need to upgrade to Rails 7+ before starting the migration.
## 1. Migrate from Webpacker to jsbundling-rails
Start by following these steps:
1. Replace `webpacker` with `jsbundling-rails` in your Gemfile;
2. Run `./bin/bundle install`;
3. Run `./bin/rails javascript:install:webpack`;
4. Remove the file `config/initializers/assets.rb`;
5. Remove the file `bin/webpack`;
6. Remove the file `bin/webpack-dev-server`;
7. Remove the folder `config/webpack` (note: any custom configuration should be migrated to the new `webpack.config.js` file);
8. Remove the file `config/webpacker.yml`;
9. Replace all instances of `javascript_pack_tag` with `javascript_include_tag` and add `defer: true` to them.
After you are done you will notice that the install step added various files to your project and updated some of the existing ones.
**The new 'bin/dev' and 'Procfile.dev' files**
The `./bin/dev` file is a shell script that uses [foreman](https://github.com/ddollar/foreman) and `Procfile.dev` to start two processes in a single terminal: `rails s` and `yarn build`. The latter replaces `webpack-dev-server` for bundling and watching for changes in javascript files.
**The 'build' attribute added to package.json**
This is the command that `yarn build` will use to bundle javascript files.
**The new 'webpack.config.js' file**
In `webpacker` this file was hidden inside the gem, but now you can edit it directly. If you had custom configuration in `config/webpack` you can move them to here. Projects with multiple entrypoints will need to adjust the `entry` attribute:
```js
module.exports = {
entry: {
application: "./app/javascript/application.js",
admin: "./app/javascript/admin.js"
}
}
```
**The 'link_tree' directive added to 'app/assets/manifest.js'**
This tells Sprockets to include the files in `app/assets/builds` during `assets:precompile`. This is the folder where `yarn build` will place the bundled files, so make sure you commit it to the repository and don't delete it when cleaning assets.
**What about babel?**
If you would like to continue using babel for transpiling, you will need to configure it manually. First, open `webpack.config.js` and add this:
```js
module.exports = {
module: {
rules: [
{
test: /\.(js)$/,
exclude: /node_modules/,
use: ['babel-loader']
}
]
}
}
```
Then open `package.json` and add this:
```json
"babel": {
"presets": [
"./webpack.babel.js"
]
}
```
Finally, download [webpackers babel preset](https://github.com/rails/webpacker/blob/master/package/babel/preset.js) file and place it in the same directory as `package.json` with the name `webpack.babel.js`.
**Module resolution**
Webpacker included the `source_path` (default: `app/javascript/`) into module resolution, so a statement like `import 'channels'` imported `app/javascript/channels/`. After migrating to `jsbundling-rails` this is no longer the case. You will need to update your `webpack.config.js` to include the following if you wish to maintain that behavior:
```javascript
module.exports = {
// ...
resolve: {
modules: ["app/javascript", "node_modules"],
},
//...
}
```
Alternatively, you can change modules to use relative imports, for example:
```diff
- import 'channels'
+ import './channels'
```
### Extracting Sass/SCSS from JavaScript
In webpacker it is possible to extract Sass/SCSS from JavaScript by enabling `extract_css` in `webpacker.yml`. This allows for including those source files in JavaScript, e.g. `import '../scss/application.scss`
If you wish to keep this functionality follow these steps:
1. Run `yarn add mini-css-extract-plugin sass sass-loader css-loader`;
2. Update your `webpack.config.js` to require `mini-css-extract-plugin` and configure the loaders (see example below).
Example `webpack.config.js`:
```javascript
const path = require("path")
const webpack = require("webpack")
const MiniCssExtractPlugin = require("mini-css-extract-plugin")
module.exports = {
mode: "production",
devtool: "source-map",
entry: {
application: "./app/javascript/application.js"
},
resolve: {
modules: ["app/javascript", "node_modules"],
},
output: {
filename: "[name].js",
sourceMapFilename: "[file].map",
path: path.resolve(__dirname, "app/assets/builds"),
},
plugins: [
new MiniCssExtractPlugin(),
new webpack.optimize.LimitChunkCountPlugin({
maxChunks: 1
})
],
module: {
rules: [
{
test: /\.s[ac]ss$/i,
use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"],
},
],
},
}
```
## 2. Migrate from sass-rails to cssbundling-rails
Note: if your application used Webpacker's `extract_css` to build your CSS and did not require `sass-rails`, you can skip this section.
Start by following these steps:
1. Add `cssbundling-rails` to your Gemfile;
2. Run `./bin/bundle install`;
3. Run `./bin/rails css:install:sass`.
After you are done you will notice that the install step updated some files.
**The new process in 'Procfile.dev'**
Just like the javascript process, this one will bundle and watch for changes in css files.
**The 'build:css' attribute added to package.json**
This is the command `yarn build` will use to bundle css files.
**The 'link_tree' directive removed from 'app/assets/manifest.js'**
Now that the CSS files will be placed into `app/assets/build`, Sprockets no longer needs to worry about the `app/assets/stylesheets` folder. If you have any other `link_tree` for css files, remove them too.
### Configuring multiple entrypoints
Sprockets will only compile files in the root directories listed in `manifest.js`, but the sass package that `yarn build` uses will also check subfolders, which might cause compilation errors if your scss files are using features like `@import` and variables. This means that if you have multiple entry points in your app, you have some extra work ahead of you.
Let's assume you have the following structure in your `app/asset/stylesheets` folder:
```
stylesheets/admin.scss
stylesheets/admin/source_1.scss
stylesheets/admin/source_2.scss
stylesheets/application.scss
stylesheets/application/source_1.scss
stylesheets/application/source_2.scss
```
Start by your separating your entrypoints from your other files, and adjusting all `@import` for the new structure:
```
stylesheets/entrypoints/admin.scss
stylesheets/entrypoints/application.scss
stylesheets/sources/admin/source_1.scss
stylesheets/sources/admin/source_2.scss
stylesheets/sources/application/source_1.scss
stylesheets/sources/application/source_2.scss
```
Then adjust the `build` attribute in `package.json`:
```
"build:css": "sass ./app/assets/stylesheets/entrypoints:./app/assets/builds --no-source-map --load-path=node_modules"
```
### Deprecation warnings
Sass might raise deprecation warnings depending on what features you are using (such as division), but the messages will explain how to fix them. If you are not sure, see more details in the [official documentation](https://sass-lang.com/documentation/breaking-changes).
## 3. Migrate from Sprockets to Propshaft
Start by following these steps:
1. Remove `sprockets`, `sprockets-rails`, and `sass-rails` from the Gemfile and add `propshaft`;
2. Run `./bin/bundle install`;
3. Check your `Gemfile.lock`, repeat steps 1 and 2 for gems that list `sprockets` or `sprockets-rails` as a dependency;
4. Open `config/application.rb` and remove `config.assets.paths << Rails.root.join('app','assets')`;
5. Remove `app/assets/config/manifest.js`.
6. Replace all asset_helpers (`image_url`, `font_url`) in css files with standard `urls`.
7. If you are importing only the frameworks you need (instead of `rails/all`), remove `require "sprockets/railtie"`;
### Asset paths
Propshaft will automatically include in its search paths the folders `vendor/assets`, `lib/assets` and `app/assets` of your project and of all the gems in your Gemfile. You can see all included files by using the `reveal` rake task:
```
rake assets:reveal
```
### Asset helpers
Propshaft does not rely on asset_helpers (`asset_path`, `asset_url`, `image_url`, etc.) like Sprockets did. Instead, it will search for every `url` function in your css files, and adjust them to include the digest of the assets they reference.
Go through your css files, and make the necessary adjustments:
```diff
- background: image_url('hero.jpg');
+ background: url('/hero.jpg');
```
Notice that Propshaft's version starts with an `/` and Sprockets' version does not? That's because the latter uses **absolute paths**, and the former uses **relative paths**. To better illustrate that difference, let's assume you have the following structure:
```
assets/stylesheets/theme/main.scss
assets/images/hero.jpg
```
In Sprockets, `main.scss` can reference `hero.jpg` like this:
```css
background: image_url('hero.jpg')
```
Using the same path with `url` in Propshaft will cause it to raise an error, saying it cannot locate `theme/hero.jpg`. That's because Propshaft assumes all paths are relative to the path of the file it's processing. Since it was processing a css file inside the `theme` folder, it will also look for `hero.jpg` in the same folder.
By adding a `/` at the start of the path we are telling Propshaft to consider this path as an absolute path. While this change in behavior increases the work a bit when upgrading, it makes **external libraries like FontAwesome and Bootstrap themes work out-of-the-box**.
### Asset content
It's a common pattern in apps to inline small SVG files and low resolution versions of images that need to be displayed as quickly as possible. In Propshaft, the same line of code works for all environments:
```ruby
Rails.application.assets.load_path.find('logo.svg').content
```
As Rails escapes html tags in views by default, in order to output a rendered svg you will need to specify rails not to escape the string using [html_safe](https://api.rubyonrails.org/classes/String.html#method-i-html_safe) or [raw](https://api.rubyonrails.org/classes/ActionView/Helpers/OutputSafetyHelper.html#method-i-raw).
```ruby
Rails.application.assets.load_path.find('logo.svg').content.html_safe
raw Rails.application.assets.load_path.find('logo.svg').content
```
### Precompilation in development
Propshaft uses a dynamic assets resolver in development mode. However, when you run `assets:precompile` locally Propshaft will then switch to a static assets resolver. Therefore, changes to assets will not be observed anymore and you will have to precompile the assets each time changes are made. This is different to Sprockets.
If you wish to have dynamic assets resolver enabled again, you need to clean your target folder (usually `public/assets`) and propshaft will start serving dynamic content from source. One way to do this is to run `rails assets:clobber`.
Another way to watch changes in your CSS & JS assets is by running `bin/dev` command instead of `rails server` that not only runs the server but also keeps looking for any changes in the assets and once it detects any changes, it compiles them while the server is running. This is possible because of the `Procfile.dev`.
## 4. Specific Configuration for Test Environments
### Understanding Propshaft's Test Mode
Propshaft automatically configures itself for test environments with these defaults:
```ruby
# Automatically enabled in test environment
config.assets.server = Rails.env.test? # true for test environment
config.assets.sweep_cache = false # Disabled for faster tests
```
### Test Environment Configuration
```ruby
# config/environments/test.rb
Rails.application.configure do
# Asset server is automatically enabled - no precompilation needed
config.assets.server = true
# Optional: Add test-specific asset paths
config.assets.paths << Rails.root.join('spec/fixtures/assets')
# Optional: Disable SRI for faster test execution
config.assets.integrity_hash_algorithm = nil
# Optional: Customize asset prefix for isolated testing
# config.assets.prefix = '/test-assets'
# Performance: Use faster file watcher (if using listen gem)
config.file_watcher = ActiveSupport::EventedFileUpdateChecker
end
```
### Testing Asset Integration
#### RSpec Configuration
```ruby
# spec/rails_helper.rb
RSpec.configure do |config|
# Ensure assets are available in feature specs
config.before(:suite) do
# Warm up asset cache for faster test execution
Rails.application.assets.load_path.assets
end
# Clean up assets between tests if needed
config.after(:each) do
# Only if you modify asset paths during tests
# Rails.application.assets.load_path.clear_cache
end
end
```
#### Testing Asset Helpers
```ruby
# spec/helpers/application_helper_spec.rb
RSpec.describe ApplicationHelper, type: :helper do
describe "asset helpers" do
it "resolves asset paths correctly" do
expect(helper.asset_path('application.js')).to match(%r{^/assets/application-\w+\.js$})
end
it "includes integrity hashes when configured" do
allow(Rails.application.config.assets).to receive(:integrity_hash_algorithm).and_return('sha384')
result = helper.javascript_include_tag('application', integrity: true)
expect(result).to include('integrity="sha384-')
end
end
end
```
#### Feature Spec Asset Testing
```ruby
# spec/features/assets_spec.rb
RSpec.describe "Asset loading", type: :feature do
it "serves JavaScript assets correctly" do
visit root_path
expect(page).to have_css('script[src*="/assets/application-"]')
end
it "serves CSS assets correctly" do
visit root_path
expect(page).to have_css('link[href*="/assets/application-"][rel="stylesheet"]')
end
end
```
### Common Test Environment Issues and Solutions
#### Issue 1: Assets Not Found in Tests
**Symptom**: `Propshaft::MissingAssetError` in test environment
**Solution**:
```ruby
# Ensure asset server is enabled in test.rb
config.assets.server = true
# Check that build artifacts exist
# For jsbundling-rails/cssbundling-rails:
bundle exec rake assets:precompile # If assets need building
```
#### Issue 2: Slow Test Startup
**Symptom**: Tests take long to start due to asset discovery
**Solution**:
```ruby
# config/environments/test.rb
# Disable sweep_cache (should be default)
config.assets.sweep_cache = false
# Exclude unnecessary paths
config.assets.excluded_paths += [
Rails.root.join("app/assets/stylesheets"), # If using cssbundling
Rails.root.join("app/javascript") # If using jsbundling
]
```
#### Issue 3: Inconsistent Asset Paths Between Environments
**Symptom**: Tests pass but development/production fails with asset references
**Solution**:
```ruby
# Use consistent asset path helpers across environments
# In views, always use:
<%= asset_path('image.png') %> # Good
# Instead of:
"/assets/image.png" # Bad - won't work with digests
```
### Performance Optimization for Tests
#### Precompile Once Strategy
For CI/CD environments where you can precompile once:
```bash
# In CI setup
bundle exec rake assets:precompile
RAILS_ENV=test bundle exec rspec
```
#### Asset Path Caching
```ruby
# config/initializers/assets.rb (test environment)
if Rails.env.test?
# Warm asset cache on initialization to avoid repeated discovery
Rails.application.config.after_initialize do
Rails.application.assets.load_path.assets
end
end
```
### Integration with Test Coverage Tools
#### SimpleCov Configuration
```ruby
# spec/spec_helper.rb
require 'simplecov'
SimpleCov.start 'rails' do
# Exclude built assets from coverage
add_filter 'app/assets/builds/'
add_filter 'vendor/assets/'
end
```
### Docker and Containerized Testing
#### Dockerfile Considerations
```dockerfile
# Dockerfile
FROM ruby:3.2
# Install Node.js for asset building
RUN curl -fsSL https://deb.nodesource.com/setup_18.x | bash -
RUN apt-get install -y nodejs
# Install dependencies
COPY Gemfile Gemfile.lock package.json package-lock.json ./
RUN bundle install && npm install
# Copy source
COPY . .
# Build assets once for all test runs
RUN bundle exec rake assets:precompile
# Run tests
CMD ["bundle", "exec", "rspec"]
```
### Migration Testing Strategy
#### Before/After Asset Comparison
```ruby
# spec/migration/sprockets_to_propshaft_spec.rb
RSpec.describe "Sprockets to Propshaft migration" do
let(:expected_assets) do
%w[application.js application.css logo.png favicon.ico]
end
it "serves all expected assets" do
expected_assets.each do |asset|
expect(Rails.application.assets.resolver.resolve(asset)).to be_present
end
end
it "maintains asset content integrity" do
# Test that specific assets contain expected content
asset = Rails.application.assets.load_path.find('application.js')
expect(asset.content).to include('expected_javascript_content')
end
end
```
This comprehensive guide covers the complete migration from Sprockets to Propshaft with special attention to test environment configuration and common pitfalls.

Разница между файлами не показана из-за своего большого размера Загрузить разницу

141
docs/setup-activeadmin-app.md Обычный файл
Просмотреть файл

@@ -0,0 +1,141 @@
# Setting Up a Standalone ActiveAdmin 4 App (Tailwind v4)
This guide creates a new Rails app with ActiveAdmin 4.0.0.beta20, Tailwind CSS v4, and optional AA extension gems.
## 1. Create Rails App
```bash
rails new my_admin_app --css=tailwind --javascript=esbuild
cd my_admin_app
```
## 2. Gemfile
```ruby
# ActiveAdmin 4 beta
gem "activeadmin", "4.0.0.beta20"
# Required by ActiveAdmin 4
gem "importmap-rails", "~> 2.0"
gem "propshaft"
# Tailwind CLI (v4)
gem "tailwindcss-rails", "~> 4.4.0"
```
```bash
bundle install
```
## 3. Install ActiveAdmin
```bash
rails generate active_admin:install
rails db:create db:migrate db:seed
```
## 4. Install ActiveAdmin Assets
```bash
rails generate active_admin:assets
```
This creates:
- `app/assets/stylesheets/active_admin.css`
- `tailwind-active_admin.config.js` (ESM)
Rename to `.mjs` for Tailwind v4:
```bash
mv tailwind-active_admin.config.js tailwind-active_admin.config.mjs
```
## 5. Tailwind Input (ActiveAdmin)
Create or update the Tailwind input file:
```css
/* app/assets/stylesheets/active_admin.tailwind.css */
@import "tailwindcss";
@config "../../../tailwind-active_admin.config.mjs";
```
## 6. Build Tasks
```ruby
# lib/tasks/active_admin.rake
namespace :active_admin do
desc "Build Active Admin Tailwind stylesheets"
task build: :environment do
command = [
Rails.root.join("bin/tailwindcss").to_s,
"-i", Rails.root.join("app/assets/stylesheets/active_admin.tailwind.css").to_s,
"-o", Rails.root.join("app/assets/builds/active_admin.css").to_s,
"-m"
]
system(*command, exception: true)
end
desc "Watch Active Admin Tailwind stylesheets"
task watch: :environment do
command = [
Rails.root.join("bin/tailwindcss").to_s,
"--watch",
"-i", Rails.root.join("app/assets/stylesheets/active_admin.tailwind.css").to_s,
"-o", Rails.root.join("app/assets/builds/active_admin.css").to_s,
"-m"
]
system(*command, exception: true)
end
end
Rake::Task["assets:precompile"].enhance(["active_admin:build"])
```
## 7. JavaScript Entry
```javascript
// app/javascript/active_admin.js
import "@activeadmin/activeadmin";
```
## 8. Build Assets
```bash
bundle binstubs tailwindcss-ruby --force
npm install @activeadmin/activeadmin@^4.0.0-beta20
npm run build
```
## 9. Start Server
```bash
rails server
```
Visit http://localhost:3000/admin
## ActiveAdmin 4.0.0.beta20 Notes (from upgrade guide)
**Version Requirements:**
- Rails 7.2+ (Rails 7.0 and 7.1 are no longer supported)
- Ruby 3.2+ (Ruby 3.0 and 3.1 are no longer supported)
**Breaking Changes from earlier v4 betas:**
- `_site_header.html.erb` container class changed from `sticky` to `fixed`.
- `active_admin.html.erb` adds the `pt-16` utility class.
- Tailwind v4 requires `@import "tailwindcss"` + `@config`.
- jQuery and jQuery UI removed; `columns` and `tabs` components removed.
- Replace `default_main_content` with `render "show_default"`.
- Replace `as: :datepicker` with `as: :date_picker`.
- Replace `active_admin_comments` with `active_admin_comments_for(resource)`.
- Replace `attributes_table` with `attributes_table_for(resource)` in sidebars.
**New in beta20:**
- Parent menu item linking support
- Improved comments pagination styling
- Better vertical spacing for has-many forms
- Pointer cursor restored on eligible buttons
- Various accessibility improvements

181
docs/setup-activeadmin-gem.md Обычный файл
Просмотреть файл

@@ -0,0 +1,181 @@
# Setting Up an ActiveAdmin 4 Extension Gem (Combustion)
This guide mirrors the working setup used in this repo: ActiveAdmin 4.0.0.beta20 + Tailwind CSS v4 + Combustion test app.
## 1. Gem Dependencies
```ruby
# Gemfile
source "https://rubygems.org"
gemspec
gem "rails", "~> 7.2"
gem "activeadmin", "4.0.0.beta20"
gem "sqlite3"
gem "puma"
gem "importmap-rails", "~> 2.0"
gem "propshaft"
gem "tailwindcss-rails", "~> 4.4.0"
group :development, :test do
gem "combustion", "~> 1.3"
gem "rspec-rails"
gem "capybara"
end
```
## 2. Combustion Test App
```bash
bundle exec combust
```
## 3. config.ru Loading Order
```ruby
# config.ru
require "rubygems"
require "bundler"
Bundler.setup(:default, :development)
require "combustion"
Combustion.initialize! :active_record, :action_controller, :action_view do
config.load_defaults Rails::VERSION::STRING.to_f if Rails::VERSION::MAJOR >= 7
end
require "importmap-rails"
require "active_admin"
require "activeadmin_your_feature"
run Combustion::Application
```
## 4. Internal App Structure
```bash
cd spec/internal
mkdir -p app/admin app/assets/{builds,config,stylesheets} app/javascript
```
## 5. ActiveAdmin Setup
```ruby
# spec/internal/config/initializers/active_admin.rb
ActiveAdmin.setup do |config|
config.site_title = "Test App"
config.authentication_method = false
config.current_user_method = false
end
```
## 6. Tailwind Input + Config
```css
/* spec/internal/app/assets/stylesheets/active_admin.tailwind.css */
@import "tailwindcss";
@config "../../../tailwind-active_admin.config.mjs";
/* Import your gem CSS if needed */
@import "your_gem/css";
```
```javascript
// spec/internal/tailwind-active_admin.config.mjs
import { execSync } from "child_process";
import activeAdminPlugin from "@activeadmin/activeadmin/plugin";
const activeAdminPath = execSync("bundle show activeadmin", {
encoding: "utf-8"
}).trim();
export default {
content: [
`${activeAdminPath}/vendor/javascript/flowbite.js`,
`${activeAdminPath}/plugin.js`,
`${activeAdminPath}/app/views/**/*.{arb,erb,html,rb}`,
"./app/admin/**/*.{arb,erb,html,rb}",
"./app/views/**/*.{arb,erb,html,rb}",
"./app/javascript/**/*.js",
"../../app/assets/**/*.{js,css}"
],
darkMode: "selector",
plugins: [activeAdminPlugin]
};
```
## 7. Tailwind Build Tasks
```ruby
# spec/internal/lib/tasks/active_admin.rake
namespace :active_admin do
desc "Build Active Admin Tailwind stylesheets"
task build: :environment do
command = [
Rails.root.join("bin/tailwindcss").to_s,
"-i", Rails.root.join("app/assets/stylesheets/active_admin.tailwind.css").to_s,
"-o", Rails.root.join("app/assets/builds/active_admin.css").to_s,
"-m"
]
system(*command, exception: true)
end
end
```
## 8. Tailwind Binstub
```bash
bundle binstubs tailwindcss-ruby --force
```
## 9. JS Entry
```javascript
// spec/internal/app/javascript/active_admin.js
import "@activeadmin/activeadmin";
import "your_gem";
```
## 10. package.json (internal)
```json
{
"name": "internal",
"private": true,
"scripts": {
"build:js": "node esbuild.config.js",
"build:css": "bundle exec rake active_admin:build",
"build": "npm run build:js && npm run build:css"
},
"devDependencies": {
"@activeadmin/activeadmin": "^4.0.0-beta20",
"esbuild": "^0.24.2"
}
}
```
## 11. ActiveAdmin 4.0.0.beta20 Notes (from upgrade guide)
**Version Requirements:**
- Rails 7.2+ (Rails 7.0 and 7.1 are no longer supported)
- Ruby 3.2+ (Ruby 3.0 and 3.1 are no longer supported)
**Breaking Changes from earlier v4 betas:**
- `_site_header.html.erb` container class changed from `sticky` to `fixed`.
- `active_admin.html.erb` adds the `pt-16` utility class.
- Tailwind v4 requires `@import "tailwindcss"` + `@config`.
- jQuery and jQuery UI removed; `columns` and `tabs` components removed.
- Replace `default_main_content` with `render "show_default"`.
- Replace `as: :datepicker` with `as: :date_picker`.
- Replace `active_admin_comments` with `active_admin_comments_for(resource)`.
- Replace `attributes_table` with `attributes_table_for(resource)` in sidebars.
**New in beta20:**
- Parent menu item linking support
- Improved comments pagination styling
- Better vertical spacing for has-many forms
- Pointer cursor restored on eligible buttons
- Various accessibility improvements

Просмотреть файл

@@ -1,55 +0,0 @@
namespace :active_admin do
desc 'Build Active Admin Tailwind stylesheets'
task :build do
require 'fileutils'
root = File.expand_path('../../', __dir__)
# Ensure builds directory exists
FileUtils.mkdir_p(File.join(root, 'app/assets/builds'))
# Build with Tailwind CLI
command = [
'npx', 'tailwindcss',
'-i', File.join(root, 'app/assets/stylesheets/active_admin.tailwind.css'),
'-o', File.join(root, 'app/assets/builds/active_admin.css'),
'-c', File.join(root, 'tailwind.config.js'),
'-m'
]
system(*command, exception: true)
puts 'Built Active Admin CSS with Tailwind'
end
desc 'Watch Active Admin Tailwind stylesheets'
task :watch do
root = File.expand_path('../../', __dir__)
# Watch for changes
command = [
'npx', 'tailwindcss',
'--watch',
'-i', File.join(root, 'app/assets/stylesheets/active_admin.tailwind.css'),
'-o', File.join(root, 'app/assets/builds/active_admin.css'),
'-c', File.join(root, 'tailwind.config.js'),
'-m'
]
system(*command)
end
end
# Enhance existing rake tasks
if Rake::Task.task_defined?('assets:precompile')
Rake::Task['assets:precompile'].enhance(['active_admin:build'])
end
if Rake::Task.task_defined?('test:prepare')
Rake::Task['test:prepare'].enhance(['active_admin:build'])
end
if Rake::Task.task_defined?('spec:prepare')
Rake::Task['spec:prepare'].enhance(['active_admin:build'])
end
if Rake::Task.task_defined?('db:test:prepare')
Rake::Task['db:test:prepare'].enhance(['active_admin:build'])
end

Просмотреть файл

@@ -1,16 +0,0 @@
@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";
@import "activeadmin-tom_select/src/tom-select-tailwind.css";
/* Additional batch actions dropdown styles that aren't in the ActiveAdmin plugin */
@layer components {
.batch-actions-dropdown-toggle:disabled {
@apply opacity-50 cursor-not-allowed;
}
.batch-actions-dropdown-arrow {
@apply w-2.5 h-2.5;
}
}

Просмотреть файл

@@ -1,18 +0,0 @@
const execSync = require("node:child_process").execSync;
const activeAdminPath = execSync("bundle show activeadmin", {
encoding: "utf-8",
}).trim();
module.exports = {
content: [
`${activeAdminPath}/vendor/javascript/flowbite.js`,
`${activeAdminPath}/plugin.js`,
`${activeAdminPath}/app/views/**/*.{arb,erb,html,rb}`,
"./app/admin/**/*.{arb,erb,html,rb}",
"./app/views/active_admin/**/*.{arb,erb,html,rb}",
"./app/views/admin/**/*.{arb,erb,html,rb}",
"./app/views/layouts/active_admin*.{erb,html}",
"./app/assets/controllers/active_admin/**/*.js",
],
darkMode: "selector"
};

225
docs/upload-system.md Обычный файл
Просмотреть файл

@@ -0,0 +1,225 @@
# CKEditor5-Rails Upload System Documentation
## Overview
The CKEditor5-Rails gem implements a flexible image upload system that allows users to upload images directly from the editor to a server endpoint instead of embedding them as Base64. The system is designed to be backend-agnostic and can integrate with various storage solutions including ActiveStorage and Shrine.
## Architecture
### Core Components
#### 1. SimpleUploadAdapter Plugin (`lib/ckeditor5/rails/plugins/simple_upload_adapter.rb`)
The heart of the upload system is an inline JavaScript plugin that:
- Extends CKEditor5's Plugin class
- Requires the FileRepository plugin as a dependency
- Implements the upload adapter factory pattern
- Handles file uploads via XMLHttpRequest with progress tracking
**Location**: `lib/ckeditor5/rails/plugins/simple_upload_adapter.rb`
**Key Features**:
- Async/await based upload handling
- Progress tracking through XMLHttpRequest events
- CSRF token integration for Rails security
- Abort capability for cancelled uploads
- JSON response parsing for uploaded file URLs
#### 2. PropsInlinePlugin Base Class (`lib/ckeditor5/rails/editor/props_inline_plugin.rb`)
The upload adapter extends this base class which:
- Wraps JavaScript code in an async IIFE (Immediately Invoked Function Expression)
- Supports optional code compression via Terser
- Provides window-based plugin registration mechanism
- Handles plugin initialization errors gracefully
**Location**: `lib/ckeditor5/rails/editor/props_inline_plugin.rb`
#### 3. Plugin Registration System (`lib/ckeditor5/rails/plugins.rb`)
Central registry that:
- Loads all core plugins including SimpleUploadAdapter
- Manages plugin dependencies
- Handles plugin patches and fixes
**Location**: `lib/ckeditor5/rails/plugins.rb`
## Configuration System
### Preset Builder Integration (`lib/ckeditor5/rails/presets/preset_builder.rb`)
The upload adapter is configured through the preset system:
```ruby
def simple_upload_adapter(upload_url = '/uploads', compress: !@disallow_inline_plugin_compression)
plugins do
remove(:Base64UploadAdapter) # Remove default Base64 adapter
end
plugin(Plugins::SimpleUploadAdapter.new(compress: compress))
configure(:simpleUpload, { uploadUrl: upload_url })
end
```
**Location**: `lib/ckeditor5/rails/presets/preset_builder.rb:394-401`
**Configuration Steps**:
1. Removes the default Base64UploadAdapter plugin
2. Adds the SimpleUploadAdapter plugin
3. Configures the upload URL endpoint
4. Optionally enables/disables JavaScript compression
### Usage in Presets
Upload functionality is enabled in presets via:
```ruby
# In preset definition
simple_upload_adapter # Uses default '/uploads' endpoint
simple_upload_adapter '/custom' # Custom endpoint
```
**Example Location**: `sandbox/config/initializers/ckeditor5.rb:82`
## Frontend Implementation
### Upload Flow
1. **User Action**: User selects/pastes an image in the editor
2. **Plugin Activation**: FileRepository triggers createUploadAdapter
3. **Adapter Creation**: SimpleUploadAdapter creates an upload instance
4. **FormData Preparation**: File wrapped in FormData with 'upload' field name
5. **Security Headers**:
- X-Requested-With: XMLHttpRequest
- X-CSRF-Token: Extracted from meta tag
6. **Upload Process**:
- Progress events update loader.uploaded/uploadTotal
- Success (200-299): Parse JSON response for URL
- Error handling for failed/aborted uploads
7. **Editor Update**: Returned URL replaces placeholder image
### Response Format
Server must return JSON with structure:
```json
{
"url": "https://example.com/uploads/image.jpg"
}
```
## Integration Points
### 1. Rails Controller
The upload endpoint (not included in gem) should:
- Accept POST requests to configured URL
- Process multipart/form-data with 'upload' field
- Store file using preferred backend (ActiveStorage, Shrine, etc.)
- Return JSON with uploaded file URL
- Handle CSRF token validation
### 2. Helper Methods
Upload configuration accessible via:
- `ckeditor5_editor` helper in views
- Preset configuration in initializers
- Runtime configuration overrides
**Location**: `lib/ckeditor5/rails/editor/helpers/editor_helpers.rb`
### 3. Engine Registration
Upload adapter available through:
- Engine preset system
- Direct plugin inclusion
- Configuration DSL methods
**Location**: `lib/ckeditor5/rails/engine.rb:83`
## File Structure
```
lib/ckeditor5/rails/
├── plugins/
│ ├── simple_upload_adapter.rb # Main upload adapter implementation
│ └── ...
├── editor/
│ ├── props_inline_plugin.rb # Base class for inline plugins
│ └── helpers/
│ └── editor_helpers.rb # View helpers for editor
├── presets/
│ └── preset_builder.rb # Configuration DSL with upload method
└── engine.rb # Rails engine with upload registration
```
## Configuration Examples
### Basic Setup
```ruby
CKEditor5::Rails.configure do
# Enable with default /uploads endpoint
simple_upload_adapter
end
```
### Custom Endpoint
```ruby
CKEditor5::Rails.configure do
# Custom upload endpoint
simple_upload_adapter '/api/images/upload'
end
```
### With Compression Disabled
```ruby
CKEditor5::Rails.configure do
# Disable JavaScript compression for debugging
simple_upload_adapter '/uploads', compress: false
end
```
## Key Implementation Details
### JavaScript Plugin Structure
The plugin is written as an ES6 module that:
1. Imports required CKEditor5 modules dynamically
2. Returns a class extending Plugin
3. Implements standard CKEditor5 plugin lifecycle
4. Integrates with FileRepository for upload management
### Security Considerations
- CSRF token automatically extracted from Rails meta tag
- XMLHttpRequest marked with X-Requested-With header
- Server-side validation responsibility lies with implementer
### Error Handling
- Network errors caught and rejected with descriptive messages
- HTTP status codes outside 200-299 range treated as errors
- Upload abort capability for user cancellation
## Backend Requirements
To implement the upload endpoint:
1. **Route Definition**: Add POST route to configured URL
2. **File Processing**: Handle multipart upload with 'upload' parameter
3. **Storage Backend**: Integrate with ActiveStorage, Shrine, or custom solution
4. **Response Format**: Return JSON with 'url' key
5. **Security**: Validate CSRF tokens and user permissions
## Extension Points
The system supports:
- Multiple upload adapters via plugin system
- Custom configuration through preset builder
- Backend flexibility through endpoint abstraction
- Compression toggle for development/production
- Integration with various storage backends
This architecture provides a clean separation between the editor frontend and storage backend, allowing developers to implement uploads using their preferred Rails patterns and storage solutions.

Просмотреть файл

@@ -1,32 +0,0 @@
# This file was generated by Appraisal
source "https://rubygems.org"
gem "rails", "~> 6.1.0"
gem "activeadmin", "~> 2.9.0"
gem "sqlite3", "~> 1.4"
gem "concurrent-ruby", "1.3.4"
gem "bigdecimal"
gem "csv"
gem "mutex_m"
gem "puma"
gem "capybara"
gem "cuprite"
gem "rspec_junit_formatter"
gem "rspec-rails"
gem "simplecov", require: false
gem "super_diff"
gem "fasterer"
gem "rubocop"
gem "rubocop-capybara"
gem "rubocop-packaging"
gem "rubocop-performance"
gem "rubocop-rails"
gem "rubocop-rspec"
gem "rubocop-rspec_rails"
gem "appraisal"
gem "pry-rails"
gem "sassc"
gem "sprockets-rails"
gemspec path: "../"

Просмотреть файл

@@ -1,32 +0,0 @@
# This file was generated by Appraisal
source "https://rubygems.org"
gem "rails", "~> 7.0.0"
gem "activeadmin", "~> 2.14"
gem "sqlite3", "~> 1.4"
gem "concurrent-ruby", "1.3.4"
gem "bigdecimal"
gem "csv"
gem "mutex_m"
gem "puma"
gem "capybara"
gem "cuprite"
gem "rspec_junit_formatter"
gem "rspec-rails"
gem "simplecov", require: false
gem "super_diff"
gem "fasterer"
gem "rubocop"
gem "rubocop-capybara"
gem "rubocop-packaging"
gem "rubocop-performance"
gem "rubocop-rails"
gem "rubocop-rspec"
gem "rubocop-rspec_rails"
gem "appraisal"
gem "pry-rails"
gem "sassc"
gem "sprockets-rails"
gemspec path: "../"

Просмотреть файл

@@ -1,32 +0,0 @@
# This file was generated by Appraisal
source "https://rubygems.org"
gem "rails", "~> 7.0.0"
gem "activeadmin", "~> 3.2"
gem "sqlite3", "~> 1.4"
gem "concurrent-ruby", "1.3.4"
gem "bigdecimal"
gem "csv"
gem "mutex_m"
gem "puma"
gem "capybara"
gem "cuprite"
gem "rspec_junit_formatter"
gem "rspec-rails"
gem "simplecov", require: false
gem "super_diff"
gem "fasterer"
gem "rubocop"
gem "rubocop-capybara"
gem "rubocop-packaging"
gem "rubocop-performance"
gem "rubocop-rails"
gem "rubocop-rspec"
gem "rubocop-rspec_rails"
gem "appraisal"
gem "pry-rails"
gem "sassc"
gem "sprockets-rails"
gemspec path: "../"

Просмотреть файл

@@ -1,32 +0,0 @@
# This file was generated by Appraisal
source "https://rubygems.org"
gem "rails", "~> 7.1.0"
gem "activeadmin", "~> 3.2"
gem "sqlite3", "~> 1.4"
gem "concurrent-ruby", "1.3.4"
gem "bigdecimal"
gem "csv"
gem "mutex_m"
gem "puma"
gem "capybara"
gem "cuprite"
gem "rspec_junit_formatter"
gem "rspec-rails"
gem "simplecov", require: false
gem "super_diff"
gem "fasterer"
gem "rubocop"
gem "rubocop-capybara"
gem "rubocop-packaging"
gem "rubocop-performance"
gem "rubocop-rails"
gem "rubocop-rspec"
gem "rubocop-rspec_rails"
gem "appraisal"
gem "pry-rails"
gem "sassc"
gem "sprockets-rails"
gemspec path: "../"

Просмотреть файл

@@ -1,32 +0,0 @@
# This file was generated by Appraisal
source "https://rubygems.org"
gem "rails", "~> 7.2.0"
gem "activeadmin", "~> 3.2"
gem "sqlite3"
gem "concurrent-ruby", "1.3.4"
gem "bigdecimal"
gem "csv"
gem "mutex_m"
gem "puma"
gem "capybara"
gem "cuprite"
gem "rspec_junit_formatter"
gem "rspec-rails"
gem "simplecov", require: false
gem "super_diff"
gem "fasterer"
gem "rubocop"
gem "rubocop-capybara"
gem "rubocop-packaging"
gem "rubocop-performance"
gem "rubocop-rails"
gem "rubocop-rspec"
gem "rubocop-rspec_rails"
gem "appraisal"
gem "pry-rails"
gem "sassc"
gem "sprockets-rails"
gemspec path: "../"

Просмотреть файл

@@ -3,7 +3,7 @@
source "https://rubygems.org"
gem "rails", "~> 7.2.0"
gem "activeadmin", "4.0.0.beta16"
gem "activeadmin", "4.0.0.beta20"
gem "sqlite3"
gem "concurrent-ruby", "1.3.4"
gem "bigdecimal"

Просмотреть файл

@@ -3,7 +3,7 @@
source "https://rubygems.org"
gem "rails", "~> 8.0.0"
gem "activeadmin", "4.0.0.beta16"
gem "activeadmin", "4.0.0.beta20"
gem "sqlite3"
gem "concurrent-ruby", "1.3.4"
gem "bigdecimal"

Просмотреть файл

@@ -2,7 +2,7 @@
module ActiveAdmin
module QuillEditor
VERSION = '2.0.0'
VERSION = '2.1.0'
QUILL_VERSION = '2.0.3'
end
end