-
Notifications
You must be signed in to change notification settings - Fork 63
/
quotes.ex
96 lines (87 loc) 路 2.21 KB
/
quotes.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
defmodule Quotes do
@moduledoc """
Documentation for Quotes.
"""
@doc """
`parse_json` returns a list of maps containing quotes. <br />
The format returned is:
```elixir
[
%{
"author" => "Albert Einstein",
"text" => "Once we accept our limits, we go beyond them."
},
%{
"author" => "Peter Drucker",
"source" => "https://www.goodreads.com/quotes/784267",
"tags" => "time, management",
"text" => "Until we can manage time, we can manage nothing else."
}
%{...},
...
]
```
All quotes MUST have an `author` and `text` field. <br />
Some quotes have `tags` and `source`,
please help to expand/verify others. <br />
see: https://github.com/nelsonic/quotes#contributing
"""
def parse_json do
{:ok, cwd} = File.cwd
# we need this cd to locate the file in /deps
case cwd =~ "/quotes" do
true ->
File.read!("quotes.json") |> Jason.decode!()
# coveralls-ignore-start
false -> # temporarily cd into deps/quotes dir and read quotes.json file:
File.cd!("deps/quotes")
data = File.read!("quotes.json")
|> Jason.decode!()
# chnge back into the root directory
File.cd!("../..")
data # return the decoded (parsed) JSON data
# coveralls-ignore-stop
end
end
@doc """
`random` returns a random quote. <br />
e.g:
```elixir
%{
"author" => "Peter Drucker",
"source" => "https://www.goodreads.com/quotes/784267",
"tags" => "time, management",
"text" => "Until we can manage time, we can manage nothing else."
}
```
"""
def random do
parse_json()
|> Enum.random()
end
@doc """
`random_by_tag` returns a random quote for the chosen tag/keyword.
e.g:
```elixir
iex> Quotes.random_by_tag("time")
%{
"author" => "Leo Tolstoy",
"text" => "The two most powerful warriors are patience and time."
}
```
"""
def random_by_tag(tag) do
# IO.inspect(tag)
parse_json()
|> Enum.map(fn q ->
# IO.inspect(q)
if ( !is_nil(q["text"]) && q["text"] =~ tag )
|| ( !is_nil(q["tags"]) && q["tags"] =~ tag )
do
q
end
end)
|> Enum.filter(& !is_nil(&1))
|> Enum.random()
end
end