3

バックグラウンドで Wisper pub/sub を使用する単純な POST Grape エンドポイントがあります。

module Something
  class Doit < Grape::API
    post :now do
      service = SomePub.new
      service.subscribe(SomeSub.new)
      service.call(params)
    end
  end
end

実際に計算が行われるSomeSub場所は次のとおりです。

class SomeSub
  def do_calculations(payload)
     {result: "42"}.to_json
  end
end

SomePubも簡単です:

class SomePub
  include Wisper::Publisher

  def call(payload)
    broadcast(:do_calculations, payload)
  end
end

したがって{result: "42"}、Grape のpost :nowエンドポイントを呼び出すときに JSON で応答する必要があります。

残念ながら、この方法では機能しません。私が持っているものは次のとおりです。

{"local_registrations":[{"listener":{},"on":{},"with":null,"prefix":"","allowed_classes":[],"broadcaster":{}}]}

Wisper の wiki の例はあまり役に立ちません ( https://github.com/krisleech/wisper/wiki/Grape )

SomePub#do_calculationsGrape のエンドポイント呼び出しの結果として、実際に結果を渡す方法はありますか?

4

1 に答える 1

3

PubSub パターンのポイントは、Publisher がサブスクライバーをまったく認識していないことです。あなたが達成しようとしているのは、サブスクライバーの結果をパブリッシャーに戻すことです。これはすべてのアイデアに反しています。

ただし、できることは、サブスクライバーもパブリッシャーにして、別のサブスクライバーで応答を収集することです。

手元に Grape がインストールされていないため、これはサンプル コードであることに注意してください (ただし、動作することを願っています)。

class ResponseListener
  attr_reader :response

  def initialize
    @response = {}
  end

  def collect_response(item)
    @response.merge!(item) # customize as you wish
  end
end

class SomeSub
  include Wisper::Publisher

  def do_calculations(payload)
     broadcast(:collect_response, result: "42")
  end
end

module Something
  class Doit < Grape::API
    post :now do
      response_listener = ResponseListener.new
      # globally subscribe response_listener to all events it can respond to
      Wisper.subscribe(response_listener) 

      service = SomePub.new
      service.subscribe(SomeSub.new)
      service.call(params)

      response_listener.response.to_json # render collected response
    end
  end
end
于 2015-09-16T20:18:58.180 に答える