Skip to content

Commit

Permalink
Add Mayo.List module and add atom, list validation methods to Mayo.Any
Browse files Browse the repository at this point in the history
  • Loading branch information
tommy351 committed Jul 3, 2016
1 parent 02fdfa8 commit ba9cd86
Show file tree
Hide file tree
Showing 3 changed files with 96 additions and 0 deletions.
34 changes: 34 additions & 0 deletions lib/mayo/any.ex
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,40 @@ defmodule Mayo.Any do
}}
end

@doc """
Checks if the value is an atom.
iex> Mayo.Any.atom(:test)
:test
iex> Mayo.Any.atom("test")
{:error, %Mayo.Error{type: "any.atom"}}
"""
def atom(value) when is_atom(value) or is_nil(value), do: value

def atom(_) do
{:error, %Mayo.Error{
type: "any.atom"
}}
end

@doc """
Checks if the value is a list.
iex> Mayo.Any.list([1, 2, 3])
[1, 2, 3]
iex> Mayo.Any.list("test")
{:error, %Mayo.Error{type: "any.list"}}
"""
def list(value) when is_list(value) or is_nil(value), do: value

def list(_) do
{:error, %Mayo.Error{
type: "any.list"
}}
end

@doc """
Forbids any value except `nil`.
Expand Down
58 changes: 58 additions & 0 deletions lib/mayo/list.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
defmodule Mayo.List do
@doc """
Checks the minimum number of elements in the list.
iex> Mayo.List.min([1, 2, 3], 3)
[1, 2, 3]
iex> Mayo.List.min([], 3)
{:error, %Mayo.Error{type: "list.min"}}
"""
def min(value, len) when is_list(value) and length(value) == len, do: value

def min(value, _) when is_list(value) do
{:error, %Mayo.Error{
type: "list.min"
}}
end

def min(value, _), do: value

@doc """
Checks the maximum number of elements in the list.
iex> Mayo.List.max([1, 2, 3], 3)
[1, 2, 3]
iex> Mayo.List.max([1, 2, 3, 4], 3)
{:error, %Mayo.Error{type: "list.max"}}
"""
def max(value, len) when is_list(value) and length(value) == len, do: value

def max(value, _) when is_list(value) do
{:error, %Mayo.Error{
type: "list.max"
}}
end

def max(value, _), do: value

@doc """
Checks the number of elements in the list.
iex> Mayo.List.length([1, 2, 3], 3)
[1, 2, 3]
iex> Mayo.List.length([1], 3)
{:error, %Mayo.Error{type: "list.length"}}
"""
def length(value, len) when is_list(value) and length(value) == len, do: value

def length(value, _) when is_list(value) do
{:error, %Mayo.Error{
type: "list.length"
}}
end

def length(value, _), do: value
end
4 changes: 4 additions & 0 deletions test/mayo/list_test.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
defmodule Mayo.ListTest do
use ExUnit.Case
doctest Mayo.List
end

0 comments on commit ba9cd86

Please sign in to comment.