sodapopcan

sodapopcan

I’ve been doing a lot of prototypes in Phoenix lately. After doing the same annoying things over and over after each invocation of $ mix phx.new blah I ended up with script to bootstrap a new app the way I like it. I’m sure many have done this and was wondering if others had scripts to share. Or perhaps there is a library I’m missing to better define this stuff? https://phx.new/ does not do it for me. I’d love to see your scripts or get feedback on mine (I’m no shell expert).

The things I always do are:

  • Tell ecto to use utc_datetime_usec for timestamps
  • Use binary ids for primary keys
  • Create a custom Schema module for setting said primary keys as well as use and import the usual stuff
  • Remove page controller and associated files
  • Remove other boilerplate (phoenix css, phoenix logo)
  • Create a HomeLive LiveView (I pretty much always have a HomeLive to start which maybe gets renamed later)

Here’s my script:

#!/usr/bin/env bash

function snake_to_pascal {
  echo $1 | perl -pe 's/(?:\b|_)(\p{Ll})/\u$1/g'
}

mix phx.new "$@" --binary-id

cd "$1"

# Delete page controller
rm "lib/$1_web/controllers/page_controller.ex"
rm "test/$1_web/controllers/page_controller_test.exs"

# Delete templates
rm "lib/$1_web/templates/page/index.html.heex"
rmdir "lib/$1_web/templates/page"

# Delete view
rm "lib/$1_web/views/page_view.ex"

# Remove header from the root layout
sed -I '' '13,27d' "lib/$1_web/templates/layout/root.html.heex"

# Remove getext thing (if it's there)
sed -I '' '10s/.*/      compilers: Mix.compilers(),/' mix.exs

# Remove CSS
rm assets/css/phoenix.css
echo > assets/css/app.css

# Use utc_datetime_usec in migrations
subt="s/pool_size: 10/pool_size: 10,\n  migration_timestamps: \[type: :utc_datetime_usec\]/"
sed -I '' "$subt" "config/dev.exs"
sed -I '' "$subt" "config/test.exs"

# Setup a HomeLive
sed -I '' 's/get "\/", PageController, :index/live "\/", HomeLive, :index/' "lib/$1_web/router.ex"

mkdir "lib/$1_web/live"

module=$(snake_to_pascal "$1")

cat <<EOF > "lib/$1/schema.ex" 
defmodule ${module}.Schema do
  defmacro __using__(_) do
    quote do
      use Ecto.Schema

      import Ecto.Changeset, warn: false

      @timestamps_opts type: :utc_datetime_usec

      @primary_key {:id, :binary_id, autogenerate: true}
      @foreign_key_type :binary_id
    end
  end
end
EOF

cat <<EOF > "lib/$1_web/live/home_live.ex" 
defmodule ${module}Web.HomeLive do
  use ${module}Web, :live_view

  def render(assigns) do
    ~H"""
    <h1>${module}</h1>
    """
  end
end
EOF

# Delete phoenix logo
rm priv/static/images/phoenix.png

# Use the heex formatting plugin
cat <<EOF > ".formatter.exs"
[
  import_deps: [:ecto, :phoenix],
  plugins: [Phoenix.LiveView.HTMLFormatter],
  inputs: ["*.{heex,ex,exs}", "priv/*/seeds.exs", "{config,lib,test}/**/*.{heex,ex,exs}"],
  subdirectories: ["priv/*/migrations"]
]
EOF

I realize this is coming hot on the heels of the next phoenix release so these could end up changing a little. But I’m glad I didn’t take the time to make this thing add tailwind!

Showing Posts 1 to 10

dogweather

dogweather

I’d like to see a guide like this for making simple JSON servers in Phoenix: the steps to exclude all the templating, HTML, even database sometimes.

sodapopcan

sodapopcan OP

If you don’t want the database you can do $ mix phx.new --no-ecto. Otherwise I don’t fully know what you have in mind but I assume you would want to uncomment the /api routes in the router and set up some common controllers?

