rick_and_morty 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +55 -1
- data/README.md +115 -9
- data/lib/rick_and_morty/async_stream.rb +41 -7
- data/lib/rick_and_morty/character.rb +2 -0
- data/lib/rick_and_morty/client.rb +65 -42
- data/lib/rick_and_morty/endpoint.rb +42 -12
- data/lib/rick_and_morty/episode.rb +2 -0
- data/lib/rick_and_morty/errors.rb +35 -0
- data/lib/rick_and_morty/location.rb +2 -0
- data/lib/rick_and_morty/version.rb +1 -1
- data/lib/rick_and_morty.rb +14 -11
- data/rick_and_morty.gemspec +12 -22
- metadata +12 -16
- data/.rubocop.yml +0 -17
- data/Gemfile +0 -14
- data/Gemfile.lock +0 -55
- data/Rakefile +0 -16
- data/bin/console +0 -15
- data/bin/setup +0 -8
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 0ea39537617fc666a720f16809364a9ed54e59f15f5150407675520950a5e8a5
|
|
4
|
+
data.tar.gz: f7bce16fb5140b3e656db4db5222aa8b8f648225479b49e343c31035e8c40672
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 466da94edb7dbe6c819ffff2ed77aeed87c5c4d1249af1ab04b43471082408892af0532ecea5cef4d23d504157400c761b098625de3c04ee99665e73437b57f2
|
|
7
|
+
data.tar.gz: 1b7288744a5d6e9264ad4e9cd3e471ee04a2d862cabd1a1fc25e8f061337319aedfac7e3f749fcd7d3ef3445178d69c9be034fcd4ba66b3249e7807674529b04
|
data/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,59 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project will be documented in this file.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
|
+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
|
+
|
|
1
8
|
## [Unreleased]
|
|
2
9
|
|
|
10
|
+
## [0.2.0] - 2026-12-02
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- Filters for `characters`, `locations` and `episodes` (and `Endpoint#all` /
|
|
15
|
+
`#list`). Unknown filters raise `ArgumentError`.
|
|
16
|
+
- `character`, `location` and `episode` accept an Array of ids and return an
|
|
17
|
+
Array of records.
|
|
18
|
+
- Rate-limited (`429`) requests are retried with exponential backoff or the
|
|
19
|
+
`Retry-After` delay. `RickAndMorty::RateLimitError` is raised once retries are
|
|
20
|
+
exhausted.
|
|
21
|
+
- `RickAndMorty::HTTPError` (with `#status`) as the parent of `ClientError`,
|
|
22
|
+
`ServerError`, and the new `NotFoundError` and `RateLimitError`. Error
|
|
23
|
+
messages include the API's error text.
|
|
24
|
+
- Connection timeouts, `Accept: application/json` and a
|
|
25
|
+
`rick_and_morty-ruby/<version>` User-Agent.
|
|
26
|
+
- Endpoints accept `client:` and `concurrency:` options.
|
|
27
|
+
- Test suite (Minitest, WebMock and VCR) with 100% line and branch coverage.
|
|
28
|
+
- README with usage documentation.
|
|
29
|
+
- GitHub Actions CI for Ruby 3.3, 3.4 and 4.0, plus Dependabot for Bundler and
|
|
30
|
+
GitHub Actions.
|
|
31
|
+
|
|
32
|
+
### Changed
|
|
33
|
+
|
|
34
|
+
- **Breaking:** requires Ruby 3.3 or newer.
|
|
35
|
+
- **Breaking:** `all` returns `[]` when a filter matches nothing (the API
|
|
36
|
+
answers `404`), and `list` returns `[]` past the last page.
|
|
37
|
+
- **Breaking:** an invalid JSON body raises `RickAndMorty::Error` (was `nil`),
|
|
38
|
+
and unexpected statuses such as redirects raise `RickAndMorty::HTTPError`
|
|
39
|
+
(was `nil`).
|
|
40
|
+
- **Breaking:** ids passed to `find` must be integers (or integer strings).
|
|
41
|
+
- `all` fetches pages with a bounded thread pool (2 threads by default)
|
|
42
|
+
instead of one thread per page. Results are concatenated once instead of
|
|
43
|
+
with repeated `Array#+`.
|
|
44
|
+
- `AsyncStream#sum` behaves like `Enumerable#sum` (returns the initial value
|
|
45
|
+
for empty collections); `AsyncStream#flat_map` was added.
|
|
46
|
+
- HTTPS is enabled based on the URL scheme instead of always.
|
|
47
|
+
- Development dependencies moved to the `Gemfile`; gem metadata now includes
|
|
48
|
+
the changelog and bug tracker URLs.
|
|
49
|
+
|
|
50
|
+
### Fixed
|
|
51
|
+
|
|
52
|
+
- `all` raised `TypeError` when the results fit in a single page, for example
|
|
53
|
+
`Episode.new.all` filtered to one episode.
|
|
54
|
+
- `all` spawned one thread and connection per page (41 for characters), which
|
|
55
|
+
can exceed the API rate limit and fail with `ClientError` (`429`).
|
|
56
|
+
|
|
3
57
|
## [0.1.0] - 2021-12-02
|
|
4
58
|
|
|
5
|
-
- Initial release
|
|
59
|
+
- Initial release.
|
data/README.md
CHANGED
|
@@ -1,15 +1,22 @@
|
|
|
1
1
|
# RickAndMorty
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://github.com/3zcurdia/rick_and_morty/actions/workflows/ruby.yml)
|
|
4
|
+
[](https://rubygems.org/gems/rick_and_morty)
|
|
4
5
|
|
|
5
|
-
|
|
6
|
+
A small, dependency-free Ruby client for
|
|
7
|
+
[The Rick and Morty API](https://rickandmortyapi.com): characters, locations and
|
|
8
|
+
episodes, with filtering and concurrent pagination.
|
|
9
|
+
|
|
10
|
+
## Requirements
|
|
11
|
+
|
|
12
|
+
Ruby 3.3 or newer (tested on 3.3, 3.4 and 4.0).
|
|
6
13
|
|
|
7
14
|
## Installation
|
|
8
15
|
|
|
9
16
|
Add this line to your application's Gemfile:
|
|
10
17
|
|
|
11
18
|
```ruby
|
|
12
|
-
gem
|
|
19
|
+
gem "rick_and_morty"
|
|
13
20
|
```
|
|
14
21
|
|
|
15
22
|
And then execute:
|
|
@@ -22,22 +29,121 @@ Or install it yourself as:
|
|
|
22
29
|
|
|
23
30
|
## Usage
|
|
24
31
|
|
|
25
|
-
|
|
32
|
+
Responses are parsed into `Hash`es with `Symbol` keys.
|
|
33
|
+
|
|
34
|
+
```ruby
|
|
35
|
+
require "rick_and_morty"
|
|
36
|
+
|
|
37
|
+
# Single records
|
|
38
|
+
RickAndMorty.character(1)[:name] # => "Rick Sanchez"
|
|
39
|
+
RickAndMorty.location(1)[:name] # => "Earth (C-137)"
|
|
40
|
+
RickAndMorty.episode(1)[:episode] # => "S01E01"
|
|
41
|
+
|
|
42
|
+
# Several records in one request
|
|
43
|
+
RickAndMorty.character([1, 2]).map { |c| c[:name] } # => ["Rick Sanchez", "Morty Smith"]
|
|
44
|
+
|
|
45
|
+
# Every record (all pages are fetched for you)
|
|
46
|
+
RickAndMorty.characters.size # => 826
|
|
47
|
+
RickAndMorty.locations
|
|
48
|
+
RickAndMorty.episodes
|
|
49
|
+
|
|
50
|
+
# Filtering
|
|
51
|
+
RickAndMorty.characters(name: "rick", status: "alive")
|
|
52
|
+
RickAndMorty.locations(dimension: "Dimension C-137")
|
|
53
|
+
RickAndMorty.episodes(episode: "S01")
|
|
54
|
+
RickAndMorty.characters(name: "nobody") # => []
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Available filters:
|
|
58
|
+
|
|
59
|
+
| Resource | Filters |
|
|
60
|
+
| ---------- | ------- |
|
|
61
|
+
| Characters | `name`, `status` (`alive`, `dead`, `unknown`), `species`, `type`, `gender` (`female`, `male`, `genderless`, `unknown`) |
|
|
62
|
+
| Locations | `name`, `type`, `dimension` |
|
|
63
|
+
| Episodes | `name`, `episode` (e.g. `"S01E01"` or `"S01"`) |
|
|
64
|
+
|
|
65
|
+
Unknown filters raise `ArgumentError`, because the API silently ignores them
|
|
66
|
+
and returns every record.
|
|
67
|
+
|
|
68
|
+
### Endpoints
|
|
69
|
+
|
|
70
|
+
The module methods are shortcuts for the endpoint classes, which also expose
|
|
71
|
+
single pages:
|
|
72
|
+
|
|
73
|
+
```ruby
|
|
74
|
+
characters = RickAndMorty::Character.new
|
|
75
|
+
characters.list(2) # page 2 (20 records per page)
|
|
76
|
+
characters.list(1, species: "Alien")
|
|
77
|
+
characters.all(gender: "female")
|
|
78
|
+
characters.find(1)
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
`all` fetches the first page, then the remaining pages concurrently with a
|
|
82
|
+
small, bounded thread pool (2 threads by default) and returns the results in
|
|
83
|
+
order. Configure it per endpoint:
|
|
84
|
+
|
|
85
|
+
```ruby
|
|
86
|
+
RickAndMorty::Character.new(concurrency: 4).all
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
### Rate limits and errors
|
|
90
|
+
|
|
91
|
+
The API rate-limits clients. Rate-limited (`429`) requests are retried up to 3
|
|
92
|
+
times with exponential backoff (1s, 2s, 4s), or after the delay the API sends
|
|
93
|
+
in `Retry-After`. You can tune this by injecting a client:
|
|
94
|
+
|
|
95
|
+
```ruby
|
|
96
|
+
client = RickAndMorty::Client.new(RickAndMorty::Endpoint::BASE_URL, max_retries: 5, backoff: 0.5)
|
|
97
|
+
RickAndMorty::Character.new(client: client).all
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
All errors inherit from `RickAndMorty::Error`. HTTP errors expose the response
|
|
101
|
+
`status` and include the API's error message:
|
|
102
|
+
|
|
103
|
+
| Error | When |
|
|
104
|
+
| ----- | ---- |
|
|
105
|
+
| `RickAndMorty::NotFoundError` | `404`, e.g. an unknown id |
|
|
106
|
+
| `RickAndMorty::RateLimitError` | `429` after all retries (`#retry_after`) |
|
|
107
|
+
| `RickAndMorty::ClientError` | Other `4xx` (parent of the two above) |
|
|
108
|
+
| `RickAndMorty::ServerError` | `5xx` |
|
|
109
|
+
| `RickAndMorty::HTTPError` | Any other non-2xx status (parent of all the above) |
|
|
110
|
+
|
|
111
|
+
```ruby
|
|
112
|
+
RickAndMorty.character(999_999)
|
|
113
|
+
# => raises RickAndMorty::NotFoundError, "[404] Character not found"
|
|
114
|
+
```
|
|
26
115
|
|
|
27
116
|
## Development
|
|
28
117
|
|
|
29
|
-
After checking out the repo, run `bin/setup` to install dependencies. Then
|
|
118
|
+
After checking out the repo, run `bin/setup` to install dependencies. Then run
|
|
119
|
+
`bundle exec rake` to run the tests and RuboCop. You can also run `bin/console`
|
|
120
|
+
for an interactive prompt.
|
|
121
|
+
|
|
122
|
+
Tests replay [VCR](https://github.com/vcr/vcr) cassettes stored in
|
|
123
|
+
`test/fixtures/vcr_cassettes`. Delete a cassette to re-record it against the
|
|
124
|
+
live API.
|
|
30
125
|
|
|
31
|
-
To install this gem onto your local machine, run `bundle exec rake install`. To
|
|
126
|
+
To install this gem onto your local machine, run `bundle exec rake install`. To
|
|
127
|
+
release a new version, update the version number in
|
|
128
|
+
`lib/rick_and_morty/version.rb` and the `CHANGELOG.md`, then run
|
|
129
|
+
`bundle exec rake release`, which will create a git tag for the version, push
|
|
130
|
+
git commits and the created tag, and push the `.gem` file to
|
|
131
|
+
[rubygems.org](https://rubygems.org).
|
|
32
132
|
|
|
33
133
|
## Contributing
|
|
34
134
|
|
|
35
|
-
Bug reports and pull requests are welcome on GitHub at
|
|
135
|
+
Bug reports and pull requests are welcome on GitHub at
|
|
136
|
+
https://github.com/3zcurdia/rick_and_morty. This project is intended to be a
|
|
137
|
+
safe, welcoming space for collaboration, and contributors are expected to adhere
|
|
138
|
+
to the [code of conduct](https://github.com/3zcurdia/rick_and_morty/blob/main/CODE_OF_CONDUCT.md).
|
|
36
139
|
|
|
37
140
|
## License
|
|
38
141
|
|
|
39
|
-
The gem is available as open source under the terms of the
|
|
142
|
+
The gem is available as open source under the terms of the
|
|
143
|
+
[MIT License](https://opensource.org/licenses/MIT).
|
|
40
144
|
|
|
41
145
|
## Code of Conduct
|
|
42
146
|
|
|
43
|
-
Everyone interacting in the RickAndMorty project's codebases, issue trackers,
|
|
147
|
+
Everyone interacting in the RickAndMorty project's codebases, issue trackers,
|
|
148
|
+
chat rooms and mailing lists is expected to follow the
|
|
149
|
+
[code of conduct](https://github.com/3zcurdia/rick_and_morty/blob/main/CODE_OF_CONDUCT.md).
|
|
@@ -1,23 +1,57 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
module RickAndMorty
|
|
4
|
+
# Maps over a collection using a bounded pool of threads, preserving order.
|
|
5
|
+
# Intended for I/O-bound work such as fetching pages concurrently.
|
|
4
6
|
class AsyncStream
|
|
5
|
-
|
|
7
|
+
DEFAULT_CONCURRENCY = 2
|
|
8
|
+
|
|
9
|
+
attr_reader :concurrency
|
|
10
|
+
|
|
11
|
+
def initialize(enumerable, concurrency: DEFAULT_CONCURRENCY)
|
|
12
|
+
raise ArgumentError, "concurrency must be positive" unless concurrency.to_i.positive?
|
|
13
|
+
|
|
6
14
|
@enumerable = enumerable
|
|
15
|
+
@concurrency = concurrency.to_i
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
# Returns the results of the block for every item, in the original order.
|
|
19
|
+
# The first exception raised by the block is re-raised after pending work is dropped.
|
|
20
|
+
def map(&block)
|
|
21
|
+
items = enumerable.to_a
|
|
22
|
+
results = Array.new(items.size)
|
|
23
|
+
queue = Queue.new
|
|
24
|
+
items.each_with_index { |item, index| queue << [item, index] }
|
|
25
|
+
queue.close
|
|
26
|
+
|
|
27
|
+
workers = Array.new([concurrency, items.size].min) { spawn_worker(queue, results, &block) }
|
|
28
|
+
workers.each(&:join)
|
|
29
|
+
results
|
|
7
30
|
end
|
|
8
31
|
|
|
9
|
-
def
|
|
10
|
-
|
|
11
|
-
Thread.new { yield(item) }
|
|
12
|
-
end.map(&:value)
|
|
32
|
+
def flat_map(&)
|
|
33
|
+
map(&).flatten(1)
|
|
13
34
|
end
|
|
14
35
|
|
|
15
|
-
def sum(&
|
|
16
|
-
map(&
|
|
36
|
+
def sum(init = 0, &)
|
|
37
|
+
map(&).sum(init)
|
|
17
38
|
end
|
|
18
39
|
|
|
19
40
|
private
|
|
20
41
|
|
|
21
42
|
attr_reader :enumerable
|
|
43
|
+
|
|
44
|
+
def spawn_worker(queue, results)
|
|
45
|
+
Thread.new do
|
|
46
|
+
Thread.current.report_on_exception = false
|
|
47
|
+
while (job = queue.pop)
|
|
48
|
+
item, index = job
|
|
49
|
+
results[index] = yield(item)
|
|
50
|
+
end
|
|
51
|
+
rescue StandardError
|
|
52
|
+
queue.clear
|
|
53
|
+
raise
|
|
54
|
+
end
|
|
55
|
+
end
|
|
22
56
|
end
|
|
23
57
|
end
|
|
@@ -2,71 +2,94 @@
|
|
|
2
2
|
|
|
3
3
|
require "json"
|
|
4
4
|
require "net/http"
|
|
5
|
+
require "uri"
|
|
5
6
|
|
|
6
7
|
module RickAndMorty
|
|
8
|
+
# Minimal JSON HTTP client for the API.
|
|
7
9
|
class Client
|
|
8
|
-
|
|
10
|
+
OPEN_TIMEOUT = 10
|
|
11
|
+
READ_TIMEOUT = 30
|
|
12
|
+
MAX_RETRIES = 3
|
|
13
|
+
BACKOFF = 1.0
|
|
14
|
+
|
|
15
|
+
# Checked in order, so specific statuses must come before their families.
|
|
16
|
+
ERROR_CLASSES = {
|
|
17
|
+
Net::HTTPNotFound => NotFoundError,
|
|
18
|
+
Net::HTTPClientError => ClientError,
|
|
19
|
+
Net::HTTPServerError => ServerError
|
|
20
|
+
}.freeze
|
|
21
|
+
|
|
22
|
+
attr_reader :base_url, :max_retries, :backoff
|
|
23
|
+
|
|
24
|
+
# max_retries: how many times a rate-limited (429) request is retried.
|
|
25
|
+
# backoff: base delay in seconds, doubled on every retry unless the API sends Retry-After.
|
|
26
|
+
def initialize(base_url, max_retries: MAX_RETRIES, backoff: BACKOFF, sleeper: Kernel.method(:sleep))
|
|
9
27
|
@base_url = base_url
|
|
28
|
+
@max_retries = max_retries
|
|
29
|
+
@backoff = backoff
|
|
30
|
+
@sleeper = sleeper
|
|
10
31
|
end
|
|
11
32
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
33
|
+
# Performs a GET request and returns the parsed JSON body (with Symbol keys).
|
|
34
|
+
def get(path, query: {})
|
|
35
|
+
uri = build_uri(path, query)
|
|
36
|
+
attempt = 0
|
|
37
|
+
begin
|
|
38
|
+
request(uri)
|
|
39
|
+
rescue RateLimitError => e
|
|
40
|
+
raise if attempt >= max_retries
|
|
41
|
+
|
|
42
|
+
attempt += 1
|
|
43
|
+
@sleeper.call(e.retry_after || (backoff * (2**(attempt - 1))))
|
|
44
|
+
retry
|
|
15
45
|
end
|
|
16
46
|
end
|
|
17
47
|
|
|
18
|
-
# def post(path, data = {})
|
|
19
|
-
# request(path) do |uri|
|
|
20
|
-
# Net::HTTP::Post.new(uri)
|
|
21
|
-
# end
|
|
22
|
-
# end
|
|
23
|
-
#
|
|
24
|
-
# def put(path, data = {})
|
|
25
|
-
# request(path) do |uri|
|
|
26
|
-
# Net::HTTP::Put.new(uri)
|
|
27
|
-
# end
|
|
28
|
-
# end
|
|
29
|
-
#
|
|
30
|
-
# def delete(path)
|
|
31
|
-
# request(path) do |uri|
|
|
32
|
-
# Net::HTTP::Delete.new(uri)
|
|
33
|
-
# end
|
|
34
|
-
# end
|
|
35
|
-
|
|
36
48
|
private
|
|
37
49
|
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
Net::HTTP.start(uri.host, uri.port, use_ssl:
|
|
43
|
-
|
|
50
|
+
def request(uri)
|
|
51
|
+
request = Net::HTTP::Get.new(uri)
|
|
52
|
+
request["Accept"] = "application/json"
|
|
53
|
+
request["User-Agent"] = "rick_and_morty-ruby/#{VERSION}"
|
|
54
|
+
Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https",
|
|
55
|
+
open_timeout: OPEN_TIMEOUT, read_timeout: READ_TIMEOUT) do |http|
|
|
44
56
|
handle(http.request(request))
|
|
45
57
|
end
|
|
46
58
|
end
|
|
47
59
|
|
|
48
|
-
def handle(
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
60
|
+
def handle(response)
|
|
61
|
+
return parse_json(response.body) if response.is_a?(Net::HTTPSuccess)
|
|
62
|
+
raise rate_limit_error(response) if response.is_a?(Net::HTTPTooManyRequests)
|
|
63
|
+
|
|
64
|
+
error_class = ERROR_CLASSES.find { |status_class, _| response.is_a?(status_class) }&.last || HTTPError
|
|
65
|
+
raise error_class.new(error_message(response), status: response.code)
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
def rate_limit_error(response)
|
|
69
|
+
retry_after = Float(response["Retry-After"], exception: false)
|
|
70
|
+
RateLimitError.new(error_message(response), retry_after:)
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
def error_message(response)
|
|
74
|
+
parsed = begin
|
|
75
|
+
JSON.parse(response.body.to_s)
|
|
76
|
+
rescue JSON::ParserError
|
|
77
|
+
nil
|
|
56
78
|
end
|
|
79
|
+
detail = parsed["error"] if parsed.is_a?(Hash)
|
|
80
|
+
["[#{response.code}]", detail || response.message].compact.join(" ")
|
|
57
81
|
end
|
|
58
82
|
|
|
59
83
|
def parse_json(content)
|
|
60
84
|
JSON.parse(content, symbolize_names: true)
|
|
61
|
-
rescue JSON::ParserError
|
|
62
|
-
|
|
85
|
+
rescue JSON::ParserError => e
|
|
86
|
+
raise Error, "invalid JSON response: #{e.message}"
|
|
63
87
|
end
|
|
64
88
|
|
|
65
|
-
def build_uri(path,
|
|
66
|
-
query_items = args.fetch(:query, {}).compact
|
|
67
|
-
|
|
89
|
+
def build_uri(path, query)
|
|
68
90
|
uri = URI.join(base_url, path)
|
|
69
|
-
|
|
91
|
+
params = query.compact
|
|
92
|
+
uri.query = URI.encode_www_form(params) unless params.empty?
|
|
70
93
|
uri
|
|
71
94
|
end
|
|
72
95
|
end
|
|
@@ -1,33 +1,63 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
module RickAndMorty
|
|
4
|
+
# Base class for the API resources (character, location and episode).
|
|
4
5
|
class Endpoint
|
|
5
|
-
|
|
6
|
-
|
|
6
|
+
BASE_URL = "https://rickandmortyapi.com/api/"
|
|
7
|
+
FILTERS = [].freeze
|
|
8
|
+
|
|
9
|
+
attr_reader :concurrency
|
|
10
|
+
|
|
11
|
+
def initialize(client: Client.new(BASE_URL), concurrency: AsyncStream::DEFAULT_CONCURRENCY)
|
|
12
|
+
@client = client
|
|
13
|
+
@concurrency = concurrency
|
|
7
14
|
end
|
|
8
15
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
16
|
+
# Fetches every page of the resource, matching the optional filters.
|
|
17
|
+
# Returns an empty Array when nothing matches.
|
|
18
|
+
def all(**filters)
|
|
19
|
+
first_page = fetch_page(nil, filters)
|
|
20
|
+
return [] unless first_page
|
|
21
|
+
|
|
22
|
+
pages = first_page.dig(:info, :pages).to_i
|
|
23
|
+
first_page[:results] + AsyncStream.new(2..pages, concurrency:).flat_map { |page| list(page, **filters) }
|
|
15
24
|
end
|
|
16
25
|
|
|
17
|
-
|
|
18
|
-
|
|
26
|
+
# Fetches a single page of results (20 items per page).
|
|
27
|
+
def list(page = nil, **filters)
|
|
28
|
+
fetch_page(page, filters)&.fetch(:results) || []
|
|
19
29
|
end
|
|
20
30
|
|
|
31
|
+
# Finds a record by id, or an Array of records when given an Array of ids.
|
|
21
32
|
def find(id)
|
|
22
|
-
client.get("#{endpoint_name}/#{id}")
|
|
33
|
+
return client.get("#{endpoint_name}/#{Integer(id)}") unless id.is_a?(Array)
|
|
34
|
+
return [] if id.empty?
|
|
35
|
+
|
|
36
|
+
result = client.get("#{endpoint_name}/#{id.map { |item| Integer(item) }.join(",")}")
|
|
37
|
+
result.is_a?(Array) ? result : [result]
|
|
23
38
|
end
|
|
24
39
|
|
|
25
40
|
private
|
|
26
41
|
|
|
27
42
|
attr_reader :client
|
|
28
43
|
|
|
44
|
+
def fetch_page(page, filters)
|
|
45
|
+
validate_filters!(filters)
|
|
46
|
+
client.get(endpoint_name, query: { page:, **filters })
|
|
47
|
+
rescue NotFoundError
|
|
48
|
+
nil
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
def validate_filters!(filters)
|
|
52
|
+
unknown = filters.keys - self.class::FILTERS
|
|
53
|
+
return if unknown.empty?
|
|
54
|
+
|
|
55
|
+
raise ArgumentError, "unknown filter(s) #{unknown.map(&:inspect).join(", ")} for #{endpoint_name}; " \
|
|
56
|
+
"valid filters: #{self.class::FILTERS.map(&:inspect).join(", ")}"
|
|
57
|
+
end
|
|
58
|
+
|
|
29
59
|
def endpoint_name
|
|
30
|
-
@endpoint_name ||= self.class.name.split("::")
|
|
60
|
+
@endpoint_name ||= self.class.name.split("::").last.downcase
|
|
31
61
|
end
|
|
32
62
|
end
|
|
33
63
|
end
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module RickAndMorty
|
|
4
|
+
# Base class for every error raised by this gem.
|
|
5
|
+
class Error < StandardError; end
|
|
6
|
+
|
|
7
|
+
# Raised when the API answers with an unexpected HTTP status.
|
|
8
|
+
class HTTPError < Error
|
|
9
|
+
attr_reader :status
|
|
10
|
+
|
|
11
|
+
def initialize(message = nil, status: nil)
|
|
12
|
+
@status = status&.to_i
|
|
13
|
+
super(message)
|
|
14
|
+
end
|
|
15
|
+
end
|
|
16
|
+
|
|
17
|
+
# Raised on 4xx responses.
|
|
18
|
+
class ClientError < HTTPError; end
|
|
19
|
+
|
|
20
|
+
# Raised on 404 responses (unknown id).
|
|
21
|
+
class NotFoundError < ClientError; end
|
|
22
|
+
|
|
23
|
+
# Raised on 429 responses once the client has exhausted its retries.
|
|
24
|
+
class RateLimitError < ClientError
|
|
25
|
+
attr_reader :retry_after
|
|
26
|
+
|
|
27
|
+
def initialize(message = nil, status: 429, retry_after: nil)
|
|
28
|
+
@retry_after = retry_after
|
|
29
|
+
super(message, status:)
|
|
30
|
+
end
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
# Raised on 5xx responses.
|
|
34
|
+
class ServerError < HTTPError; end
|
|
35
|
+
end
|
data/lib/rick_and_morty.rb
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
-
require "json"
|
|
4
3
|
require_relative "rick_and_morty/version"
|
|
4
|
+
require_relative "rick_and_morty/errors"
|
|
5
5
|
require_relative "rick_and_morty/async_stream"
|
|
6
6
|
require_relative "rick_and_morty/client"
|
|
7
7
|
require_relative "rick_and_morty/endpoint"
|
|
@@ -9,31 +9,34 @@ require_relative "rick_and_morty/character"
|
|
|
9
9
|
require_relative "rick_and_morty/location"
|
|
10
10
|
require_relative "rick_and_morty/episode"
|
|
11
11
|
|
|
12
|
+
# Ruby client for The Rick and Morty API (https://rickandmortyapi.com).
|
|
12
13
|
module RickAndMorty
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
def self.characters
|
|
18
|
-
Character.new.all
|
|
14
|
+
# All characters, optionally filtered by name, status, species, type or gender.
|
|
15
|
+
def self.characters(**)
|
|
16
|
+
Character.new.all(**)
|
|
19
17
|
end
|
|
20
18
|
|
|
19
|
+
# A character by id, or an Array of characters when given an Array of ids.
|
|
21
20
|
def self.character(id)
|
|
22
21
|
Character.new.find(id)
|
|
23
22
|
end
|
|
24
23
|
|
|
25
|
-
|
|
26
|
-
|
|
24
|
+
# All locations, optionally filtered by name, type or dimension.
|
|
25
|
+
def self.locations(**)
|
|
26
|
+
Location.new.all(**)
|
|
27
27
|
end
|
|
28
28
|
|
|
29
|
+
# A location by id, or an Array of locations when given an Array of ids.
|
|
29
30
|
def self.location(id)
|
|
30
31
|
Location.new.find(id)
|
|
31
32
|
end
|
|
32
33
|
|
|
33
|
-
|
|
34
|
-
|
|
34
|
+
# All episodes, optionally filtered by name or episode code (e.g. "S01E01").
|
|
35
|
+
def self.episodes(**)
|
|
36
|
+
Episode.new.all(**)
|
|
35
37
|
end
|
|
36
38
|
|
|
39
|
+
# An episode by id, or an Array of episodes when given an Array of ids.
|
|
37
40
|
def self.episode(id)
|
|
38
41
|
Episode.new.find(id)
|
|
39
42
|
end
|
data/rick_and_morty.gemspec
CHANGED
|
@@ -5,39 +5,29 @@ require_relative "lib/rick_and_morty/version"
|
|
|
5
5
|
Gem::Specification.new do |spec|
|
|
6
6
|
spec.name = "rick_and_morty"
|
|
7
7
|
spec.version = RickAndMorty::VERSION
|
|
8
|
-
spec.authors = ["Luis Ezcurdia"]
|
|
8
|
+
spec.authors = ["Luis Ezcurdia Razo"]
|
|
9
9
|
spec.email = ["ing.ezcurdia@gmail.com"]
|
|
10
|
-
|
|
11
|
-
spec.summary = "Rick and Morty Api wrapper"
|
|
12
|
-
spec.description = "Rick and Morty Api wrapper."
|
|
13
|
-
spec.homepage = "https://github.com/3zcurdia/rick_and_morty"
|
|
14
10
|
spec.license = "MIT"
|
|
15
|
-
spec.required_ruby_version = ">= 2.6.0"
|
|
16
11
|
|
|
17
|
-
|
|
12
|
+
spec.summary = "Rick and Morty API wrapper"
|
|
13
|
+
spec.description = "A dependency-free Ruby client for The Rick and Morty API (https://rickandmortyapi.com): " \
|
|
14
|
+
"characters, locations and episodes with filtering and concurrent pagination."
|
|
15
|
+
spec.homepage = "https://github.com/3zcurdia/rick_and_morty"
|
|
16
|
+
spec.required_ruby_version = ">= 3.3"
|
|
18
17
|
|
|
19
|
-
spec.metadata["
|
|
20
|
-
spec.metadata["
|
|
21
|
-
|
|
18
|
+
spec.metadata["source_code_uri"] = spec.homepage
|
|
19
|
+
spec.metadata["changelog_uri"] = "#{spec.homepage}/blob/main/CHANGELOG.md"
|
|
20
|
+
spec.metadata["bug_tracker_uri"] = "#{spec.homepage}/issues"
|
|
21
|
+
spec.metadata["rubygems_mfa_required"] = "true"
|
|
22
22
|
|
|
23
23
|
# Specify which files should be added to the gem when it is released.
|
|
24
24
|
# The `git ls-files -z` loads the files in the RubyGem that have been added into git.
|
|
25
|
-
spec.files = Dir.chdir(
|
|
25
|
+
spec.files = Dir.chdir(__dir__) do
|
|
26
26
|
`git ls-files -z`.split("\x0").reject do |f|
|
|
27
|
-
|
|
27
|
+
f.match(%r{\A(?:(?:bin|test|spec|features)/|\.(?:git|github|rubocop)|Gemfile|Rakefile|mise\.toml|AGENTS\.md)})
|
|
28
28
|
end
|
|
29
29
|
end
|
|
30
30
|
spec.bindir = "exe"
|
|
31
31
|
spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
|
|
32
32
|
spec.require_paths = ["lib"]
|
|
33
|
-
|
|
34
|
-
# Uncomment to register a new dependency of your gem
|
|
35
|
-
# spec.add_dependency "example-gem", "~> 1.0"
|
|
36
|
-
# spec.add_development_dependency "vcr", "~> 6.0"
|
|
37
|
-
|
|
38
|
-
# For more information and examples about making a new gem, checkout our
|
|
39
|
-
# guide at: https://bundler.io/guides/creating_gem.html
|
|
40
|
-
spec.metadata = {
|
|
41
|
-
"rubygems_mfa_required" => "true"
|
|
42
|
-
}
|
|
43
33
|
end
|
metadata
CHANGED
|
@@ -1,38 +1,33 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: rick_and_morty
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.
|
|
4
|
+
version: 0.2.0
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
|
-
- Luis Ezcurdia
|
|
8
|
-
autorequire:
|
|
7
|
+
- Luis Ezcurdia Razo
|
|
9
8
|
bindir: exe
|
|
10
9
|
cert_chain: []
|
|
11
|
-
date:
|
|
10
|
+
date: 1980-01-02 00:00:00.000000000 Z
|
|
12
11
|
dependencies: []
|
|
13
|
-
description: Rick and Morty
|
|
12
|
+
description: 'A dependency-free Ruby client for The Rick and Morty API (https://rickandmortyapi.com):
|
|
13
|
+
characters, locations and episodes with filtering and concurrent pagination.'
|
|
14
14
|
email:
|
|
15
15
|
- ing.ezcurdia@gmail.com
|
|
16
16
|
executables: []
|
|
17
17
|
extensions: []
|
|
18
18
|
extra_rdoc_files: []
|
|
19
19
|
files:
|
|
20
|
-
- ".rubocop.yml"
|
|
21
20
|
- CHANGELOG.md
|
|
22
21
|
- CODE_OF_CONDUCT.md
|
|
23
|
-
- Gemfile
|
|
24
|
-
- Gemfile.lock
|
|
25
22
|
- LICENSE.txt
|
|
26
23
|
- README.md
|
|
27
|
-
- Rakefile
|
|
28
|
-
- bin/console
|
|
29
|
-
- bin/setup
|
|
30
24
|
- lib/rick_and_morty.rb
|
|
31
25
|
- lib/rick_and_morty/async_stream.rb
|
|
32
26
|
- lib/rick_and_morty/character.rb
|
|
33
27
|
- lib/rick_and_morty/client.rb
|
|
34
28
|
- lib/rick_and_morty/endpoint.rb
|
|
35
29
|
- lib/rick_and_morty/episode.rb
|
|
30
|
+
- lib/rick_and_morty/errors.rb
|
|
36
31
|
- lib/rick_and_morty/location.rb
|
|
37
32
|
- lib/rick_and_morty/version.rb
|
|
38
33
|
- rick_and_morty.gemspec
|
|
@@ -40,8 +35,10 @@ homepage: https://github.com/3zcurdia/rick_and_morty
|
|
|
40
35
|
licenses:
|
|
41
36
|
- MIT
|
|
42
37
|
metadata:
|
|
38
|
+
source_code_uri: https://github.com/3zcurdia/rick_and_morty
|
|
39
|
+
changelog_uri: https://github.com/3zcurdia/rick_and_morty/blob/main/CHANGELOG.md
|
|
40
|
+
bug_tracker_uri: https://github.com/3zcurdia/rick_and_morty/issues
|
|
43
41
|
rubygems_mfa_required: 'true'
|
|
44
|
-
post_install_message:
|
|
45
42
|
rdoc_options: []
|
|
46
43
|
require_paths:
|
|
47
44
|
- lib
|
|
@@ -49,15 +46,14 @@ required_ruby_version: !ruby/object:Gem::Requirement
|
|
|
49
46
|
requirements:
|
|
50
47
|
- - ">="
|
|
51
48
|
- !ruby/object:Gem::Version
|
|
52
|
-
version:
|
|
49
|
+
version: '3.3'
|
|
53
50
|
required_rubygems_version: !ruby/object:Gem::Requirement
|
|
54
51
|
requirements:
|
|
55
52
|
- - ">="
|
|
56
53
|
- !ruby/object:Gem::Version
|
|
57
54
|
version: '0'
|
|
58
55
|
requirements: []
|
|
59
|
-
rubygems_version:
|
|
60
|
-
signing_key:
|
|
56
|
+
rubygems_version: 4.0.20
|
|
61
57
|
specification_version: 4
|
|
62
|
-
summary: Rick and Morty
|
|
58
|
+
summary: Rick and Morty API wrapper
|
|
63
59
|
test_files: []
|
data/.rubocop.yml
DELETED
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
AllCops:
|
|
2
|
-
TargetRubyVersion: 2.6
|
|
3
|
-
NewCops: enable
|
|
4
|
-
|
|
5
|
-
Style/StringLiterals:
|
|
6
|
-
Enabled: true
|
|
7
|
-
EnforcedStyle: double_quotes
|
|
8
|
-
|
|
9
|
-
Style/StringLiteralsInInterpolation:
|
|
10
|
-
Enabled: true
|
|
11
|
-
EnforcedStyle: double_quotes
|
|
12
|
-
|
|
13
|
-
Style/Documentation:
|
|
14
|
-
Enabled: false
|
|
15
|
-
|
|
16
|
-
Layout/LineLength:
|
|
17
|
-
Max: 120
|
data/Gemfile
DELETED
data/Gemfile.lock
DELETED
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
PATH
|
|
2
|
-
remote: .
|
|
3
|
-
specs:
|
|
4
|
-
rick_and_morty (0.1.0)
|
|
5
|
-
|
|
6
|
-
GEM
|
|
7
|
-
remote: https://rubygems.org/
|
|
8
|
-
specs:
|
|
9
|
-
addressable (2.8.0)
|
|
10
|
-
public_suffix (>= 2.0.2, < 5.0)
|
|
11
|
-
ast (2.4.2)
|
|
12
|
-
crack (0.4.5)
|
|
13
|
-
rexml
|
|
14
|
-
hashdiff (1.0.1)
|
|
15
|
-
minitest (5.14.4)
|
|
16
|
-
parallel (1.21.0)
|
|
17
|
-
parser (3.0.3.1)
|
|
18
|
-
ast (~> 2.4.1)
|
|
19
|
-
public_suffix (4.0.6)
|
|
20
|
-
rainbow (3.0.0)
|
|
21
|
-
rake (13.0.6)
|
|
22
|
-
regexp_parser (2.1.1)
|
|
23
|
-
rexml (3.2.5)
|
|
24
|
-
rubocop (1.23.0)
|
|
25
|
-
parallel (~> 1.10)
|
|
26
|
-
parser (>= 3.0.0.0)
|
|
27
|
-
rainbow (>= 2.2.2, < 4.0)
|
|
28
|
-
regexp_parser (>= 1.8, < 3.0)
|
|
29
|
-
rexml
|
|
30
|
-
rubocop-ast (>= 1.12.0, < 2.0)
|
|
31
|
-
ruby-progressbar (~> 1.7)
|
|
32
|
-
unicode-display_width (>= 1.4.0, < 3.0)
|
|
33
|
-
rubocop-ast (1.14.0)
|
|
34
|
-
parser (>= 3.0.1.1)
|
|
35
|
-
ruby-progressbar (1.11.0)
|
|
36
|
-
unicode-display_width (2.1.0)
|
|
37
|
-
vcr (6.0.0)
|
|
38
|
-
webmock (3.14.0)
|
|
39
|
-
addressable (>= 2.8.0)
|
|
40
|
-
crack (>= 0.3.2)
|
|
41
|
-
hashdiff (>= 0.4.0, < 2.0.0)
|
|
42
|
-
|
|
43
|
-
PLATFORMS
|
|
44
|
-
arm64-darwin-21
|
|
45
|
-
|
|
46
|
-
DEPENDENCIES
|
|
47
|
-
minitest (~> 5.0)
|
|
48
|
-
rake (~> 13.0)
|
|
49
|
-
rick_and_morty!
|
|
50
|
-
rubocop (~> 1.21)
|
|
51
|
-
vcr
|
|
52
|
-
webmock
|
|
53
|
-
|
|
54
|
-
BUNDLED WITH
|
|
55
|
-
2.2.32
|
data/Rakefile
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
# frozen_string_literal: true
|
|
2
|
-
|
|
3
|
-
require "bundler/gem_tasks"
|
|
4
|
-
require "rake/testtask"
|
|
5
|
-
|
|
6
|
-
Rake::TestTask.new(:test) do |t|
|
|
7
|
-
t.libs << "test"
|
|
8
|
-
t.libs << "lib"
|
|
9
|
-
t.test_files = FileList["test/**/*_test.rb"]
|
|
10
|
-
end
|
|
11
|
-
|
|
12
|
-
require "rubocop/rake_task"
|
|
13
|
-
|
|
14
|
-
RuboCop::RakeTask.new
|
|
15
|
-
|
|
16
|
-
task default: %i[test rubocop]
|
data/bin/console
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env ruby
|
|
2
|
-
# frozen_string_literal: true
|
|
3
|
-
|
|
4
|
-
require "bundler/setup"
|
|
5
|
-
require "rick_and_morty"
|
|
6
|
-
|
|
7
|
-
# You can add fixtures and/or initialization code here to make experimenting
|
|
8
|
-
# with your gem easier. You can also use a different console, if you like.
|
|
9
|
-
|
|
10
|
-
# (If you use this, don't forget to add pry to your Gemfile!)
|
|
11
|
-
# require "pry"
|
|
12
|
-
# Pry.start
|
|
13
|
-
|
|
14
|
-
require "irb"
|
|
15
|
-
IRB.start(__FILE__)
|