Skip to content

Instantly share code, notes, and snippets.

@seaneshbaugh
Last active August 29, 2015 14:20
Show Gist options
  • Select an option

  • Save seaneshbaugh/a9deab5d33ec750aeb42 to your computer and use it in GitHub Desktop.

Select an option

Save seaneshbaugh/a9deab5d33ec750aeb42 to your computer and use it in GitHub Desktop.
defmodule Post do
defstruct [:id, :title, :body]
end
defmodule Exseed do
defmacro seed(model, do: block) do
quote do
var!(attributes, Exseed) = %{}
unquote(Macro.postwalk(block, &postwalk(&1, model)))
struct(unquote(model), var!(attributes, Exseed))
end
end
defmacro attr(attribute, value) do
quote do
var!(attributes, Exseed) = Dict.put(var!(attributes, Exseed), unquote(attribute), unquote(value))
end
end
def postwalk({attribute, _meta, [value]} = ast, {_, _, [model]}) do
attributes = struct(Module.concat([model]), %{}) |> Map.keys |> Enum.reject(fn key -> key in [:__meta__, :__struct__] end)
if attribute in attributes do
quote do
attr(unquote(attribute), unquote(value))
end
else
ast
end
end
def postwalk(ast, _model) do
ast
end
end
defmodule ExseedTest do
import Exseed
def test do
attributes = "hello"
seed Post do
id 1
title "LOL"
body_1 = "RO"
body_2 = "FL"
body body_1 <> body_2
IO.puts "1234"
end |> IO.inspect
IO.inspect attributes
end
end
ExseedTest.test
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment