ViewComponent Contrib 使用指南
1. 项目介绍
ViewComponent Contrib 是一个为 ViewComponent 提供扩展和开发者工具的集合。它旨在简化 ViewComponent 的使用,提供更多的功能和模式,帮助开发者更高效地构建和维护 Rails 应用中的视图组件。
2. 项目快速启动
安装
首先,确保你已经安装了 Ruby on Rails 和 ViewComponent。然后,将 ViewComponent Contrib 添加到你的 Gemfile 中:
gem 'view_component-contrib'
运行 bundle install
安装依赖。
初始化
使用交互式生成器(自定义 Rails 模板)来快速启动 ViewComponent Contrib:
rails app:template LOCATION='https://github.com/palkan/view_component-contrib/blob/main/template.rb'
创建组件
创建一个新的组件:
rails generate component ExampleComponent
这将生成以下文件:
app/components/example_component/example_component.html.erb
app/components/example_component/example_component.rb
使用组件
在你的视图中使用新创建的组件:
<%= render ExampleComponent.new %>
3. 应用案例和最佳实践
国际化支持
ViewComponent Contrib 提供了内置的国际化支持。如果你使用 ViewComponentContrib::Base
,你已经包含了翻译支持。否则,你需要手动包含模块:
class ApplicationViewComponent < ViewComponent::Base
include ViewComponentContrib::TranslationHelper
end
你可以覆盖默认的命名空间和特定组件的作用域:
class ApplicationViewComponent < ViewComponentContrib::Base
self.i18n_namespace = "my_components"
end
class SomeButton::Component < ApplicationViewComponent
self.i18n_scope = %w[legacy button]
end
CSS 模块化
使用 postcss-modules
插件来隔离 CSS,确保类名在组件中是局部的,并在构建时生成唯一的类名:
<div class="<%= css_module_class('example-class') %>">
<!-- 组件内容 -->
</div>
4. 典型生态项目
Dry-Initializer
ViewComponent Contrib 推荐使用 dry-initializer
来改进开发体验,将命令式的 #initialize
方法转换为声明式的方式:
class ExampleComponent < ViewComponent::Base
extend Dry::Initializer
option :title, default: proc { "Default Title" }
end
ViewComponentContrib::Preview
使用 ViewComponentContrib::Preview
类来减少样板代码,并提供一组有用的助手:
class ExampleComponentPreview < ViewComponentContrib::Preview::Base
def default
render_with_template
end
end
通过这些工具和扩展,ViewComponent Contrib 帮助开发者更高效地构建和维护 Rails 应用中的视图组件。