Skip to content

Instantly share code, notes, and snippets.

@mikalv
Forked from rcdilorenzo/macro_fun.exs
Created January 16, 2020 03:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikalv/2ecb1795faa36035a317fe4618469d27 to your computer and use it in GitHub Desktop.
Save mikalv/2ecb1795faa36035a317fe4618469d27 to your computer and use it in GitHub Desktop.
Macro fun in Elixir mimicking Ruby's attr_accessor
defmodule MacroExp do
defmacro attr_accessor(atom) do
getter = String.to_atom("get_#{atom}")
setter = String.to_atom("set_#{atom}")
quote do
def unquote(getter)(data) do
data |> Map.from_struct |> Map.get(unquote(atom))
end
def unquote(setter)(data, value) do
data |> Map.put(unquote(atom), value)
end
end
end
defmacro attr_reader(atom) do
getter = String.to_atom("get_#{atom}")
quote do
def unquote(getter)(data) do
data |> Map.from_struct |> Map.get(unquote(atom))
end
end
end
end
defmodule Calculation do
import MacroExp
defstruct first: nil, second: nil, operator: :plus
attr_accessor :first # defines set_first/2 and get_first/1
attr_accessor :second # defines set_second/2 and get_second/1
attr_reader :operator # defines set_operator/2 and get_operator/1
def result(%Calculation{first: first, second: second, operator: :plus}) do
first + second
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment