Import in an import, functions not found?

I have a helper module for importing that I want to split into two modules and import the first into the second (so I can reuse the first). Basically:

defmodule DataHelpers do
  def foo(), do: ...
end

defmodule ViewHelpers do
  import DataHelpers
end

defmodule SomeOtherModule do
  import ViewHelpers
end

I get an error that foo() is not defined in SomeOtherModule.

Hi @7rans, I think you’re confused about what import does. When you import DataHelpers inside of ViewHelpers you allow code inside of ViewHelpers to refer to functions inside DataHelpers to call functions from DataHelpers without specifying the module. What it does not do is copy or add those functions into DataHelpers.

If you want both of those helpers in SomeOtherModule you’ll need to import both modules.

4 Likes

You could do this:

defmodule DataHelpers do
    def foo() do
      # ...
    end
  end

  defmodule ViewHelpers do
    defmacro __using__(_) do
      quote do
        import DataHelpers
      end
    end
  end

  defmodule SomeOtherModule do
    use ViewHelpers
  end

But it is only interesting if useing ViewHelpers will import multiple modules, otherwise it is just useless indirection.

1 Like

I take it this has to do with “lexical scoping”, and that makes sense.

From a usability standpoint, it might be nice if there were a way to have “pass-it-on” imports (would that be private vs public imports?). Just a thought.

Thanks for the explanation.

Thanks for the workaround. So far I’ve been able to get on without it. But it’s nice to know the way if I need it.