Primer View Components 项目教程
1. 项目的目录结构及介绍
primer/view_components/
├── app/
│ ├── components/
│ │ ├── message_component.rb
│ │ └── message_component.html.erb
│ └── views/
│ └── demo/
│ └── index.html.erb
├── config/
│ └── application.rb
├── lib/
│ └── tasks/
├── spec/
│ └── components/
│ └── message_component_spec.rb
├── Gemfile
├── Gemfile.lock
└── README.md
目录结构介绍
- app/components/: 存放ViewComponents的Ruby文件和对应的模板文件。
message_component.rb
: ViewComponent的Ruby类文件。message_component.html.erb
: ViewComponent的模板文件。
- app/views/demo/: 存放视图文件,用于渲染ViewComponents。
index.html.erb
: 示例视图文件,用于调用ViewComponent。
- config/: 存放项目的配置文件。
application.rb
: 应用程序的主要配置文件。
- lib/tasks/: 存放Rake任务文件。
- spec/components/: 存放ViewComponents的测试文件。
message_component_spec.rb
: ViewComponent的单元测试文件。
- Gemfile: 定义项目所需的Ruby gems。
- Gemfile.lock: 锁定gems的版本。
- README.md: 项目的说明文档。
2. 项目的启动文件介绍
app/components/message_component.rb
class MessageComponent < ViewComponent::Base
def initialize(name:)
@name = name
end
end
app/components/message_component.html.erb
<h1>Hello <%= @name %></h1>
app/views/demo/index.html.erb
<%= render(MessageComponent.new(name: "World")) %>
3. 项目的配置文件介绍
config/application.rb
require_relative "boot"
require "rails/all"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module MyApp
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 6.1
# Configuration for the application, engines, and railties goes here.
#
# These settings can be overridden in specific environments using the files
# in config/environments, which are processed later.
#
# config.time_zone = "Central Time (US & Canada)"
# config.eager_load_paths << Rails.root.join("extras")
end
end
Gemfile
source 'https://rubygems.org'
gem 'rails', '~> 6.1.0'
gem 'view_component', '~> 2.0'
group :development, :test do
gem 'rspec-rails', '~> 5.0'
end
Gemfile.lock
GEM
remote: https://rubygems.org/
specs:
actioncable (6.1.0)
actionmailbox (6.1.0)
actionmailer (6.1.0)
actionpack (6.1.0)
actiontext (6.1.0)
actionview (6.1.0)
activejob (6.1.0)
activemodel (6.1.0)
activerecord (6.1.0)
activestorage (6.1.0)
activesupport (6.1.0)
rails (6.1.0)
actioncable (= 6.1.0)
actionmailbox (= 6.1.0)
actionmailer (= 6.1.0)
actionpack (= 6.1.0)
actiontext (= 6.1.0)
actionview (= 6.1.0)
activejob (= 6.1.0)
activemodel (= 6.1.0)
activerecord (= 6.1.0)
activestorage (= 6.1.0)
activesupport (= 6.1.0)
view_component (2.0.0)
PLATFORMS
ruby
DEPENDENCIES
rails (~> 6.1.0)
view_component (~> 2.0)
BUNDLED WITH
2.2.15
以上是基于开源项目 primer/view_components
的教程,涵盖了项目的目录结构、启动文件和配置文件的介绍。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考