How to make a context reusable?

Hi everyone. I learning phoenix through a toy app, and I’m having some trouble trying to make a context reusable, by putting it in its own repository. This app requires a database to work, so it needs to define its own tables. The approach I’m going with is to have migrations on this repo, and copy these files to new applications that will use them.

My problem is: how do I handle the application scope? I need to have a reference column on the tables, and also need to define a scope on my library. Can I receive the scope through configuration? If so, how can I write the library code and tests? Do I define a default overideable scope?

Do these questions even make sense? Is this problem commonly solved in complete different manner?

1 Like

You’ve mostly described a solution (putting context modules in their own repository) not the problem so it’s hard to answer this question. I would say it’s fairly uncommon thing to do yes. Some libraries, Oban comes to mind, do provide a context to manage its own db tables, so it certainly can be done. You might want to look at its source for inspiration.

I reread my post and you’re right. I guess what I need is a way to make a context reusable across different apps. In my case, I have a nano (more like femto) ERP for a family business, and I’d like to take the acounting context to use on another project.

Just create a supervised library. No need to have anything to do with Phoenix, plain mix new --sup accounting. Use Ecto and expect configuration through Application and you’re good to go.

1 Like

That was my initial idea, I just don’t know how to handle getting a generic scope through the Application configuration

I’ll tell you how. Make your supervised library expose a protocol and internally work only with it, no concrete implementations. Then, implement the protocol for your scope, or scopes, and pass them fearlessly to the library. This way you program against a contract. It might sound strange to you because the Elixir community generally dislikes doing it, for some reason. It will work for you in this case.

1 Like