122 lines
2.7 KiB
Elixir
122 lines
2.7 KiB
Elixir
defmodule Helpers do
|
|
def do!(thing) do
|
|
case thing do
|
|
{:ok, answer} -> answer
|
|
{_, _error} -> nil
|
|
end
|
|
end
|
|
|
|
def pluralize(qty, word) do
|
|
plural =
|
|
if qty == 1 do
|
|
"#{word}"
|
|
else
|
|
"#{word}s"
|
|
end
|
|
|
|
"#{qty} #{plural}"
|
|
end
|
|
|
|
def parse_date(str), do: str |> to_string |> Timex.parse("%Y-%m-%d", :strftime)
|
|
|
|
def valid_phone() do
|
|
Regex.compile!("^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$")
|
|
end
|
|
|
|
def format_phone(str) do
|
|
str
|
|
|> String.replace(" ", "")
|
|
|> String.replace("-", "")
|
|
|> String.replace(".", "")
|
|
|> String.replace(~r/[\(\)]/, "")
|
|
end
|
|
|
|
def to_slug(nil), do: nil
|
|
|
|
def to_slug(name) when is_binary(name) do
|
|
name
|
|
|> String.replace(" ", "-")
|
|
|> String.downcase()
|
|
end
|
|
|
|
def to_slug(obj), do: to_slug(obj.name)
|
|
|
|
def from_slug(name) do
|
|
name
|
|
|> String.replace("-", " ")
|
|
|> String.split(" ")
|
|
|> Enum.map(&:string.titlecase/1)
|
|
|> Enum.join(" ")
|
|
end
|
|
|
|
def birthday(friend) do
|
|
this_year =
|
|
Date.utc_today()
|
|
|> Calendar.strftime("%Y")
|
|
|> String.to_integer()
|
|
|
|
next_birthday =
|
|
friend.born
|
|
|> Calendar.strftime("%m-%d")
|
|
|
|
next_birthdate =
|
|
"#{this_year}-#{next_birthday}"
|
|
|> Date.from_iso8601!()
|
|
|
|
if next_birthdate |> Date.diff(Date.utc_today()) < 0 do
|
|
"#{this_year + 1}-#{next_birthday}" |> Date.from_iso8601!()
|
|
else
|
|
next_birthdate
|
|
end
|
|
end
|
|
|
|
def time_until_birthday(friend) do
|
|
birthday(friend) |> Date.diff(Date.utc_today())
|
|
end
|
|
|
|
def relations(friend, include_self \\ false) do
|
|
list =
|
|
[friend.relationships, friend.reverse_relationships]
|
|
|> List.flatten()
|
|
|> Enum.dedup()
|
|
|
|
if include_self, do: list, else: list |> Enum.filter(&(&1.id != friend.id))
|
|
end
|
|
|
|
def relation(friend, friend2) do
|
|
Friends.Relationship.get(friend, friend2)
|
|
end
|
|
|
|
def events(%Friends.Relationship{} = relationship) do
|
|
relationship.events
|
|
end
|
|
|
|
def random_string(length) do
|
|
:crypto.strong_rand_bytes(length)
|
|
|> Base.url_encode64()
|
|
|> binary_part(0, length)
|
|
|> String.replace(~r/-/, "")
|
|
end
|
|
|
|
def unique_friend_email, do: "user#{System.unique_integer()}@example.com"
|
|
def valid_friend_name, do: "#{random_string(5)} Mc#{random_string(5)}"
|
|
def valid_friend_phone, do: "+1 (917) 624 2939" |> Helpers.format_phone()
|
|
def valid_friend_birthdate, do: ~D"1990-05-05"
|
|
|
|
def valid_friend_attributes(attrs \\ %{}) do
|
|
Enum.into(attrs, %{
|
|
id: nil,
|
|
name: valid_friend_name(),
|
|
phone: valid_friend_phone(),
|
|
born: valid_friend_birthdate(),
|
|
email: unique_friend_email()
|
|
})
|
|
end
|
|
|
|
def friend_fixture(attrs \\ %{}) do
|
|
attrs
|
|
|> valid_friend_attributes()
|
|
|> Friends.Friend.create_or_update()
|
|
end
|
|
end
|