-
-
Save craigp/79334773cd12a23243a891917a9d762d to your computer and use it in GitHub Desktop.
Officially tired of aliasing `Repo` and importing `Ecto.Query` by hand every IEx session
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env elixir | |
ecto_import = "import Ecto.Query, only: [from: 2]" | |
mixexs = | |
Path.join(["mix.exs"]) | |
|> File.read! | |
namespace = | |
Regex.run(~r{defmodule\s+(\w+)\.}, mixexs) | |
|> List.last | |
repo_alias = "alias #{namespace}.Repo" | |
models = | |
Enum.map Path.wildcard("web/models/*.ex"), fn m -> | |
Regex.run(~r{models/(\w+).ex}, m) | |
|> List.last | |
|> String.split("_") | |
|> Enum.map(& String.capitalize &1) | |
|> Enum.join("") | |
end | |
aliases = | |
models | |
|> Enum.map(& "alias #{namespace}.#{&1}") | |
|> Enum.join("\n") | |
iexexs_txt = "#{ecto_import}\n\n#{repo_alias}\n\n#{aliases}\n" | |
Path.join([".iex.exs"]) | |
|> File.write(iexexs_txt, [:append]) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ cd ~/elixir/hello_phoenix | |
$ head -1 mix.exs | |
defmodule HelloPhoenix.Mixfile do | |
$ tree web/models | |
web/models | |
├── comment.ex | |
├── post.ex | |
└── user.ex | |
$ curl -o new_phoenix_dot_iex.exs -L http://git.io/vCNRt | |
$ elixir new_phoenix_dot_iex.exs | |
$ cat .iex.exs | |
import Ecto.Query, only: [from: 2] | |
alias HelloPhoenix.Repo | |
alias HelloPhoenix.Comment | |
alias HelloPhoenix.Post | |
alias HelloPhoenix.User | |
$ iex -S mix | |
iex(1)> Repo.all from u in User, select: u | |
[debug] SELECT u0."id", u0."name", u0."inserted_at", u0."updated_at" FROM "users" AS u0 [] OK query=68.9ms queue=2.2ms | |
[%HelloPhoenix.User{__meta__: #Ecto.Schema.Metadata<:loaded>, id: 1, | |
inserted_at: #Ecto.DateTime<2015-10-18T07:19:31Z>, name: "Brad", | |
updated_at: #Ecto.DateTime<2015-10-18T07:19:31Z>}] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment