DEV Community

Thanabodee Charoenpiriyakij
Thanabodee Charoenpiriyakij

Posted on

2 2

"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

จบ...

Top comments (1)

Collapse
 
iporsut profile image
Weerasak Chongnguluam

และ oneline แบบนี้ได้เลย SoLazy.resources "/myapi", do: IO.puts "nested context"

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay