Posts tagged #phoenix

Open your text editor with the migration file when you run mix ecto.gen.migration

There is a neat little trick which I found while browsing Ecto’s code Adding the following line to your ~/.bashrc will open up your new migration file with the text editor of your choice

ECTO_EDITOR="code" # put the name of your editor here

Now, when you run mix ecto.gen.migration, it will open up your editor and you can modify your migration.

I actually use neovim to edit my code. However, it doesn’t open up from erlang. I tried running :os.cmd 'nvim /tmp/a' but it fails with an error about stdin not being found.

A good .iex.exs for your phoenix apps

Having a good .iex.exs in your phoenix apps makes it easy to navigate in your iex repl.

Here is what I have in my phoenix apps:

# .iex.exs
alias GC.{

import Ecto.Query

alias GC.Client, as: DC
alias GC.Web.Router.Helpers, as: RH

import IExHelpers

# lib/iex_helpers.ex

defmodule IExHelpers do
  alias GC.{Repo, User}
  def get_user, do:, limit: 1)
  def routes, do: "phx.routes"

What are the tricks present in your .iex.exs? Please share :)

Changes to your prod.exs before deploying phoenix apps using distillery

While deploying my first phoenix app. I spent 2 hours trying to debug why my phoenix app wasn’t showing up on http://localhost:4000. I usually test it using curl -v http://localhost:4000/ from my server. I had my head scratching for a long time before reading these lines in the prod.exs file

# ## Using releases
# If you are doing OTP releases, you need to instruct Phoenix
# to start the server for all endpoints:
#     config :phoenix, :serve_endpoints, true
#config :phoenix, :serve_endpoints, true

As it says, uncomment the :serve_endpoints line if you are using distillery for deployments and save yourself some frustration :)

How to redirect to back or the root path similar to rails in a phoenix app

While writing a phoenix app you may want to redirect a user back to where they came from. This is possible because HTTP sends you a refer header which tells you which page/url the user came from. Rails allows you to this using redirect_to :back in versions < 5 and redirect_back(fallback: "/") in versions >= 5. You can do something similar in Phoenix by using the following code snippet.

def redirect_back(conn, fallback \\ "/") do
    case get_req_header(conn, "referer") do
      [referer] -> redirect conn, to: referer
      _         -> redirect conn, to: fallback

Which can be used as below.

|> put_flash(:info, "Success!")
|> redirect_back

# or

|> put_flash(:info, "Success!")
|> redirect_back(_fallback = "/dash")

How to open your web browser with your app when you start your phoenix app

I have added this line to my .iex.exs to automatically open my web browser when I start my phoenix app

# .iex.exs
spawn(fn -> :os.cmd('xdg-open http://localhost:4000/') end)

Hat tip to: