# 从 Hanami 发送实时事件

> 把 pusher gem 注册为 Hanami 2 provider，从 action 和 operation 发送 Hibira 事件，并在 action 中签署频道订阅。

Source: https://hibira.io/zh-cn/guides/hanami

把 pusher gem 注册为 Hanami 2 provider，从 action 和 operation 发送 Hibira 事件，并在 action 中签署频道订阅。

Package: pusher

- provider 注册一个 client，action 和 operation 通过 Deps 获取。
- 由 action 为 pusher-js 和 Laravel Echo 签署私有和 presence 频道。

## 1. 安装

```shell
bundle add pusher
```

## 2. 配置

```ruby
# config/providers/hibira.rb
Hanami.app.register_provider(:hibira) do
  prepare { require "pusher" }
  start do
    register "hibira", Pusher::Client.new(
      app_id: target["settings"].hibira_app_id, key: target["settings"].hibira_app_key,
      secret: target["settings"].hibira_app_secret, host: "ws.hibira.io", port: 443, use_tls: true
    )
  end
end

# config/settings.rb: setting :hibira_app_id, setting :hibira_app_key, setting :hibira_app_secret
```

## 3. 使用

```ruby
# app/actions/pusher/auth.rb (config/routes.rb: post "/pusher/auth", to: "pusher.auth")
module Bookshelf
  module Actions
    module Pusher
      class Auth < Bookshelf::Action
        include Deps["hibira"]

        def handle(request, response)
          # check the signed-in user may join request.params[:channel_name] first
          response.format = :json
          response.body = hibira.authenticate(request.params[:channel_name], request.params[:socket_id]).to_json
        end
      end
    end
  end
end

# anywhere: hibira.trigger("orders", "order.shipped", { id: 1042 })
```

## 开始之前

- 应用密钥只会在创建应用或轮换密钥时显示一次。请只放在服务器上，不要放进浏览器或游戏的构建包。
- Free 套餐需要把页面加载的每个来源都加入应用的“允许的来源”（开发时是 http://localhost:3000，之后是您的域名）。"*" 需要付费套餐。

- [RubyGems](https://rubygems.org/gems/pusher)
