ipregistry 1.0.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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: ac4136cfc952e92a327b985aa8d1b83d2903ed9ab1db81f123bc484a0dc3f038
4
+ data.tar.gz: ba13012fb035c71eece4bcaedf159e1e49b6ec0291714ec89f506164de63585b
5
+ SHA512:
6
+ metadata.gz: 4818fd403064398abe2a8741b6e08f68812b0e981dea244e6e677153198545b03625464eadbf355388b3c3862eda28d215756518a6bbf365f95f756b3652949b
7
+ data.tar.gz: 603353339ff653723b71d474219daaf0a5cd7957e4cc035cd799850498db64acd33d55657123a0c87e81a64c4fa519420dcc9cac27c3ab91a79d50041c5b106c
data/CHANGELOG.md ADDED
@@ -0,0 +1,35 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ ## [1.0.0] - 2026-07-04
11
+ ### Added
12
+ - Initial release of the official Ruby client library for the Ipregistry API.
13
+ - `Client#lookup` for single IP address lookups, `Client#lookup_origin` for origin (requester) lookups returning
14
+ parsed User-Agent data, and `Client#batch_lookup` for resolving many IP addresses at once. Batch lookups
15
+ transparently split arrays larger than the API's 1024-address limit into concurrently dispatched sub-requests
16
+ (configurable via `max_batch_size:` and `batch_concurrency:`) and reassemble results in input order.
17
+ - `Client#parse_user_agents` for parsing raw User-Agent strings into structured data.
18
+ - Batch results (`BatchResponse`) expose per-entry success or failure through `Result` objects, are `Enumerable`,
19
+ and support pattern matching.
20
+ - Nil-safe response models: nested sections are always present, so chained access such as
21
+ `info.location.country.name` never raises; boolean fields are exposed as predicates (`security.vpn?`).
22
+ - Optional in-memory caching (`Cache::Memory`) with LRU eviction and TTL, plus a duck-typed interface for custom
23
+ backends. Caching is disabled by default; origin lookups are never cached and batch lookups reuse cached entries.
24
+ - Automatic retries with exponential backoff for transient network errors and 5xx responses, honoring the
25
+ `Retry-After` header. Retries on 429 Too Many Requests are disabled by default.
26
+ - Typed errors rooted at `Ipregistry::Error`: every documented API error code maps to a dedicated `ApiError`
27
+ subclass (e.g. `InvalidApiKeyError`, `InsufficientCreditsError`), and client-side failures raise
28
+ `ConnectionError`, `TimeoutError`, or `ParseError`.
29
+ - `Ipregistry.bot?` helper to skip lookups for crawler traffic.
30
+ - Offline unit/behavior specs using WebMock, plus opt-in live system specs in `spec/system` (run with
31
+ `IPREGISTRY_API_KEY` set).
32
+ - Zero runtime dependencies (standard library only).
33
+
34
+ [Unreleased]: https://github.com/ipregistry/ipregistry-ruby/compare/v1.0.0...HEAD
35
+ [1.0.0]: https://github.com/ipregistry/ipregistry-ruby/releases/tag/v1.0.0
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,285 @@
1
+ [<img src="https://cdn.ipregistry.co/icons/favicon-96x96.png" alt="Ipregistry" width="64"/>](https://ipregistry.co/)
2
+ # Ipregistry Ruby Client Library
3
+
4
+ [![License](http://img.shields.io/:license-apache-blue.svg)](LICENSE)
5
+ [![Gem Version](https://img.shields.io/gem/v/ipregistry)](https://rubygems.org/gems/ipregistry)
6
+ [![CI](https://github.com/ipregistry/ipregistry-ruby/actions/workflows/ci.yaml/badge.svg)](https://github.com/ipregistry/ipregistry-ruby/actions/workflows/ci.yaml)
7
+
8
+ This is the official Ruby client library for the [Ipregistry](https://ipregistry.co) IP geolocation and threat data
9
+ API, allowing you to look up your own IP address or specified ones. Responses return multiple data points including
10
+ carrier, company, currency, location, time zone, threat information, and more. The library can also parse raw
11
+ User-Agent strings.
12
+
13
+ The gem has **zero runtime dependencies** — it is built entirely on the Ruby standard library.
14
+
15
+ ## Getting Started
16
+
17
+ You'll need an Ipregistry API key, which you can get along with 100,000 free lookups by signing up for a free account
18
+ at [https://ipregistry.co](https://ipregistry.co).
19
+
20
+ ### Installation
21
+
22
+ Add the gem to your application's Gemfile:
23
+
24
+ ```ruby
25
+ gem "ipregistry"
26
+ ```
27
+
28
+ Or install it directly:
29
+
30
+ ```bash
31
+ gem install ipregistry
32
+ ```
33
+
34
+ Requires Ruby 3.1 or later.
35
+
36
+ ### Quick start
37
+
38
+ #### Single IP lookup
39
+
40
+ ```ruby
41
+ require "ipregistry"
42
+
43
+ client = Ipregistry::Client.new("YOUR_API_KEY")
44
+
45
+ # Look up data for a given IPv4 or IPv6 address.
46
+ # On the server side, retrieve the client IP from the request headers.
47
+ info = client.lookup("54.85.132.205")
48
+
49
+ info.location.country.name # => "United States"
50
+ info.location.city # => "Ashburn"
51
+ info.connection.asn # => 14618
52
+ info.security.vpn? # => false
53
+ info.time_zone.id # => "America/New_York"
54
+ ```
55
+
56
+ Every response is a lightweight value object. Nested sections are always present, so chained access like
57
+ `info.location.country.name` never raises — absent fields return `nil` and absent flags return `false`. The raw
58
+ decoded payload is available through `info.to_h`, and any field (including ones without a dedicated reader) through
59
+ `info["field"]`.
60
+
61
+ #### Origin IP lookup
62
+
63
+ To look up the IP address the request is sent from — no argument needed — use `lookup_origin`. It returns a
64
+ `RequesterIpInfo`, which additionally carries parsed User-Agent data:
65
+
66
+ ```ruby
67
+ origin = client.lookup_origin
68
+ origin.ip # => your public IP
69
+ origin.location.country.name
70
+ origin.user_agent&.name # => e.g. "Ruby" (nil when the API omits it)
71
+ ```
72
+
73
+ #### Batch IP lookup
74
+
75
+ `batch_lookup` resolves many IP addresses in a single request. Each entry may independently succeed or fail (for
76
+ example on an invalid address), so results are inspected element by element:
77
+
78
+ ```ruby
79
+ response = client.batch_lookup(["73.2.2.2", "8.8.8.8", "2001:67c:2e8:22::c100:68b"])
80
+
81
+ response.each do |result|
82
+ if result.success?
83
+ puts result.value.location.country.name
84
+ else
85
+ # A per-entry error (e.g. invalid IP address); an Ipregistry::ApiError.
86
+ warn "entry failed: #{result.error.message}"
87
+ end
88
+ end
89
+
90
+ response[0].value! # the first entry's IpInfo, raising its error if it failed
91
+ response.values # only the successfully resolved IpInfo objects, in order
92
+ response.errors # only the per-entry errors, in order
93
+ ```
94
+
95
+ `BatchResponse` is `Enumerable`, so `map`, `select`, `zip`, and friends work as expected, and results support
96
+ pattern matching (`in { error: Ipregistry::ApiError }`).
97
+
98
+ The Ipregistry API accepts up to 1024 IP addresses per request. `batch_lookup` transparently splits larger arrays
99
+ into several requests, dispatched with bounded concurrency, and reassembles the results in input order — so you can
100
+ pass an arbitrarily long array without hitting `TOO_MANY_IPS`. Tune the behavior when needed:
101
+
102
+ ```ruby
103
+ client = Ipregistry::Client.new("YOUR_API_KEY",
104
+ max_batch_size: 1024, # addresses per request (max/default: 1024)
105
+ batch_concurrency: 4) # concurrent sub-requests (default: 4; 1 = sequential)
106
+ ```
107
+
108
+ Only cache misses are sent to the API; if a whole sub-request fails (network or API error), `batch_lookup` raises
109
+ that error, whereas an individual bad address surfaces as a per-entry error as shown above.
110
+
111
+ ## Lookup options
112
+
113
+ Lookups accept keywords that map to Ipregistry query parameters:
114
+
115
+ ```ruby
116
+ info = client.lookup("8.8.8.8",
117
+ hostname: true, # resolve reverse-DNS hostname
118
+ fields: "location.country.name,security") # select only these fields
119
+ ```
120
+
121
+ | Keyword | Description |
122
+ |-------------------|-----------------------------------------------------------------------------------------------------------------------------|
123
+ | `hostname:` | Enable reverse-DNS hostname resolution (disabled by default). |
124
+ | `fields:` | Restrict the response to the given [fields](https://ipregistry.co/docs/filtering-selecting-fields), reducing payload size. |
125
+ | any other keyword | Passed through as an arbitrary query parameter not covered by a dedicated keyword. |
126
+
127
+ The same keywords are accepted by `lookup_origin` and `batch_lookup`.
128
+
129
+ ## Caching
130
+
131
+ Although the client has built-in support for in-memory caching, it is **disabled by default** to ensure data freshness.
132
+
133
+ To enable caching, pass a `Cache::Memory` when constructing the client:
134
+
135
+ ```ruby
136
+ client = Ipregistry::Client.new("YOUR_API_KEY", cache: Ipregistry::Cache::Memory.new)
137
+ ```
138
+
139
+ The in-memory cache is thread-safe and supports size- and time-based eviction (LRU with a TTL):
140
+
141
+ ```ruby
142
+ cache = Ipregistry::Cache::Memory.new(
143
+ max_size: 8192, # maximum number of entries (default 4096)
144
+ ttl: 600) # entry lifetime in seconds (default 600)
145
+
146
+ client = Ipregistry::Client.new("YOUR_API_KEY", cache: cache)
147
+ ```
148
+
149
+ Origin (requester) lookups are never cached, because the requester IP is only known from the response. Batch lookups
150
+ transparently serve already-cached entries and only request the remainder from the API.
151
+
152
+ You can provide your own cache backend (Redis, `Rails.cache`, ...) with any object responding to:
153
+
154
+ ```ruby
155
+ get(key) # => value or nil
156
+ set(key, value)
157
+ delete(key)
158
+ clear
159
+ ```
160
+
161
+ ## Retries
162
+
163
+ Failed requests are automatically retried with an exponential backoff. By default, up to 3 retries are performed on
164
+ transient network errors and 5xx server responses.
165
+
166
+ Because Ipregistry does not rate limit by default (rate limiting is opt-in per API key), retries on
167
+ _429 Too Many Requests_ responses are **disabled by default**. Enable them if your API key is configured with a rate
168
+ limit and you want the client to wait and retry (honoring the `Retry-After` header when present):
169
+
170
+ ```ruby
171
+ client = Ipregistry::Client.new("YOUR_API_KEY",
172
+ max_retries: 3, # 0 disables retries entirely
173
+ retry_interval: 1, # base backoff in seconds (interval * 2^attempt)
174
+ retry_on_server_error: true, # retry on 5xx (default: true)
175
+ retry_on_too_many_requests: true) # retry on 429 (default: false)
176
+ ```
177
+
178
+ ## Timeouts and concurrency
179
+
180
+ By default every request times out after 15 seconds (applied to connection open, read, and write). Adjust it with the
181
+ `timeout:` keyword:
182
+
183
+ ```ruby
184
+ client = Ipregistry::Client.new("YOUR_API_KEY", timeout: 5)
185
+ ```
186
+
187
+ A `Client` is safe for concurrent use, so share one instance across threads; batch lookups already parallelize their
188
+ sub-requests internally.
189
+
190
+ ## Errors
191
+
192
+ Every error raised by the library inherits from `Ipregistry::Error`, so a single rescue clause covers everything:
193
+
194
+ - **`Ipregistry::ApiError`** — the API reported a failure (e.g. insufficient credits, throttling, invalid input). It
195
+ carries the raw `code`, the suggested `resolution`, and the `http_status`. Each documented error code maps to a
196
+ dedicated subclass, so you can rescue exactly the condition you care about.
197
+ - **`Ipregistry::ClientError`** — a client-side failure, further specialized as `ConnectionError`, `TimeoutError`, or
198
+ `ParseError`. The underlying exception, when any, is available through `#cause`.
199
+
200
+ ```ruby
201
+ begin
202
+ info = client.lookup("8.8.8.8")
203
+ rescue Ipregistry::InsufficientCreditsError
204
+ # handle exhausted credits
205
+ rescue Ipregistry::TooManyRequestsError
206
+ # handle rate limiting
207
+ rescue Ipregistry::ApiError => e
208
+ # any other API failure
209
+ warn "#{e.message} (#{e.code}): #{e.resolution}"
210
+ rescue Ipregistry::ClientError => e
211
+ # network / timeout / decoding error
212
+ warn e.cause&.message || e.message
213
+ end
214
+ ```
215
+
216
+ Error classes include `BadRequestError`, `DisabledApiKeyError`, `ForbiddenIpError`, `InsufficientCreditsError`,
217
+ `InvalidApiKeyError`, `InvalidIpAddressError`, `MissingApiKeyError`, `ReservedIpAddressError`, `TooManyIpsError`,
218
+ `TooManyRequestsError`, and more — see `Ipregistry::ERRORS_BY_CODE` for the full mapping and
219
+ [ipregistry.co/docs/errors](https://ipregistry.co/docs/errors) for the documented codes.
220
+
221
+ ## Parsing User-Agents
222
+
223
+ Parse one or more raw User-Agent strings (such as the `User-Agent` header of an incoming request) into structured
224
+ data. Like batch lookups, results are per-entry:
225
+
226
+ ```ruby
227
+ response = client.parse_user_agents(
228
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) Chrome/120.0")
229
+
230
+ ua = response[0].value!
231
+ ua.name # => "Chrome"
232
+ ua.operating_system.name # => "macOS"
233
+ ua.device.type # => "desktop"
234
+ ```
235
+
236
+ ## Filtering bots
237
+
238
+ You might want to prevent Ipregistry API calls for crawlers or bots browsing your pages. To help identify bots from
239
+ the User-Agent, the library includes a lightweight helper:
240
+
241
+ ```ruby
242
+ unless Ipregistry.bot?(request.user_agent)
243
+ info = client.lookup(request.remote_ip)
244
+ # ...
245
+ end
246
+ ```
247
+
248
+ ## Examples
249
+
250
+ Runnable examples live in the [`examples/`](examples) directory. Set your key and run one:
251
+
252
+ ```bash
253
+ IPREGISTRY_API_KEY=YOUR_API_KEY ruby examples/single.rb
254
+ ```
255
+
256
+ ## Testing
257
+
258
+ The library ships with two tiers of tests:
259
+
260
+ - **Unit / behavior specs** run offline against [WebMock](https://github.com/bblimke/webmock) stubs — no API key or
261
+ network is required. This is the default `bundle exec rake spec` and what CI runs.
262
+ - **System specs** exercise the live Ipregistry API. They live in `spec/system` and are skipped unless
263
+ `IPREGISTRY_API_KEY` is set (each successful lookup consumes credits):
264
+
265
+ ```bash
266
+ IPREGISTRY_API_KEY=YOUR_API_KEY bundle exec rake system
267
+ ```
268
+
269
+ Common tasks are wired through the `Rakefile`: `rake spec`, `rake system`, `rake rubocop`, and `rake build`. The
270
+ default task runs RuboCop and the unit specs.
271
+
272
+ ## Other Libraries
273
+
274
+ There are official Ipregistry client libraries available for many languages including
275
+ [Java](https://github.com/ipregistry/ipregistry-java),
276
+ [Javascript](https://github.com/ipregistry/ipregistry-javascript),
277
+ [Python](https://github.com/ipregistry/ipregistry-python),
278
+ [Go](https://github.com/ipregistry/ipregistry-go) and more.
279
+
280
+ Are you looking for an official client with a programming language or framework we do not support yet?
281
+ [Let us know](mailto:support@ipregistry.co).
282
+
283
+ ## License
284
+
285
+ This library is released under the [Apache 2.0 license](LICENSE).
@@ -0,0 +1,100 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ipregistry
4
+ # Ordered results of a batch operation ({Client#batch_lookup} or
5
+ # {Client#parse_user_agents}). Each entry may independently succeed or fail
6
+ # (for example on an invalid IP address), so entries are {Result} objects
7
+ # inspected element by element:
8
+ #
9
+ # response = client.batch_lookup(["8.8.8.8", "not-an-ip"])
10
+ # response.each do |result|
11
+ # if result.success?
12
+ # puts result.value.location.country.name
13
+ # else
14
+ # warn "entry failed: #{result.error.message}"
15
+ # end
16
+ # end
17
+ #
18
+ # BatchResponse is Enumerable, so +map+, +select+, +zip+, and friends work
19
+ # as expected. Use {#values} for the successful values only, or
20
+ # {Result#value!} to raise a failed entry's error.
21
+ class BatchResponse
22
+ include Enumerable
23
+
24
+ # One entry of a batch operation: either a value (an {Models::IpInfo} or
25
+ # {Models::UserAgent}) or the {ApiError} explaining why this particular
26
+ # entry failed.
27
+ class Result
28
+ # @return [Object, nil] the resolved value, or nil when the entry failed
29
+ attr_reader :value
30
+
31
+ # @return [ApiError, nil] the entry's failure, or nil when it succeeded
32
+ attr_reader :error
33
+
34
+ def self.success(value)
35
+ new(value: value)
36
+ end
37
+
38
+ def self.failure(error)
39
+ new(error: error)
40
+ end
41
+
42
+ def initialize(value: nil, error: nil)
43
+ @value = value
44
+ @error = error
45
+ end
46
+
47
+ def success?
48
+ @error.nil?
49
+ end
50
+
51
+ def failure?
52
+ !success?
53
+ end
54
+
55
+ # The resolved value, raising the entry's error when it failed.
56
+ def value!
57
+ raise @error if @error
58
+
59
+ @value
60
+ end
61
+
62
+ def deconstruct_keys(_keys)
63
+ { value: @value, error: @error }
64
+ end
65
+ end
66
+
67
+ # @return [Array<Result>] the entries, in input order
68
+ attr_reader :results
69
+
70
+ def initialize(results)
71
+ @results = results.freeze
72
+ end
73
+
74
+ # Yields each {Result} in input order.
75
+ def each(&)
76
+ @results.each(&)
77
+ end
78
+
79
+ # The {Result} at the given index.
80
+ def [](index)
81
+ @results[index]
82
+ end
83
+
84
+ def size
85
+ @results.size
86
+ end
87
+ alias length size
88
+
89
+ # The successfully resolved values, in order, skipping failed entries.
90
+ def values
91
+ @results.select(&:success?).map(&:value)
92
+ end
93
+
94
+ # The per-entry errors, in order, skipping successful entries.
95
+ # @return [Array<ApiError>]
96
+ def errors
97
+ @results.select(&:failure?).map(&:error)
98
+ end
99
+ end
100
+ end