"do" magic keyword option

wingyplus

Thanabodee Charoenpiriyakij

Posted on November 30, 2020

"do" magic keyword option

สิ่งมหัศจรรย์ของ Elixir คือ เราใช้ Keyword ที่มี key ชื่อ do เพื่อทำ do block ใน DSL ได้ เช่น

defmodule SoLazy do
  defmacro resources(path, do: nested_context) do
    quote do
      IO.puts("Print #{unquote(path)}")
      unquote(nested_context)
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

ก็จะทำให้เราเรียกแบบนี้ได้

$ iex
Erlang/OTP 23 [erts-11.1.3] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] [hipe] [dtrace]

Interactive Elixir (1.11.1) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> require SoLazy
SoLazy
iex(2)> SoLazy.resources "/myapi" do
...(2)>   IO.puts "nested context"
...(2)> end
Print /myapi
nested context
:ok
Enter fullscreen mode Exit fullscreen mode

จบ...

💖 💪 🙅 🚩
wingyplus
Thanabodee Charoenpiriyakij

Posted on November 30, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related