【发布时间】:2018-09-14 07:20:15
【问题描述】:
在 Elixir 中,有没有办法直接从 shell 调用模块函数,而不必启动 iex -S mix 会话?让我用一个场景来说明:
作为我的 Phoenix 应用程序的一部分,我编写了一个帮助模块,该模块将从相邻的 iex -S mix 会话中运行。这是一个超级简化的版本:
defmodule MyApp.Helper do
# For the demo, these imports/aliases are not used - but they're there in real life.
import Ecto.Query
alias MyApp.Repo
def start do
{:ok, "Done"}
end
end
如果我使用iex -S mix 开始会话,然后从模块中运行一个函数,一切正常:
$ iex -S mix
Erlang/OTP 20 [erts-9.2] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false] [dtrace]
Compiling 2 files (.ex)
Interactive Elixir (1.5.2) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> MyApp.Helper.start
{:ok, "Done"}
然后ctrl-c a 关闭会话。
但是,如果我尝试类似:
$ iex -S mix MyApp.Helper.start
结果
Erlang/OTP 20 [erts-9.2] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:10] [hipe] [kernel-poll:false] [dtrace]
Compiling 2 files (.ex)
** (Mix) The task "MyApp.Helper.start" could not be found
或者,我尝试将我的模块重新定义为自定义混合任务,如下所述:https://elixirschool.com/en/lessons/basics/mix-tasks/#custom-mix-task
但这也失败了,因为我的模块依赖于一些导入/别名,例如MyApp.Repo,并且尝试使用mix helper 或iex -S mix helper 执行文件导致
** (ArgumentError) repo MyApp.Repo is not started, please ensure it is part of your supervision tree
如果没有办法解决这个问题并且脚本只能从正在运行的iex -S mix 中成功执行,那很好......但是如果有一种方法可以设置,那么单线可以从 shell 运行要让它根据需要执行,那就是蜜蜂的膝盖。
【问题讨论】:
标签: shell elixir elixir-iex