Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assert the size of the list in elixir

Tags:

elixir

I would like to assert list's size. Currently I do it as follows:

assert devices = Repo.all from d in device, where d.uuid == ^attrs.uuid
assert devices.first == devices.last

Is there a better way to do that?

like image 880
almeynman Avatar asked May 24 '16 13:05

almeynman


People also ask

How do you find the size of an elixir list?

The length() function returns the length of the list that is passed as a parameter.

How do you get the first element of a list in Elixir?

The head is the first element of a list and the tail is the remainder of a list. They can be retrieved with the functions hd and tl. Let us assign a list to a variable and retrieve its head and tail.

How do I add to my list in Elixir?

In Elixir and Erlang we use `list ++ [elem]` to append elements.


1 Answers

Kernel.length/1 will return the size of a list:

length([1,2,3]) #3

You can do this from an Ecto query using:

query = from d in Device, where: d.uuid == ^uuid, select: fragment("count(?)", d.id)
assert  Repo.all(query)== 3

In Ecto 2 you can use Repo.aggregate/4

query = from d in Device, where: d.uuid == ^uuid)
assert Repo.aggregate(query, :count, :id) == 3
like image 93
Gazler Avatar answered Oct 10 '22 03:10

Gazler