Current section
Files
Jump to
Current section
Files
lib/grimoire/defaults/templates/struct.ex
defmodule Grimoire.Defaults.Templates.Structs do
# Call in cb with Itr.tables
def struct(config, {tablekey, table}) do
app_name = Macro.camelize(config.app_name)
ctx = Macro.camelize(table.__meta__.domain)
module =
tablekey
|> Atom.to_string
|> Macro.camelize
"""
defmodule #{app_name}.#{ctx}.#{module} do
use Ecto.Schema
import Ecto.Changeset
schema \"#{tablekey}\" do
#{Grimoire.Render.Lists.render_columns(config, tablekey, :default_struct_fields)}
end
def changeset(#{tablekey}, params \\\\ %{}) do
#{tablekey}
|> cast(params, [])
end
end
"""
|> Grimoire.Utilities.Strings.indent
end
def struct_fields(config, {ck, c}) do
foreign = if Map.has_key?(c, :fk), do: full_mod_name(config, c.fk), else: ""
join = if Map.has_key?(c, :join_through), do: full_mod_name(config, c.join_through), else: ""
default = case c.t do
:has_one -> "has_one :#{ck}, #{foreign}"
:belongs_to -> "belongs_to :#{ck}, #{foreign}"
:many_to_many -> "many_to_many :#{ck}, #{foreign}, join_through: #{join}"
_ -> "field :#{ck}"
end
if Map.has_key?(c, :struct) do
Enum.reduce(c.struct, [default], fn
({k, v}, acc) when is_boolean(v) -> ["#{k}: #{v}" | acc]
({k, v}, acc) when is_atom(v) -> ["#{k}: :#{v}" | acc]
({k, v}, acc) when is_binary(v) -> ["#{k}: \"#{v}\"" | acc]
({k, v}, acc) -> ["#{k}: #{v}" | acc]
end)
|> Enum.reverse
|> Enum.join(", ")
else
default
end
end
def full_mod_name(config, tk) do
app_name = config.app_name |> Macro.camelize
domain = config.current_schema[tk].__meta__.domain |> Macro.camelize
table = tk |> to_string |> Macro.camelize
"#{app_name}.#{domain}.#{table}"
end
end