Skip to content

Instantly share code, notes, and snippets.

@pikender
Last active Apr 11, 2016
Embed
What would you like to do?
Ecto Model Schema Extension
defmodule Nectar.ModelExtension do
defmacro __using__(_opts) do
quote do
Module.register_attribute(__MODULE__, :schema_changes, accumulate: true)
import Nectar.ModelExtension, only: [add_to_schema: 1]
end
end
defmacro add_to_schema([do: block]) do
schema_change = Macro.escape(block)
quote bind_quoted: [schema_change: schema_change] do
Module.put_attribute(__MODULE__, :schema_changes, schema_change)
end
end
end
defmodule Nectar.ExtendProduct do
use Nectar.ModelExtension
add_to_schema do: (field :special, :boolean, virtual: true)
defmacro extensions do
@schema_changes
end
end
defmodule Nectar.Product do
import Nectar.ExtendProduct
schema do
extensions
end
## Add #special boolean to get casted
def changeset(model, params \\ :empty) do
model
|> cast(params, @required_fields, ~w(special))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment