Skip to content

Instantly share code, notes, and snippets.

@benjamintanweihao
Last active July 14, 2016 08:24
Show Gist options
  • Select an option

  • Save benjamintanweihao/fd9a2d0e2ca15163ea7448751d312202 to your computer and use it in GitHub Desktop.

Select an option

Save benjamintanweihao/fd9a2d0e2ca15163ea7448751d312202 to your computer and use it in GitHub Desktop.
Second attempt. This one works.
defmodule Html do
defmacro markup(do: inner) do
quote do
{:ok, var!(buffer, Html)} = start_buffer
unquote(inner)
result = get_buffer(var!(buffer, Html))
stop_buffer(var!(buffer, Html))
result
end
end
defmacro tag(name, do: inner) do
quote do
put_buffer(var!(buffer, Html), "<#{unquote(name)}>")
unquote(inner)
put_buffer(var!(buffer, Html), "</#{unquote(name)}>")
end
end
defmacro text(text) do
quote do
put_buffer(var!(buffer, Html), unquote(text))
end
end
def start_buffer do
Agent.start_link(fn -> [] end)
end
def put_buffer(pid, buffer) do
Agent.update(pid, &[buffer|&1])
end
def get_buffer(pid) do
Agent.get(pid, &(&1)) |> Enum.reverse |> Enum.join
end
def stop_buffer(pid) do
Agent.stop(pid)
end
end
defmodule Foo do
import Html
m = markup do
tag :div do
tag :h1 do
text "OHAI"
end
tag :article do
tag :h2 do
text "KTHXBAI"
end
end
end
end
IO.puts "===================="
IO.inspect m
IO.puts "===================="
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment