I’m creating a new app in phoenix 1.3 where I don’t need database, it’s gonna be a sort of dashboard, but I still need context and schemas to represent some domain things. I was thinking of having a genserver where I can store these domain objects in a map. Now my question is, do I need ecto for this? I remember reading Programming Phoenix where at the beginning instead of using the database, some in memory storage was used. Is this something like this what I have to do? Or should I create a project with --no-ecto? in that case, if I want to create a new schema, do I still have to use changesets and so on?
What would be the best way to replace database storage for in memory storage?
thanks
If you still want to use ChangeSets (you mentioned schemas) the Using Ecto without a Repo may be of interest.
You can also use Erlang Term Storage: Optimizing Your Elixir and Phoenix projects with ETS.
Mnesia is a bit more involved.
I’ve been using Ecto for schemas, changesets, and validations to build out an Elasticsearch client. I’m using embedded_schemas
.
Here’s a fairly contrived example, but this is sort of what I’m doing:
defmodule MySchema do
use Ecto.Schema
import Ecto.Changeset
@primary_key false
embedded_schema do
field :my_field, :string
end
def changeset(schema, attrs) do
# cast, validations, etc.
end
end
attrs = %{ my_field: "Some Value" }
changeset = MySchema.changeset(%MySchema{}, attrs)
case changeset.valid? do
true -> persist_changes # this could be to your local storage or wherever
false -> handle_failure
end
In my case, I actually don’t really need changesets, what I need are schemas, as I need a way to represent let’s say a domain object. So I guess I need Ecto for this right? as schemas are from ecto, unless there is another structure I can use to represent a domain model?
You could use plain old structs. Using Changesets though will get you nice things like Ecto.Changeset.cast/4, which will handle type checking for you. If you simply need to structure your data you may be able to get away with structs though.
You don’t need Ecto per se. You can get by my defining your own struct that represents your domain using defstruct
. Ecto.Schema automatically gives you a struct. If were to use an embedded_schema
you would still get that but you would also have access to changesets. Changesets are fantastic for making sure data/fields exists whenever you want to do a CRUD operation.