首页
/ Active Delivery 使用教程

Active Delivery 使用教程

2024-08-27 22:36:03作者:苗圣禹Peter

项目介绍

Active Delivery 是一个 Ruby 和 Rails 框架,用于在一个地方管理所有类型的通知。它提供了一个单一的接口或抽象层,用于处理不同类型的通知,如邮件、推送通知等。Active Delivery 从 v1.0 版本开始与 Abstract Notifier 捆绑在一起,使得开发者可以轻松地创建和管理用户通知。

项目快速启动

安装

首先,在 Gemfile 中添加以下行:

gem "active_delivery", "~> 1.0"

然后执行:

bundle install

配置

创建一个基础的 Delivery 类,并配置通知线路:

# 在基础类中配置通知线路
class ApplicationDelivery < ActiveDelivery::Base
  self.abstract_class = true

  # 例如,你可以使用一个自定义的通知线路
  register_line :sms, ActiveDelivery::Lines::Notifier, resolver: ->(_1) { _1.name.gsub(/Delivery$/, "SMSNotifier").safe_constantize }
end

使用

创建一个具体的 Delivery 类,并触发通知:

class PostDelivery < ApplicationDelivery
  def notify_about_new_post(post)
    with(post: post).notify(:new_post)
  end
end

在控制器或其他地方调用:

PostDelivery.notify_about_new_post(post)

应用案例和最佳实践

组织通知逻辑

使用 Active Delivery 可以更好地组织通知相关的逻辑。例如,之前你可能需要在多个地方处理通知逻辑,现在可以集中在一个地方处理:

# 之前
def after_some_action
  MyMailer.with(user: user).some_action(resource).deliver_later if user.receive_emails
  NotifyService.send_notification(user, "action") if whatever_else
end

# 之后
def after_some_action
  MyDelivery.with(user: user).some_action(resource).deliver_later
end

测试

Active Delivery 提供了优雅的方式来测试通知是否被发送。例如,使用 RSpec:

it "delivers notification" do
  expect { subject }.to have_delivered_to(Community::EventsDelivery, :modified, event)
end

典型生态项目

Abstract Notifier

Abstract Notifier 是 Active Delivery 的配套项目,用于创建自定义通知器。它提供了一个抽象层,使得你可以轻松地添加新的通知类型,如 SMS、Webhook 等。

Active Job

Active Job 是 Rails 的一个组件,用于处理后台任务。Active Delivery 可以与 Active Job 集成,使得通知可以异步发送,提高应用的性能和响应速度。

通过以上步骤和示例,你可以快速上手并有效地使用 Active Delivery 来管理你的应用中的各种通知。

登录后查看全文
热门项目推荐