Shrine 开源项目教程

Shrine 开源项目教程

shrineFile Attachment toolkit for Ruby applications项目地址:https://gitcode.com/gh_mirrors/sh/shrine

项目介绍

Shrine 是一个用于文件上传的 Ruby 库,它提供了灵活的插件架构,使得开发者可以根据需要定制上传功能。Shrine 支持多种存储后端,如文件系统、Amazon S3 等,并且可以轻松集成到 Rails 等框架中。

项目快速启动

安装

首先,将 Shrine 添加到你的 Gemfile 中:

gem 'shrine'

然后运行 bundle install

配置

创建一个初始化文件 config/initializers/shrine.rb

require "shrine"
require "shrine/storage/file_system"

Shrine.plugin :sequel # 如果你使用 Sequel
Shrine.plugin :activerecord # 如果你使用 ActiveRecord
Shrine.plugin :cached_attachment_data # 用于缓存上传的文件
Shrine.plugin :restore_cached_data # 用于解析缓存的文件数据

Shrine.storages = {
  cache: Shrine::Storage::FileSystem.new("public", prefix: "uploads/cache"),
  store: Shrine::Storage::FileSystem.new("public", prefix: "uploads/store"),
}

模型定义

在你的模型中添加附件:

class ImageUploader < Shrine
  # 插件和上传选项
end

class Photo < Sequel::Model # 或 ActiveRecord::Base
  include ImageUploader::Attachment(:image)
end

表单

在你的表单中添加文件上传字段:

<%= form_for @photo do |f| %>
  <%= f.hidden_field :image, value: @photo.cached_image_data %>
  <%= f.file_field :image %>
  <%= f.submit %>
<% end %>

应用案例和最佳实践

多文件上传

Shrine 支持多文件上传,可以通过数组形式处理多个文件:

class Album < Sequel::Model # 或 ActiveRecord::Base
  include ImageUploader::Attachment(:images)
end

存储到 Amazon S3

配置 Shrine 使用 Amazon S3 存储:

require "shrine/storage/s3"

s3_options = {
  access_key_id: "YOUR_ACCESS_KEY_ID",
  secret_access_key: "YOUR_SECRET_ACCESS_KEY",
  region: "YOUR_REGION",
  bucket: "YOUR_BUCKET",
}

Shrine.storages = {
  cache: Shrine::Storage::S3.new(prefix: "cache", **s3_options),
  store: Shrine::Storage::S3.new(prefix: "store", **s3_options),
}

典型生态项目

Refile

Refile 是另一个文件上传库,但它的功能相对简单,适合小型项目。

CarrierWave

CarrierWave 是另一个流行的文件上传库,它提供了丰富的功能和灵活的配置选项,适合中大型项目。

Active Storage

Active Storage 是 Rails 5.2 引入的官方文件上传解决方案,它与 Rails 集成紧密,适合 Rails 项目。

通过以上教程,你应该能够快速上手并使用 Shrine 进行文件上传。希望这些内容对你有所帮助!

shrineFile Attachment toolkit for Ruby applications项目地址:https://gitcode.com/gh_mirrors/sh/shrine

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

伍辰惟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值