如何同时确定多个模块? (宏尝试不起作用)

时间:2016-10-25 16:02:30

标签: elixir

我需要所有模型来实现特定的协议。我当前的尝试是RequestAPI.post(postString: postString, url: "https://www.someurl.com") { (succeeded: Bool, msg: String, responceData:AnyObject) -> () in if(succeeded) { print(items: "User logged in. Registration is done.") // Move to the UI thread DispatchQueue.main.async (execute: { () -> Void in //Set User's logged in Util.set_IsUserLoggedIn(state: true) Util.set_UserData(userData: responceData) self.appDelegate.createMenuView() }) } else { // Move to the UI thread DispatchQueue.main.async (execute: { () -> Void in let alertcontroller = UIAlertController(title: JJS_MESSAGE, message: msg, preferredStyle: UIAlertControllerStyle.alert) alertcontroller.title = "No Internet" alertcontroller.message = FAILURE_MESSAGE self.present(alertcontroller, animated: true, completion: nil) }) } } 模块,其中定义了此宏:

MyApp.Convert

错误:

defmodule ConvertMacro do
  @moduledoc """
  All model structs need to implement the convert interface and must be added
  here.
  """

  defmacro defimpl_convert_for(modules) do
    Enum.map(modules, fn module ->
      quote do
        defimpl Units.Convert, for: unquote(module) do
          require Units

          def to_standard_metric(struct) do
            Units.to_standard_metric_for_struct(unquote(module), struct)
          end

          def to_user_data(struct) do
            Units.to_user_data_for_struct(unquote(module), struct)
          end
        end
      end
    end)
  end
end

ConvertMacto.defimpl_convert_for([MyApp.User, MyApp.Block])

(错误信息实际上有点多余)

有没有办法实现我想要做的事情,或者我只需要全部输入?

1 个答案:

答案 0 :(得分:4)

它实际上要简单得多,因为defimpl原生支持它:

defimpl FooProtocol, for: [Foo, Baz, Bar] do
  def protocol_function(x, y, z) do
    @for.some_function(x, y, z)
  end
end

@for模块属性允许您访问为其实现协议的模块。您可以在此处查看示例:https://github.com/elixir-ecto/ecto/blob/master/lib/ecto/date_time.ex#L650-L662