dogweather

dogweather

Thanks. My Phoenix app probably has the most minimal dependencies possible: it’s a “redirect server”. I have all my old domain names pointed to it, and it saves my Pagerank/SEO by replying with 301’s to the current locations. It doesn’t even need JSON. The log looks like this:

01:41:56.084 request_id=FxiUHVktYMUpJhcAMZiB [info] GET /ors/167.347
01:41:56.084 request_id=FxiUHVktYMUpJhcAMZiB [info] Sent 301 in 51µs
01:42:01.986 request_id=FxiUHrju6IcV6nYAMZiR [info] GET /
01:42:01.986 request_id=FxiUHrju6IcV6nYAMZiR [info] Sent 301 in 63µs
01:42:06.529 request_id=FxiUH8fF40HTccUAMZih [info] GET /ors/609.020
01:42:06.530 request_id=FxiUH8fF40HTccUAMZih [info] Sent 301 in 78µs
01:42:08.381 request_id=FxiUIDYk7rKSDOwAMZix [info] HEAD /
01:42:08.381 request_id=FxiUIDYk7rKSDOwAMZix [info] Sent 301 in 47µs

It’s great because it uses just 200MB of RAM and 0% CPU. I have it on a server with my other apps, so hosting is free. It’s very flexible and testable.

dimitarvp

dimitarvp

Voting with three hands up! :041:

I too wish we had flags for starting projects like this. Hell, with the advent of tools like treesitter I’d even try my hand at devising scripts that can modify existing projects.

Alas, the pesky bills always keep coming and nobody will pay you to do such work. :022:

dimitarvp

dimitarvp

You probably would be better served by a Plug project. You start off with much less deps and you can opt-in to anything you need from Phoenix, piecemeal.

It’s slightly more tedious to do but it still took me an afternoon and that project has been rock-solid for no less than 2 years now, doing its stuff on a VPS. I only invested another several hours when I wanted to add some metrics a few months ago.

dmitriid

dmitriid

I have the same feeling. I’m now starting a third project this year, and every time after running phx.new I have the same reaction: “now what?” :slight_smile: Oh, right: clean out views and layouts, remember how to tie layouts together for a live view, add seeds and repo details,… and a thousand of other small things

Too bas these small things are different for different people, otherwise it would be nice to have them done by the generator

webuhu

webuhu

Anyone else also cleaning up the code comments?

cevado

cevado

i usually clean up comments. but I only use a replace regex applyied to all .ex files in the project.

sodapopcan

sodapopcan OP

A bunch of them, yes, but I haven’t worked that into the script yet. There are some I think are useful to leave if it was expecting to grow, although I’ve never started such a project on my own before.

cevado

cevado

I usually do this manually, because I change some naming convetion and organization on phoenix apps.
But I guess this automatic cleanup as your script does, would be cool.
I think it could even be mix task on phoenix… mix phx.clean_examples or something like that.

Where Next? Top

Trending in Discussions Top

AstonJ
As the title says, please share what you’ve been up to with Elixir. Whether that’s been learning it, looking into it, making stuff with i...
2977 91898 914
New
AstonJ
The obligatory hello world thread! Who are you and where are you from? :stuck_out_tongue:
4616 55835 594
New
byu
@chrismccord : I just saw the Extract AGENTS.md from Phoenix.new into phx.new generator commit to the phoenix project. My initial shotgu...
New
arcanemachine
I was working on an Ecto migration and I needed a timestamp. So, for the nth time, I looked up the different data types for timestamps, a...
New
alexslade
Fly’s CEO posted this recently - Turn And Face The Strange · The Fly Blog It says that Fly is going all-in on sprites, which is a worry ...
New
Herve37
We’re evaluating API mocking tools for OpenAPI-based projects and would love to hear what other teams are using. We’re particularly inte...
New
matt-savvy
Is there a word for the ~> symbol used in Version strings? Do you also just call it a Squiggle Arrow™ ?!
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New

Latest on Elixir Forum

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews