Skip to content

Instantly share code, notes, and snippets.

@bitwalker
Created March 23, 2016 22:48
Show Gist options
  • Save bitwalker/ae5be60faf924d2e5082 to your computer and use it in GitHub Desktop.
Save bitwalker/ae5be60faf924d2e5082 to your computer and use it in GitHub Desktop.
A simple solution to executing code as part of a release
defmodule MyApp do
use Application
def start(_type, _args) do
import Supervisor.Spec, warn: false
:ok = handle_args!
children = []
Supervisor.start_link(children, strategy: :one_for_one, name: MyApp.Supervisor)
end
def config_change(_changed, _new, _removed) do
:ok = handle_args!
:ok
end
defp handle_args! do
# Any -- arguments will get stripped, so pass them plain and append the flags for convenience
raw_args = Enum.map(:init.get_plain_arguments, fn a -> "--#{a}" end)
case OptionParser.parse(raw_args, switches: [migrate: :boolean]) do
{opts, _, _} when is_list(opts) ->
migrate? = get_in(opts, [:migrate]) || false
cond do
migrate? -> migrate!
:else -> :ok
end
_ ->
:ok
end
end
defp migrate! do
core_priv_dir = "#{:code.priv_dir(:myapp)}"
migrations_dir = Path.join([core_priv_dir, "repo", "migrations"])
seed_script = Path.join([core_priv_dir, "repo", "seeds.exs"])
# Run migrations
Ecto.Migrator.run(MyApp.Repo, migrations_dir, :up, all: true)
# Run seed script
Code.require_file(seed_script)
:ok
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment