错误 - 在elixir中实现协议

时间:2016-03-17 12:46:23

标签: elixir

我正在运行以下代码:

ExHubic.Request.request({:get, "/account", nil, :hubic}, ExHubic)   

并收到以下错误:

** (Protocol.UndefinedError) protocol ExHubic.Request not implemented for {:get, "/account", nil, :hubic}
    (ex_hubic) lib/request.ex:1: ExHubic.Request.impl_for!/1
    (ex_hubic) lib/request.ex:6: ExHubic.Request.request/2

此错误消息向我建议该协议未针对ExHubic.Query.Hubic.t类型实施,该类型定义为@type t :: {atom, String.t, any, :hubic}

这可能是我创建的类型的问题,但我看不到它。

某些背景信息:

defprotocol ExHubic.Request do
  @moduledoc false
  @spec request(query :: ExHubic.Query.t, client :: atom)
                :: ExHubic.Query.http_query_t
  def request(query, client)
end

defimpl ExHubic.Request, for:  ExHubic.Query.Hubic  do
  @spec request(query :: ExHubic.Query.Hubic.t, client :: atom)
                :: {:ok, ExHubic.Client.response_t} | {:error, ExHubic.Client.response_t}
  def request({method, uri, params, :hubic} = query, client) do
     implementation_details
  end
end

defmodule ExHubic.Query do
  @moduledoc false
  @type t ::  {atom, String.t, any, atom}
end

defmodule ExHubic.Query.Hubic do
  @type t :: {atom, String.t, any, :hubic}
  @spec account() :: __MODULE__.t
  def account(), do: {:get, "/account", :nil, :hubic}
end

1 个答案:

答案 0 :(得分:3)

这里有几个问题,首先,您正在使用协议的原子(模块名称)。您需要使用内置类型或结构,如http://elixir-lang.org/getting-started/protocols.html#protocols-and-structs中所述。这意味着向模块添加defstruct:

defmodule ExHubic.Query.Hubic do
  defstruct [:method, :uri, :params,  service: :hubic]
  @type t :: %__MODULE__{method: atom, uri: String.t, params: any, service: :hubic}
  def account(), do: {:get, "/account", :nil, :hubic}
end

defprotocol ExHubic.Request do
  def request(query, client)
end


defimpl ExHubic.Request, for:  ExHubic.Query.Hubic  do

  @spec request(Query.t, atom) :: any
  def request(query, client) do
    IO.inspect query
  end
end

然后您可以将其用于:

ExHubic.Request.request(%ExHubic.Query.Hubic{method: :get, params: nil, service: :hubic, uri: "/account"}, client)