本文介绍了Code.ensure_loaded?在.iex.exs中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 .iex.exs 中存储了一个万灵药的控制台配置:

I have an elixir console configuration stored in .iex.exs:

if Code.ensure_loaded?(MyApp.Repo) do
  alias MyApp.Repo
end

我希望能够同时运行 iex iex -S mix 。如果删除 iex 上的条件,我将有例外。

I want to have an ability to run both iex and iex -S mix. I'll have exception if I remove condition on iex.

但此条件不能很好地工作!即使在 iex -S混合上,如果我尝试调用(模块存储库不可用)错误。 code> Repo.get(...)。所以,我的问题是:

But this conditions doesn't work well! Even on iex -S mix I have (module Repo is not available) error if I'm trying to invoke Repo.get(...). So, my questions are:


  1. 为什么 Code.ensure_loaded?不起作用在这里?

  2. 我该如何解决?

  1. Why Code.ensure_loaded? doesn't work here?
  2. How can I fix that?


推荐答案

这是范围界定的问题。在一个块内,您定义了以下别名:

This is a matter of scoping. Inside a block, you have this alias defined:

if Code.ensure_loaded?(MyApp.Repo) do
  alias MyApp.Repo
  Repo.get(...) #⇒ available
end

要在整个IEx范围内定义别名,则应在任何块之外调用它:

To define an alias IEx-wide, you should call it outside of any block:

alias MyApp.Repo

您不需要有条件的如果Code.ensure_loaded?(MyApp.Repo) IEx iex -S mix ,将自动为您加载所有依赖项。对于纯 iex ,这可能会比较麻烦:

You do not need a conditional if Code.ensure_loaded?(MyApp.Repo) when IEx is executed with iex -S mix, all the dependencies will be loaded for you automagically. For pure iex this might be done in more cumbersome way:

defmodule FileExt do
  def ls_all(dir, acc \\ []) do
    case File.ls(dir) do
      {:ok, list} -> list |> Enum.reduce(acc, fn f, acc ->
          fullname = dir <> "/" <> f
          if fullname |> File.dir?, do: ls_all(fullname, acc), else: acc ++ [fullname]
        end)
      {:error, e} ->
        IO.puts "Unable to list. Reason: #{e}"
        acc
    end
  end

  def require_lib do
    try do
      "lib" |> FileExt.ls_all |> Kernel.ParallelRequire.files
    rescue
      e in UndefinedFunctionError -> Code.ensure_loaded?(MyApp.Repo)
    end
  end
end

try do
  MyApp.Repo.get
rescue
  e in UndefinedFunctionError -> FileExt.require_lib
end

alias MyApp.Repo

上面的代码将从 lib 目录中加载所有文件。

The above would load all files from the "lib" directory.

尽管我会在这里关闭完美主义始终使用 iex -S混合,而无需检查:

Though I would shut the perfectionism up here and go with iex -S mix always, without check:

Code.ensure_loaded?(MyApp.Repo)
alias MyApp.Repo

这篇关于Code.ensure_loaded?在.iex.exs中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 16:18