style_capsule
CSS scoping for Ruby components. Attribute selectors encapsulate styles for Phlex, ViewComponent, and ERB so rules stay inside the component wrapper. Works with Rails and standalone in other Ruby frameworks (Sinatra, Hanami, and similar) or plain Ruby. Cache strategies: none, time-based, custom proc, and file-based.
Design changes go through rfcs/ (RFC 0001).
Installation
Add to your Gemfile:
gem "style_capsule"Then run bundle install.
Features
- Attribute-based CSS scoping (class names stay as written)
- Phlex, ViewComponent, and ERB; Rails integration via the railtie
- Per-component-type scope IDs (shared across instances)
- Optional CSS nesting (
:nesting) for browsers that support it - Stylesheet registry for head rendering, namespaces, and asset bundlers such as Propshaft
- Cache strategies: none, time-based, custom proc, and file-based
-
ActiveSupport::Notificationsevents for CSS processing and file writes - Fallback output directory when the primary path is not writable
- Path traversal checks, input validation, and CSS size limits
Usage
Phlex Components
class MyComponent < ApplicationComponent
include StyleCapsule::Component
def component_styles
<<~CSS
.section { color: red; }
.heading:hover { opacity: 0.8; }
CSS
end
def view_template
div(class: "section") do
h2(class: "heading") { "Hello" }
end
end
endCSS is automatically scoped with [data-capsule="..."] attributes and content is wrapped in a scoped element.
ViewComponent
class MyComponent < ApplicationComponent
include StyleCapsule::ViewComponent
def component_styles
<<~CSS
.section { color: red; }
CSS
end
def call
content_tag :div, class: "section" do
"Hello"
end
end
endERB Templates
<%= style_capsule do %>
<style>
.section { color: red; }
</style>
<div class="section">Content</div>
<% end %>With custom wrapper tag:
<%= style_capsule(tag: :section) do %>
<style>
.section { color: red; }
</style>
<div class="section">Content</div>
<% end %>CSS Scoping Strategies
StyleCapsule supports two CSS scoping strategies:
-
Selector Patching (default): Adds
[data-capsule="..."]prefix to each selector- Better browser support (all modern browsers)
- Output:
[data-capsule="abc123"] .section { color: red; }
-
CSS Nesting (optional): Wraps nestable rules in
[data-capsule="..."] { ... }- Skips per-selector rewrite; hoists
@keyframes/@font-faceand similar to top level - Requires CSS nesting support (Chrome 112+, Firefox 117+, Safari 16.5+)
- Output:
[data-capsule="abc123"] { .section { color: red; } }
- Skips per-selector rewrite; hoists
Configuration
Per-component (using style_capsule - recommended):
class MyComponent < ApplicationComponent
include StyleCapsule::Component
style_capsule scoping_strategy: :nesting # Use CSS nesting
endWith custom wrapper tag:
class MyComponent < ApplicationComponent
include StyleCapsule::Component
style_capsule tag: :section # Use <section> instead of <div> for wrapper
endGlobal (in base component class):
class ApplicationComponent < Phlex::HTML
include StyleCapsule::Component
style_capsule scoping_strategy: :nesting # Enable for all components
endNote: If you change the strategy and it doesn't take effect, clear the CSS cache:
MyComponent.clear_css_cacheStylesheet Registry
Register styles for head rendering when the layout should emit links or shared style tags instead of body <style> tags. Configure with style_capsule:
class MyComponent < ApplicationComponent
include StyleCapsule::Component
style_capsule namespace: :admin # Configure namespace and enable head rendering
def component_styles
<<~CSS
.section { color: red; }
CSS
end
endWith cache strategy and CSS scoping:
class MyComponent < ApplicationComponent
include StyleCapsule::Component
style_capsule(
namespace: :admin,
cache_strategy: :time,
cache_ttl: 1.hour,
scoping_strategy: :nesting
)
def component_styles
<<~CSS
.section { color: red; }
CSS
end
endThen in your layout (render only the namespace you need):
<head>
<%= stylesheet_registry_tags(namespace: :admin) %>
</head>Or in Phlex (requires including StyleCapsule::PhlexHelper):
head do
stylesheet_registry_tags(namespace: :admin)
endNamespace Isolation: Using namespaces prevents stylesheet leakage between different application contexts. For example, login pages can use namespace: :login, ActiveAdmin can use namespace: :active_admin, and user components can use namespace: :user. Each namespace is rendered separately, improving caching efficiency and preventing style conflicts.
Registering Stylesheet Files
You can also register external stylesheet files (not inline CSS) for head rendering. When a component has a configured namespace via style_capsule, you don't need to specify it every time:
In ERB:
<% register_stylesheet("stylesheets/user/my_component", "data-turbo-track": "reload") %>
<% register_stylesheet("stylesheets/admin/dashboard", namespace: :admin) %>In Phlex (requires including StyleCapsule::PhlexHelper):
class UserComponent < ApplicationComponent
include StyleCapsule::Component
include StyleCapsule::PhlexHelper
style_capsule namespace: :user # Set default namespace
def view_template
# Namespace automatically uses :user from style_capsule
register_stylesheet("stylesheets/user/my_component", "data-turbo-track": "reload")
# Can still override namespace if needed
register_stylesheet("stylesheets/shared/common", namespace: :shared)
div { "Content" }
end
endIn ViewComponent (requires including StyleCapsule::ViewComponentHelper):
class UserComponent < ApplicationComponent
include StyleCapsule::ViewComponent
include StyleCapsule::ViewComponentHelper
style_capsule namespace: :user # Set default namespace
def call
# Namespace automatically uses :user from style_capsule
register_stylesheet("stylesheets/user/my_component", "data-turbo-track": "reload")
content_tag(:div, "Content")
end
endRegistered files are rendered via stylesheet_registry_tags in your layout, just like inline CSS. The namespace is automatically used from the component's style_capsule configuration when not explicitly specified.
Boot-time file paths: register static paths once with StyleCapsule::StylesheetRegistry.register_eager(...) (initializers, class load). Use register / register_stylesheet during rendering for request-scoped paths.
Late head injection (Rails)
Layouts usually call stylesheet_registry_tags in <head> before the body renders. Components that call register_stylesheet later in the same response would miss that call without help.
By default, StyleCapsule::HeadInjectionMiddleware appends pending request-scoped stylesheet tags immediately before </head> after the response body is built. Disable when you buffer or stream the body yourself:
# config/application.rb
config.style_capsule.head_injection_middleware = falseThe middleware only rewrites bufferable bodies (Rack bodies that respond to to_ary). Chunked HTML with a bufferable body is injected, then returned with Content-Length and without Transfer-Encoding. Non-bufferable streaming bodies (ActionController::Live, SSE, and similar) are left alone; disable the middleware and inject manually with StyleCapsule::StylesheetRegistry.inject_pending_head_stylesheets if needed. The middleware does not buffer when no pending request-scoped stylesheets remain. When it does rewrite, it holds the full 2xx HTML body in memory.
Caching Strategies
No Caching (Default)
class MyComponent < ApplicationComponent
include StyleCapsule::Component
style_capsule # No cache strategy set (default: :none)
endTime-Based Caching
style_capsule cache_strategy: :time, cache_ttl: 1.hour # Using ActiveSupport::Duration
# Or using integer seconds:
style_capsule cache_strategy: :time, cache_ttl: 3600 # Cache for 1 hourCustom Proc Caching
style_capsule cache_strategy: ->(css, capsule_id, namespace) {
cache_key = "css_#{capsule_id}_#{namespace}"
should_cache = css.length > 100
expires_at = Time.now + 1800
[cache_key, should_cache, expires_at]
}Note: cache_strategy accepts Symbol (:time), String ("time"), or Proc. Strings are automatically converted to symbols.
File-Based Caching (HTTP Caching)
Writes CSS to files for HTTP caching. Requires class method def self.component_styles:
class MyComponent < ApplicationComponent
include StyleCapsule::Component
style_capsule cache_strategy: :file
# Must use class method for file caching
def self.component_styles
<<~CSS
.section { color: red; }
CSS
end
endConfiguration:
# config/initializers/style_capsule.rb
StyleCapsule::CssFileWriter.configure(
output_dir: Rails.root.join("app/assets/builds/capsules"),
filename_pattern: ->(component_class, capsule_id) {
"capsule-#{capsule_id}.css"
},
fallback_dir: StyleCapsule::CssFileWriter::FALLBACK_OUTPUT_DIR
)Fallback Directory: When the primary output directory is not writable (for example a read-only app tree in a container), writes go under a per-user directory in Dir.tmpdir. If that write also fails, rendering uses inline CSS.
Precompilation:
bin/rails style_capsule:build # Build CSS files
bin/rails style_capsule:clear # Clear generated filesFiles are automatically built during bin/rails assets:precompile.
Compatibility: The stylesheet registry works with Propshaft, Sprockets, and other Rails asset bundlers. Static file paths are collected in a process-wide manifest (similar to Propshaft's approach), while inline CSS is stored per-request.
Instrumentation
Subscribe to ActiveSupport::Notifications for CSS processing and file write events. Metric payloads are built only when a subscriber is present.
Available Events
-
style_capsule.css_processor.scope- CSS scoping operations with duration and size metrics -
style_capsule.css_file_writer.write- CSS file write operations with duration and size metrics -
style_capsule.css_file_writer.fallback- When fallback directory is used (read-only filesystem) -
style_capsule.css_file_writer.fallback_failure- When both primary and fallback directories fail -
style_capsule.css_file_writer.write_failure- Other write errors
Example: Monitoring CSS Processing
# config/initializers/style_capsule.rb
ActiveSupport::Notifications.subscribe("style_capsule.css_processor.scope") do |name, start, finish, id, payload|
duration_ms = (finish - start) * 1000
Rails.logger.info "CSS scoped in #{duration_ms.round(2)}ms, input: #{payload[:input_size]} bytes, output: #{payload[:output_size]} bytes"
endExample: Monitoring File Writes
ActiveSupport::Notifications.subscribe("style_capsule.css_file_writer.write") do |name, start, finish, id, payload|
duration_ms = (finish - start) * 1000
StatsD.timing("style_capsule.write.duration", duration_ms)
StatsD.histogram("style_capsule.write.size", payload[:size])
endExample: Monitoring Fallback Scenarios
ActiveSupport::Notifications.subscribe("style_capsule.css_file_writer.fallback") do |name, start, finish, id, payload|
Rails.logger.warn "StyleCapsule fallback used: #{payload[:component_class]} -> #{payload[:fallback_path]}"
# Exception info available: payload[:exception] and payload[:exception_object]
StatsD.increment("style_capsule.css_file_writer.fallback", tags: [
"component:#{payload[:component_class]}",
"error:#{payload[:exception].first}"
])
endExample: Error Reporting
ActiveSupport::Notifications.subscribe("style_capsule.css_file_writer.fallback_failure") do |name, start, finish, id, payload|
ActionReporter.notify(
"StyleCapsule: CSS write failure (both primary and fallback failed)",
context: {
component_class: payload[:component_class],
original_path: payload[:original_path],
fallback_path: payload[:fallback_path],
original_exception: payload[:original_exception],
fallback_exception: payload[:fallback_exception]
}
)
endFor more details, see the ActiveSupport::Notifications documentation.
Advanced Usage
Database-Stored CSS
For CSS stored in a database (e.g., user-generated styles, themes), use StyleCapsule's CSS processor directly:
# app/models/theme.rb
class Theme < ApplicationRecord
def generate_capsule_id
return capsule_id if capsule_id.present?
scope_key = "theme_#{id}_#{name}"
self.capsule_id = "a#{Digest::SHA1.hexdigest(scope_key)}"[0, 8]
save! if persisted?
capsule_id
end
def scoped_css
return scoped_css_cache if scoped_css_cache.present? &&
scoped_css_updated_at == updated_at
current_capsule_id = generate_capsule_id
scoped = StyleCapsule::CssProcessor.scope_selectors(css_content, current_capsule_id)
update_columns(
scoped_css_cache: scoped,
scoped_css_updated_at: updated_at,
capsule_id: current_capsule_id
)
scoped
end
endUsage:
<div data-capsule="<%= theme.capsule_id %>">
<style><%= raw theme.scoped_css %></style>
<div class="header">Content</div>
</div>CSS Selector Support
- Regular selectors:
.section,#header,div.container - Pseudo-classes and pseudo-elements:
.button:hover,.item::before - Multiple selectors:
.a, .b, .c { color: red; } - Component-scoped selectors:
:host,:host(.active),:host-context(.theme-dark) - Media queries:
@media (max-width: 768px) { ... }
Requirements
- Ruby >= 3.4
- Rails >= 7.0, < 9.0 (optional, for Rails integration)
- ActiveSupport >= 7.0, < 9.0 (optional, for Rails integration)
Note: The gem works without Rails. See Non-Rails Support below.
Non-Rails Support
The core library is framework-agnostic. Without Rails, use StyleCapsule::CssProcessor directly, StyleCapsule::Component with Phlex, or StyleCapsule::StandaloneHelper for ERB-style templates. The stylesheet registry falls back to thread-local storage when ActiveSupport::CurrentAttributes is not loaded.
Experimental Fiber isolation: StyleCapsule.isolation_level = :fiber isolates request-scoped stylesheet registry state and the helper scope cache per Fiber (for Fiber servers / interleaved Fibers on one Thread). It does not flip Rails' own config.active_support.isolation_level; Falcon-style apps usually set both.
For setup examples, API notes, and the relationship between style_capsule and stylesheet_registry, see docs/non_rails_support.md.
How It Works
- Scope ID Generation: Each component class gets a unique scope ID based on its class name (shared across all instances)
- CSS Rewriting: CSS selectors gain
[data-capsule="..."]attribute selectors (or a nesting wrapper) - HTML Wrapping: Component content is wrapped in a scoped element
- Class names: Class names in CSS and markup stay as written
Development
bundle install
bundle exec appraisal install
# Run tests
bundle exec polyrun parallel-rspec --workers 5 --merge-failures
# Run tests for all Rails versions
bundle exec appraisal rails72 polyrun parallel-rspec --workers 5 --merge-failures
bundle exec appraisal rails8ruby34 polyrun parallel-rspec --workers 5 --merge-failures
# Linting
bundle exec standardrb --fixContributing
Bug reports and pull requests are welcome on GitHub at https://github.com/amkisko/style_capsule.rb
Contribution policy:
- New features are not necessarily added to the gem
- Pull requests should have test coverage and changelog entry
Review policy:
- Critical fixes: up to 2 calendar weeks
- Pull requests: up to 6 calendar months
- Issues: up to 1 calendar year
Publishing
rm style_capsule-*.gem
gem build style_capsule.gemspec
gem push style_capsule-*.gemSecurity
StyleCapsule includes security protections:
- Path traversal protection
- Capsule id and HTML attribute validation and escaping
- Size limits (1MB per component)
- Reject CSS that would close a style tag
For detailed security information, see SECURITY.md.
Links
- GitHub
- GitLab
- RubyGems
-
Versions Atom (feed id
9946895197223) - libraries.io
- Deps.dev
- SonarCloud
- Snyk
- Codecov
- OpenSSF Scorecard
License
The gem is available as open source under the terms of the MIT License.
Sponsors
Sponsored by Kisko Labs.