2016-03-17 51 views
0

我运行下面的代码实现协议:错误 - 在灵药

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 

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

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

一些背景:

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 

回答

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) 
+0

我碰到了我以前的尝试的问题。你的答案可能是正确的答案,但我还没有能够成功实现这一点。我不会在电脑桌上呆几周。关于元组不允许的一点是绝对正确的,并且使我走上了正确的道路。但是我还不确定查询或客户端应该是第一个参数。当我回到办公桌时,我需要进一步调查。谢谢。 –

+0

将元组更改为修复它的结构。为参考目的:文件:[查询](https://github.com/stephenmoloney/ex_hubic/blob/master/lib/query/hubic.ex),[协议](https://github.com/stephenmoloney/ex_hubic /blob/master/lib/request.ex),[Protocol Impl](https://github.com/stephenmoloney/ex_hubic/blob/master/lib/request/hubic/request.ex) –