Skip to content

Commit

Permalink
fix: Fixing table access when file already exists. #1
Browse files Browse the repository at this point in the history
  • Loading branch information
LuchoTurtle committed Dec 25, 2022
1 parent ab8c2b7 commit 990444e
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 5 deletions.
16 changes: 14 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1146,9 +1146,14 @@ defmodule UsersTable do
alias Pockets

@table :users_table
@filepath "cache.dets"

def init do
Pockets.new(@table, "cache.dets")
case Pockets.new(@table, @filepath) do
{:ok, set} -> {:ok, set}
{:error, _} ->
Pockets.open(@table, @filepath)
end
end

def list_users do
Expand All @@ -1172,6 +1177,7 @@ referring to whether the user has paid or not.
All the functions being used are used
according to the [`ets` wrapper documentation](https://github.com/TheFirstAvenger/ets).
- the `init/0` function creates the table to store our users.
If the file already exists, we open the file.
- `list_users` returns the list of users.
- `create_user/3` receives a `stripe_id`, `person_id` and `status`
(pertaining to whether the payment has been made or not)
Expand All @@ -1181,8 +1187,14 @@ Let's make use of some of these functions.
We want to setup the `DETS` table on the process startup.
For this, we are going to initiate the table
on the `start/1` function inside `lib/app/application.ex`.
This functions is executed when the process is created,
This function is executed when the process is created,
so it fits right our needs!
Add the following code below the `children` array variable
inside `start/1`.

```elixir
UsersTable.init()
```


Awesome!
Expand Down
2 changes: 0 additions & 2 deletions lib/app/application.ex
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,6 @@ defmodule App.Application do

# Creating DETS user table
UsersTable.init()
#UsersTable.create_user(%{person_id: 1, stripe_id: 1, status: false})
#dbg(UsersTable.list_users())

# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
Expand Down
7 changes: 6 additions & 1 deletion lib/app/users.ex
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,14 @@ defmodule UsersTable do
alias Pockets

@table :users_table
@filepath "cache.dets"

def init do
Pockets.new(@table, "cache.dets")
case Pockets.new(@table, @filepath) do
{:ok, set} -> {:ok, set}
{:error, _} ->
Pockets.open(@table, @filepath)
end
end

def list_users do
Expand Down

0 comments on commit 990444e

Please sign in to comment.