Hello!
I’m new to elixir and trying to follow best practices by exposing my Public API through context modules.
Imagine I have a simple ecto schema like this:
# lib/businesses/business_schema.ex
defmodule Business.BusinessSchema do
use Ecto.Schema
schema "businesses" do
field :name, :string
field :status, :string
# other fields...
end
end
And then I have a context module like that uses the schema:
# lib/businesses_context.ex
defmodule BusinessContext do
alias Business.BusinessSchema
# Context functions
def get_business(id), do: # implementation...
def list_businesses(), do: # implementation...
# other functions...
end
I want all other parts of my app to be able to pattern match on the schema, but I don’t want to expose the schema to the outside world. (edit: by outside world, I just mean the code outside of the lib/app_name folder. So that the contexts are the public api for the app)
For example I want to be able to do this
# lib/some_module.ex
defmodule SomeModule do
alias BusinessContext
def some_function(%BusinessSchema{} = business) do # <---- I want to be able to do this
# do something with the business
end
end
This seems to work but feels clunky.
# lib/businesses_context.ex
defmodule BusinessContext do
alias Business.BusinessSchema
def business_schema_type, do: BusinessSchema
# Context functions
def get_business(id), do: # implementation...
def list_businesses(), do: # implementation...
# other functions...
end
# lib/some_module.ex
defmodule SomeModule do
alias BusinessContext
@business_schema_type BusinessContext.business_schema_type()
def some_function(%@business_schema_type{} = business) do # <---- This works
# do something with the business
end
end
Is there a better way to do this?