In order to make it closer to what @Flo0807 envisioned, I have changed my packageβs functionality slightly to use my new CodeGen
library, which is actually great for cases such as these, where you want automatic code generation, butr in which you want to minimize the actual amount of code in your project.
First, build the common LiveResource module for you application which encapsulates database and layout information (not that if you want two different layouts you can just define two of these modules and use them in the appropriate places):
defmodule MyAppWeb.LiveResource do
use BackpexAuto.EctoLiveResource,
repo: MyApp.Repo,
layout: {MyAppWeb.Layouts, :admin},
pubsub: MyApp.PubSub
end
This has now created a βmeta-moduleβ which you will use to create the live resource modules, BUT not, instead of using, youβll be using CodeGen from my CodeGen library:
defmodule MyAppWeb.MyContext.CountryLive do
use CodeGen,
module: MyAppWeb.LiveResource,
options: [
resource: MyApp.MyContext.Patient
]
end
The above is very similar to calling use MyAppWeb.LiveResource, ...
, except a bit more verbose. However, it has the advantage that the generated AST is divided into blocks, which you can inspect in IEx and dump the source code of some of the blocks into your actual module.
iex(2)> CodeGen.block_names(MyAppWeb.MyContext.CountryLive)
["auto_live_resource:changesets", "auto_live_resource:names",
"auto_live_resource:fields"]
iex(5)> CodeGen.show_block(MyAppWeb.MyContext.CountryLive, "auto_live_resource:fields")
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Block: auto_live_resource:fields
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β @impl Backpex.LiveResource
β def fields do
β [
β name: %{label: "Name", module: Backpex.Fields.Text},
β inserted_at: %{
β except: [:new],
β format: "%Y-%m-%d %H:%M:%S",
β label: "Inserted at",
β module: Backpex.Fields.DateTime,
β readonly: true
β },
β updated_at: %{
β except: [:new],
β format: "%Y-%m-%d %H:%M:%S",
β label: "Updated at",
β module: Backpex.Fields.DateTime,
β readonly: true
β }
β ]
β end
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
iex(4)> CodeGen.dump_source(MyAppWeb.MyContext.CountryLive, "auto_live_resource:fields")
After dumping the source, the block is added to the module:
defmodule MyAppWeb.MyContext.CountryLive do
use CodeGen,
module: MyAppWeb.LiveResource,
options: [
resource: MyApp.MyContext.Country
]
@impl Backpex.LiveResource
def fields do
[
name: %{label: "Name", module: Backpex.Fields.Text},
inserted_at: %{
except: [:new],
format: "%Y-%m-%d %H:%M:%S",
label: "Inserted at",
module: Backpex.Fields.DateTime,
readonly: true
},
updated_at: %{
except: [:new],
format: "%Y-%m-%d %H:%M:%S",
label: "Updated at",
module: Backpex.Fields.DateTime,
readonly: true
}
]
end
end