Define an extra function for all the phoenix modules

I want to use a function I defined myself put_assoc_new/4. I want it to be available like how put_assoc/3 is available, by adding import Ecto.Changeset, I don’t want to add extra imports if that is possible.

if I can add it to the Ecto.Changeset module that would be great.

what are your thoughts?

You can’t extend a library that’s not yours. :slightly_smiling_face:

You can define your own helper in your project and use it from there.

1 Like

I created use modules for schemas and context modules in my application to include things like this.

For example

defmodule MyApp.Schema do
  defmacro __using__(_) do
    quote do
      use Ecto.Schema
      import Ecto.Changeset
      alias Ecto.Changeset
    
      import MyApp.ChangesetHelpers
    end
  end
end

defmodule MyApp.ChangesetHelpers do
  def put_assoc_new ...
end 

defmodule MyApp.User do
  use MyApp.Schema
  schema "users" ...
end
5 Likes