Could anyone give me a simple example of how to persist data in Elixir. Coming from a JavaScript background I’m still not fully understanding the functional paradigm.
and where you want to persit the data? You have a few options:
- Relational database. Most obvious / popular choice is to use Ecto https://github.com/elixir-ecto/ecto
- Serialize to binary blob with :erlang.term_to_binary/1 and save to file
- Use DETS http://erlang.org/doc/man/dets.html
- Use Mnesia (via Amnesia or directly, https://github.com/meh/amnesia)
…
… - There are many many many more options.
There are 2 different meanings to this:
First is to really persist the data even when the application restarts
- This is well explained in the above post from @hubertlepicki
Second is to keep data only in running application [keep a state] (like an object instance in OO languages)
- Manual state struct which you’ll pass around in the module
- I use this option if I need to keep just a simple state in one module
- You can use Agents: http://elixir-lang.github.io/getting-started/mix-otp/agent.html
- I use this if I need to keep state between more modules
- You can create a GenServer: https://hexdocs.pm/elixir/GenServer.html
- a bit more robust solution.
The above state won’t survive the application crashes/restarts though, so you usually use the mix of GenServer/Agent and Database/Amnesia/DETS, etc.
This is a great article that talks about the different states , it is for Erlang, but it explains theory well.
http://learnyousomeerlang.com/building-applications-with-otp#the-onion-layer-theory
Cheers mate
2 Likes