Use quoted function without to write function twice

Hi,

Is it possible to use a function defined in a __using__ block without redefining it ?

--------------- working ---------------

 defmodule ModuleA do
     def function do
         IO.puts "function"
     end
     defmacro __using__(_) do
         quote do
             def function do
                 IO.puts "function"
             end         
         end
     end
 end
 defmodule ModuleB do
     use ModuleA
 end

 ModuleB.function # output function 
 ModuleA.function # output function 

--------------- not working ---------------

 defmodule ModuleA do
     defmacro __using__(_) do
         quote do
             def function do
                 IO.puts "function"
             end         
         end
     end
 end

 defmodule ModuleB do
     use ModuleA
 end

 ModuleB.function # output function 
 ModuleA.function # output function
1 Like

For note, using quotes instead of code fences make the code reeeeally hard to read. ^.^
You can use code fences by putting ``` on the line before and after the code, such as this solution:

defmodule ModuleA do
  def function do
    IO.puts "function"
  end

  defmacro __using__(_) do
    quote do
      defdelegate function(), to: ModuleA
    end
  end
end

defmodule ModuleB do
  use ModuleA
end

ModuleB.function # output function
ModuleA.function # output function

Would that work for you? :slight_smile:

Basically it is just defining the function once (in ModuleA) but the using is just setting up a delegate on whatever uses it (in this case ModuleB) to delegate the call to ModuleA.function. :slight_smile:

I use this pattern in a repeated area in my big work project.

1 Like

Thanks for solution :slight_smile: This is what i want
PS: I don’t know why _ _ using _ _ is transform to using

1 Like

The reason that __using__ was transformed to using (i.e. the word in bold) is because posts on this topic use Markdown to style. (as well as allowing BBcode and a subset of HTML, I believe).

This means that when you surround a word (or a sentence) with a * or a _, such as _foo_, it will become italic, and when you surround them with a double ** or __, it will become bold.

If you don’t want this to happen, you can surround a word or sentence with backticks (` __foo__ `) and it will become __foo__ without the markup showing.

This is useful for small single-line code snippets. If you want larger code snippets, you can surround a block of text with triple backticks instead, and you will create a code-block, which includes code highlighting.

I have edited your first post to use code blocks instead of quote blocks. :wink:

2 Likes