Phoenix generators for layout and html resource

This commit is contained in:
Mitchell Hanberg 2019-07-01 22:14:32 -04:00
parent 05b11b4bf5
commit dbf8dce765
11 changed files with 526 additions and 0 deletions

View file

@ -0,0 +1,225 @@
defmodule Mix.Tasks.Dsl.Gen.Html do
@shortdoc "Generates controller, views, and context for an HTML resource in Dsl"
@moduledoc """
Generates controller, views, and context for an HTML resource Dsl.
mix dsl.gen.html Accounts User users name:string age:integer
The first argument is the context module followed by the schema module
and its plural name (used as the schema table name).
The context is an Elixir module that serves as an API boundary for
the given resource. A context often holds many related resources.
Therefore, if the context already exists, it will be augmented with
functions for the given resource.
> Note: A resource may also be split
> over distinct contexts (such as `Accounts.User` and `Payments.User`).
The schema is responsible for mapping the database fields into an
Elixir struct.
Overall, this generator will add the following files to `lib/`:
* a context module in `lib/app/accounts.ex` for the accounts API
* a schema in `lib/app/accounts/user.ex`, with an `users` table
* a view in `lib/app_web/views/user_view.ex`
* a controller in `lib/app_web/controllers/user_controller.ex`
* default CRUD templates in `lib/app_web/templates/user`
A migration file for the repository and test files for the context and
controller features will also be generated.
The location of the web files (controllers, views, templates, etc) in an
umbrella application will vary based on the `:context_app` config located
in your applications `:generators` configuration. When set, the Phoenix
generators will generate web files directly in your lib and test folders
since the application is assumed to be isolated to web specific functionality.
If `:context_app` is not set, the generators will place web related lib
and test files in a `web/` directory since the application is assumed
to be handling both web and domain specific functionality.
Example configuration:
config :my_app_web, :generators, context_app: :my_app
Alternatively, the `--context-app` option may be supplied to the generator:
mix phx.gen.html Sales User users --context-app warehouse
## Web namespace
By default, the controller and view will be namespaced by the schema name.
You can customize the web module namespace by passing the `--web` flag with a
module name, for example:
mix phx.gen.html.dsl Sales User users --web Sales
Which would generate a `lib/app_web/controllers/sales/user_controller.ex` and
`lib/app_web/views/sales/user_view.ex`.
## Generating without a schema or context file
In some cases, you may wish to bootstrap HTML templates, controllers, and
controller tests, but leave internal implementation of the context or schema
to yourself. You can use the `--no-context` and `--no-schema` flags for
file generation control.
## table
By default, the table name for the migration and schema will be
the plural name provided for the resource. To customize this value,
a `--table` option may be provided. For example:
mix phx.gen.html.dsl Accounts User users --table cms_users
## binary_id
Generated migration can use `binary_id` for schema's primary key
and its references with option `--binary-id`.
## Default options
This generator uses default options provided in the `:generators`
configuration of your application. These are the defaults:
config :your_app, :generators,
migration: true,
binary_id: false,
sample_binary_id: "11111111-1111-1111-1111-111111111111"
You can override those options per invocation by providing corresponding
switches, e.g. `--no-binary-id` to use normal ids despite the default
configuration or `--migration` to force generation of the migration.
Read the documentation for `phx.gen.schema` for more information on
attributes.
"""
use Mix.Task
alias Mix.Phoenix.{Context, Schema}
alias Mix.Tasks.Phx.Gen
@doc false
def run(args) do
if Mix.Project.umbrella? do
Mix.raise "mix dsl.gen.html can only be run inside an application directory"
end
{context, schema} = Gen.Context.build(args)
Gen.Context.prompt_for_code_injection(context)
binding = [context: context, schema: schema, inputs: inputs(schema)]
paths = [".", :dsl]
prompt_for_conflicts(context)
context
|> copy_new_files(paths, binding)
|> print_shell_instructions()
end
defp prompt_for_conflicts(context) do
context
|> files_to_be_generated()
|> Kernel.++(context_files(context))
|> Mix.Phoenix.prompt_for_conflicts()
end
defp context_files(%Context{generate?: true} = context) do
Gen.Context.files_to_be_generated(context)
end
defp context_files(%Context{generate?: false}) do
[]
end
@doc false
def files_to_be_generated(%Context{schema: schema, context_app: context_app}) do
web_prefix = Mix.Phoenix.web_path(context_app)
test_prefix = Mix.Phoenix.web_test_path(context_app)
web_path = to_string(schema.web_path)
[
{:eex, "controller.ex", Path.join([web_prefix, "controllers", web_path, "#{schema.singular}_controller.ex"])},
{:eex, "edit.html.exs", Path.join([web_prefix, "templates", web_path, schema.singular, "edit.html.exs"])},
{:eex, "form.html.exs", Path.join([web_prefix, "templates", web_path, schema.singular, "form.html.exs"])},
{:eex, "index.html.exs", Path.join([web_prefix, "templates", web_path, schema.singular, "index.html.exs"])},
{:eex, "new.html.exs", Path.join([web_prefix, "templates", web_path, schema.singular, "new.html.exs"])},
{:eex, "show.html.exs", Path.join([web_prefix, "templates", web_path, schema.singular, "show.html.exs"])},
{:eex, "view.ex", Path.join([web_prefix, "views", web_path, "#{schema.singular}_view.ex"])},
{:eex, "controller_test.exs", Path.join([test_prefix, "controllers", web_path, "#{schema.singular}_controller_test.exs"])},
]
end
@doc false
def copy_new_files(%Context{} = context, paths, binding) do
files = files_to_be_generated(context)
IO.inspect files, label: "files"
Mix.Phoenix.copy_from(paths, "priv/templates/dsl.gen.html", binding, files)
if context.generate?, do: Gen.Context.copy_new_files(context, Mix.Phoenix.generator_paths(), binding)
context
end
@doc false
def print_shell_instructions(%Context{schema: schema, context_app: ctx_app} = context) do
if schema.web_namespace do
Mix.shell.info """
Add the resource to your #{schema.web_namespace} :browser scope in #{Mix.Phoenix.web_path(ctx_app)}/router.ex:
scope "/#{schema.web_path}", #{inspect Module.concat(context.web_module, schema.web_namespace)}, as: :#{schema.web_path} do
pipe_through :browser
...
resources "/#{schema.plural}", #{inspect schema.alias}Controller
end
"""
else
Mix.shell.info """
Add the resource to your browser scope in #{Mix.Phoenix.web_path(ctx_app)}/router.ex:
resources "/#{schema.plural}", #{inspect schema.alias}Controller
"""
end
if context.generate?, do: Gen.Context.print_shell_instructions(context)
end
defp inputs(%Schema{} = schema) do
Enum.map(schema.attrs, fn
{_, {:references, _}} ->
{nil, nil, nil}
{key, :integer} ->
{label(key), ~s(number_input form, #{inspect(key)}), error(key)}
{key, :float} ->
{label(key), ~s(number_input form, #{inspect(key)}, step: "any"), error(key)}
{key, :decimal} ->
{label(key), ~s(number_input form, #{inspect(key)}, step: "any"), error(key)}
{key, :boolean} ->
{label(key), ~s(checkbox form, #{inspect(key)}), error(key)}
{key, :text} ->
{label(key), ~s(textarea form, #{inspect(key)}), error(key)}
{key, :date} ->
{label(key), ~s(date_select form, #{inspect(key)}), error(key)}
{key, :time} ->
{label(key), ~s(time_select form, #{inspect(key)}), error(key)}
{key, :utc_datetime} ->
{label(key), ~s(datetime_select form, #{inspect(key)}), error(key)}
{key, :naive_datetime} ->
{label(key), ~s(datetime_select form, #{inspect(key)}), error(key)}
{key, {:array, :integer}} ->
{label(key), ~s(multiple_select form, #{inspect(key)}, ["1": 1, "2": 2]), error(key)}
{key, {:array, _}} ->
{label(key), ~s(multiple_select form, #{inspect(key)}, ["Option 1": "option1", "Option 2": "option2"]), error(key)}
{key, _} ->
{label(key), ~s(text_input form, #{inspect(key)}), error(key)}
end)
end
defp label(key) do
~s(phx_label form, #{inspect(key)})
end
defp error(field) do
~s{partial error_tag(form, #{inspect(field)})}
end
end

View file

@ -0,0 +1,29 @@
defmodule Mix.Tasks.Dsl.Gen.Layout do
use Mix.Task
@shortdoc "Generates a default Phoenix layout file in Dsl"
@moduledoc """
Generates a Phoenix layout file in Dsl.
mix dsl.gen.layout
"""
def run(_args) do
context_app = Mix.Phoenix.context_app()
web_prefix = Mix.Phoenix.web_path(context_app)
binding = [application_module: Mix.Phoenix.base()]
Mix.Phoenix.copy_from(dsl_paths(), "priv/templates/dsl.gen.layout", binding, [
{:eex, "app.html.eex", "#{web_prefix}/templates/layout/app.html.exs"}
])
instructions = """
A new #{web_prefix}/templates/layout/app.html.exs file was generated.
"""
Mix.shell().info(instructions)
end
defp dsl_paths do
[".", :dsl]
end
end

View file

@ -0,0 +1,62 @@
defmodule <%= inspect context.web_module %>.<%= inspect Module.concat(schema.web_namespace, schema.alias) %>Controller do
use <%= inspect context.web_module %>, :controller
alias <%= inspect context.module %>
alias <%= inspect schema.module %>
def index(conn, _params) do
<%= schema.plural %> = <%= inspect context.alias %>.list_<%= schema.plural %>()
render(conn, "index.html", <%= schema.plural %>: <%= schema.plural %>)
end
def new(conn, _params) do
changeset = <%= inspect context.alias %>.change_<%= schema.singular %>(%<%= inspect schema.alias %>{})
render(conn, "new.html", changeset: changeset)
end
def create(conn, %{<%= inspect schema.singular %> => <%= schema.singular %>_params}) do
case <%= inspect context.alias %>.create_<%= schema.singular %>(<%= schema.singular %>_params) do
{:ok, <%= schema.singular %>} ->
conn
|> put_flash(:info, "<%= schema.human_singular %> created successfully.")
|> redirect(to: Routes.<%= schema.route_helper %>_path(conn, :show, <%= schema.singular %>))
{:error, %Ecto.Changeset{} = changeset} ->
render(conn, "new.html", changeset: changeset)
end
end
def show(conn, %{"id" => id}) do
<%= schema.singular %> = <%= inspect context.alias %>.get_<%= schema.singular %>!(id)
render(conn, "show.html", <%= schema.singular %>: <%= schema.singular %>)
end
def edit(conn, %{"id" => id}) do
<%= schema.singular %> = <%= inspect context.alias %>.get_<%= schema.singular %>!(id)
changeset = <%= inspect context.alias %>.change_<%= schema.singular %>(<%= schema.singular %>)
render(conn, "edit.html", <%= schema.singular %>: <%= schema.singular %>, changeset: changeset)
end
def update(conn, %{"id" => id, <%= inspect schema.singular %> => <%= schema.singular %>_params}) do
<%= schema.singular %> = <%= inspect context.alias %>.get_<%= schema.singular %>!(id)
case <%= inspect context.alias %>.update_<%= schema.singular %>(<%= schema.singular %>, <%= schema.singular %>_params) do
{:ok, <%= schema.singular %>} ->
conn
|> put_flash(:info, "<%= schema.human_singular %> updated successfully.")
|> redirect(to: Routes.<%= schema.route_helper %>_path(conn, :show, <%= schema.singular %>))
{:error, %Ecto.Changeset{} = changeset} ->
render(conn, "edit.html", <%= schema.singular %>: <%= schema.singular %>, changeset: changeset)
end
end
def delete(conn, %{"id" => id}) do
<%= schema.singular %> = <%= inspect context.alias %>.get_<%= schema.singular %>!(id)
{:ok, _<%= schema.singular %>} = <%= inspect context.alias %>.delete_<%= schema.singular %>(<%= schema.singular %>)
conn
|> put_flash(:info, "<%= schema.human_singular %> deleted successfully.")
|> redirect(to: Routes.<%= schema.route_helper %>_path(conn, :index))
end
end

View file

@ -0,0 +1,89 @@
defmodule <%= inspect context.web_module %>.<%= inspect Module.concat(schema.web_namespace, schema.alias) %>ControllerTest do
use <%= inspect context.web_module %>.ConnCase
alias <%= inspect context.module %>
@create_attrs <%= inspect schema.params.create %>
@update_attrs <%= inspect schema.params.update %>
@invalid_attrs <%= inspect for {key, _} <- schema.params.create, into: %{}, do: {key, nil} %>
def fixture(:<%= schema.singular %>) do
{:ok, <%= schema.singular %>} = <%= inspect context.alias %>.create_<%= schema.singular %>(@create_attrs)
<%= schema.singular %>
end
describe "index" do
test "lists all <%= schema.plural %>", %{conn: conn} do
conn = get(conn, Routes.<%= schema.route_helper %>_path(conn, :index))
assert html_response(conn, 200) =~ "Listing <%= schema.human_plural %>"
end
end
describe "new <%= schema.singular %>" do
test "renders form", %{conn: conn} do
conn = get(conn, Routes.<%= schema.route_helper %>_path(conn, :new))
assert html_response(conn, 200) =~ "New <%= schema.human_singular %>"
end
end
describe "create <%= schema.singular %>" do
test "redirects to show when data is valid", %{conn: conn} do
conn = post(conn, Routes.<%= schema.route_helper %>_path(conn, :create), <%= schema.singular %>: @create_attrs)
assert %{id: id} = redirected_params(conn)
assert redirected_to(conn) == Routes.<%= schema.route_helper %>_path(conn, :show, id)
conn = get(conn, Routes.<%= schema.route_helper %>_path(conn, :show, id))
assert html_response(conn, 200) =~ "Show <%= schema.human_singular %>"
end
test "renders errors when data is invalid", %{conn: conn} do
conn = post(conn, Routes.<%= schema.route_helper %>_path(conn, :create), <%= schema.singular %>: @invalid_attrs)
assert html_response(conn, 200) =~ "New <%= schema.human_singular %>"
end
end
describe "edit <%= schema.singular %>" do
setup [:create_<%= schema.singular %>]
test "renders form for editing chosen <%= schema.singular %>", %{conn: conn, <%= schema.singular %>: <%= schema.singular %>} do
conn = get(conn, Routes.<%= schema.route_helper %>_path(conn, :edit, <%= schema.singular %>))
assert html_response(conn, 200) =~ "Edit <%= schema.human_singular %>"
end
end
describe "update <%= schema.singular %>" do
setup [:create_<%= schema.singular %>]
test "redirects when data is valid", %{conn: conn, <%= schema.singular %>: <%= schema.singular %>} do
conn = put(conn, Routes.<%= schema.route_helper %>_path(conn, :update, <%= schema.singular %>), <%= schema.singular %>: @update_attrs)
assert redirected_to(conn) == Routes.<%= schema.route_helper %>_path(conn, :show, <%= schema.singular %>)
conn = get(conn, Routes.<%= schema.route_helper %>_path(conn, :show, <%= schema.singular %>))<%= if schema.string_attr do %>
assert html_response(conn, 200) =~ <%= inspect Mix.Phoenix.Schema.default_param(schema, :update) %><% else %>
assert html_response(conn, 200)<% end %>
end
test "renders errors when data is invalid", %{conn: conn, <%= schema.singular %>: <%= schema.singular %>} do
conn = put(conn, Routes.<%= schema.route_helper %>_path(conn, :update, <%= schema.singular %>), <%= schema.singular %>: @invalid_attrs)
assert html_response(conn, 200) =~ "Edit <%= schema.human_singular %>"
end
end
describe "delete <%= schema.singular %>" do
setup [:create_<%= schema.singular %>]
test "deletes chosen <%= schema.singular %>", %{conn: conn, <%= schema.singular %>: <%= schema.singular %>} do
conn = delete(conn, Routes.<%= schema.route_helper %>_path(conn, :delete, <%= schema.singular %>))
assert redirected_to(conn) == Routes.<%= schema.route_helper %>_path(conn, :index)
assert_error_sent 404, fn ->
get(conn, Routes.<%= schema.route_helper %>_path(conn, :show, <%= schema.singular %>))
end
end
end
defp create_<%= schema.singular %>(_) do
<%= schema.singular %> = fixture(:<%= schema.singular %>)
{:ok, <%= schema.singular %>: <%= schema.singular %>}
end
end

View file

@ -0,0 +1,13 @@
h1 "Edit <%= schema.human_singular %>"
partial render("form.html",
Map.put(
assigns,
:action,
Routes.<%= schema.route_helper %>_path(@conn, :update, @<%= schema.singular %>)
)
)
span do
phx_link "Back", to: Routes.<%= schema.route_helper %>_path(@conn, :index)
end

View file

@ -0,0 +1,13 @@
form_for @changeset, @action do
if @changeset.action do
div class: "alert alert-danger" do
p "Oops, something went wrong! Please check the errors below."
end
end <%= for {label, input, error} <- inputs, input do %>
<%= label %>
<%= input %>
<%= error %> <% end %>
div do
submit "Save"
end
end

View file

@ -0,0 +1,27 @@
h1 "Listing <%= schema.human_plural %>"
table do
thead do
tr do <%= for {k, _} <- schema.attrs do %>
th "<%= Phoenix.Naming.humanize(Atom.to_string(k)) %>"<% end %>
th()
end
tbody do
for <%= schema.singular %> <- @<%= schema.plural %> do
tr do <%= for {k, _} <- schema.attrs do %>
td <%= schema.singular %>.<%= k %> <% end %>
td do
phx_link "Show", to: Routes.<%= schema.route_helper %>_path(@conn, :show, <%= schema.singular %>)
phx_link "Edit", to: Routes.<%= schema.route_helper %>_path(@conn, :edit, <%= schema.singular %>)
phx_link "Delete", to: Routes.<%= schema.route_helper %>_path(@conn, :delete, <%= schema.singular %>),
method: :delete, data: [confirm: "Are you sure?"]
end
end
end
end
end
end
span do
phx_link "New <%= schema.human_singular %>", to: Routes.<%= schema.route_helper %>_path(@conn, :new)
end

View file

@ -0,0 +1,13 @@
h1 "New <%= schema.human_singular %>"
partial render("form.html",
Map.put(
assigns,
:action,
Routes.<%= schema.route_helper %>_path(@conn, :create)
)
)
span do
phx_link "Back", to: Routes.<%= schema.route_helper %>_path(@conn, :index)
end

View file

@ -0,0 +1,16 @@
h1 "Show <%= schema.human_singular %>"
ul do <%= for {k, _} <- schema.attrs do %>
li do
strong "<%= Phoenix.Naming.humanize(Atom.to_string(k)) %>"
text @<%= schema.singular %>.<%= k %>
end <% end %>
span do
phx_link "Edit", to: Routes.<%= schema.route_helper %>_path(@conn, :edit, @<%= schema.singular %>)
end
span do
phx_link "Back", to: Routes.<%= schema.route_helper %>_path(@conn, :index)
end
end

View file

@ -0,0 +1,3 @@
defmodule <%= inspect context.web_module %>.<%= inspect Module.concat(schema.web_namespace, schema.alias) %>View do
use <%= inspect context.web_module %>, :view
end

View file

@ -0,0 +1,36 @@
html lang: "en" do
head do
meta charset: "utf-8"
meta http_equiv: "X-UA-Compatible", content: "IE=edge"
meta name: "viewport", content: "width=device-width, initial-scale=1.0"
title "<%= application_module %> · Phoenix Framework"
link rel: "stylesheet", href: Routes.static_path(@conn, "/css/app.css")
end
body do
header do
section class: "container" do
nav role: "navigation" do
ul do
li do: a("Get Started", href: "https://hexdocs.pm/phoenix/overview.html")
end
end
a href: "http://phoenixframework.org/", class: "phx-logo" do
img src: Routes.static_path(@conn, "/images/phoenix.png"),
alt: "Phoenix Framework Logo"
end
end
end
main role: "main", class: "container" do
p get_flash(@conn, :info), class: "alert alert-info", role: "alert"
p get_flash(@conn, :error), class: "alert alert-danger", role: "alert"
partial render(@view_module, @view_template, assigns)
end
script type: "text/javascript", src: Routes.static_path(@conn, "/js/app.js")
end
end