Contexts - SolarisJapan/lunaris-wiki GitHub Wiki
Contextualized Modules
Ecto's system of schemas and changesets can be leveraged to provide a framework for contextualizing modules in your application. There could be many use cases for contexts. Imagine an app which deals heavily with Shopify's order and fulfillment webhooks and APIs. We can also expect there to be some UI for this app.
Restricting Possibilities
In the example mentioned previously, the end-user would likely have no reason to create or update orders. Similarly the webhook handling module likely does not need to view the resource being created or updated. By having different context modules for each use case the module can be better kept focused on its purpose. One way to do this is to create schemas limited in scope.
A schema with no changesets for example would not allow the user to create or update a model in the database in the typical manner. With a larger project it can be easy to forget the exact context of a module, or perhaps a coworker is not as familiar with the project. The developer should take a moment to consider if they are doing the correct thing if they attempt to create or update a modal in a context where it was not previously possible.
Authorization
The above principles of restricting possibilities also has worthwhile use cases in authorization. With a slightly different example, perhaps the orders are able to be edited in the view. An admin may have a wider range of fields that they are authorized to change than a typical user.
By creating either different contexts or simply a different changeset for admins and users this can be accomplished easily. It is unlikely that admin_update_changeset
would be attributed to a user update action without being noticed.