Skip to content

Instantly share code, notes, and snippets.

@gpad
Last active August 25, 2020 07:57
Show Gist options
  • Save gpad/b6a6540e5cf2f6aca6b245ed3e7b1a83 to your computer and use it in GitHub Desktop.
Save gpad/b6a6540e5cf2f6aca6b245ed3e7b1a83 to your computer and use it in GitHub Desktop.
My .iex.extension. In your app dir you can do: `GPad.start_app :timex` and if you have :timex in your deps it will be launched.
defmodule GPad do
def get_base() do
try do
get_base(System.get_env("MIX_ENV")) |> Path.join("lib")
catch
e -> IO.puts("Error: #{inspect(e)}")
end
end
def get_base(nil) do
get_most_recent("_build")
end
def get_base(env) do
path = Path.join("_build", env)
if File.exists?(path) do
path
else
get_most_recent("_build")
end
end
def get_most_recent(base) do
File.ls!(base)
|> Enum.reject(&String.starts_with?(&1, "dialyzer"))
|> Enum.map(fn p ->
path = Path.join(base, p)
%{mtime: mtime} = File.lstat!(path)
{path, mtime}
end)
|> Enum.sort(fn {_, mtime1}, {_, mtime2} -> mtime1 > mtime2 end)
|> first(fn {p, t} ->
IO.puts("Load from #{inspect(p)} #{inspect(t)}")
p
end)
end
# defp first(l), do: hd(l)
defp first(l, fun), do: fun.(hd(l))
def load_apps() do
base = get_base()
File.ls!(base)
|> Enum.map(fn p ->
Code.prepend_path(Path.join([base, p, "ebin"]))
Application.load(String.to_atom(p))
end)
end
def load(app) when is_atom(app) do
base = get_base()
Code.prepend_path(Path.join([base, Atom.to_string(app), "ebin"]))
Application.load(app)
end
def loaded?(app) do
Application.loaded_applications() |> Enum.filter(fn {a, _, _} -> a == app end) != []
end
def start_app(app) do
if !loaded?(app) do
load_apps()
end
Application.ensure_all_started(app)
end
end
defmodule Humanize do
def memory(value) do
do_humanize(value, 1, :memory)
end
def do_humanize(value, count, type) do
unit = unit(type, count)
if value < unit do
s = :io_lib.format("~.2f", [value / unit(type, count - 1)]) |> to_string
"#{s} #{udm(count, type)}"
else
do_humanize(value, count + 1, type)
end
end
def unit(:memory, count), do: :math.pow(1024, count)
def udm(count, :memory) do
case count do
1 -> "byte"
2 -> "KB"
3 -> "MB"
4 -> "GB"
5 -> "TB"
_ -> "PB"
end
end
@doc """
Return a map composed by the keys requested. The value is nil fi key is not found.
"""
def mget(map, keys) do
Enum.reduce(keys, %{}, fn
key, acc when is_list(key) ->
k = List.last(key)
Map.put(acc, k, get_in(map, key))
key, acc ->
Map.put(acc, key, Map.get(map, key))
end)
end
end
# IO.puts "GPAD library from #{GPad.get_base()} ..."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment