moon_phase_tracker 1.4.0 → 2.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 9c9587009682cc81b906d04054af17b88ae9863ebc56227457d507a2e484eb9c
4
- data.tar.gz: 9a55ae1b9ffc3920f0fa7b9096bb5f107980efe55f646caf4d6f104890c51abb
3
+ metadata.gz: 9ff732cf61a629a58284391c9e0cc0148ec6b6a9ad4a4334a94a67070e38b6e5
4
+ data.tar.gz: e07d67d910ca2a10e7dce78d1e992dc5c936fa3a15241e4acdd18554858b6d41
5
5
  SHA512:
6
- metadata.gz: '04509c13863e69615e2a4af359e997e9481fd3765e0950fe3a966a25d5f3bca4609607fbed3a1b5d2e32b375887e97ac4ec82d937224889988842b639ab26fc7'
7
- data.tar.gz: 890dd9e2ec203dd22b512f50e7e5831ec7f18932ded680366627883c42307dcc3cc4f7e2009e44783b98e77791de51f34ca44512534375d7437b3b73f7c5a313
6
+ metadata.gz: 94b9aa6bac39efa2bafc7a3c25fb5006cfc1ac290d942acc48fdd1739f6e304cd46cd60b79540ad3c58b9e1203ea37df623d6947d0f6fa8770bc1b01af3b777b
7
+ data.tar.gz: 6a59a51a12d2457b889eb218094c178c4393bff1af296c26a235b4a1e03c6e24808d8bd2df77a6dc13f749f80ef560f73ee0196e2eb4250927b40452653824bd
data/CHANGELOG.md CHANGED
@@ -7,6 +7,39 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ Will ship as 2.0.0.
11
+
12
+ ### Breaking
13
+
14
+ - **Ruby 4.0 required**
15
+ - `required_ruby_version` is now `>= 4.0`, dropping Ruby 3.2, 3.3 and 3.4
16
+ - CI runs Ruby 4.0.10 only, in both `main.yml` and `release.yml`
17
+ - `Gemfile.lock` bumped minitest, prism and unicode-emoji so it installs on Ruby 4
18
+
19
+ ### Security
20
+
21
+ - **Server text no longer reaches `APIError` messages**
22
+ - `APIError` messages now carry only gem-computed values, such as the HTTP
23
+ status code
24
+ - Removed the server's `error` field, the HTTP reason phrase, and
25
+ `JSON::ParserError#message`, which echoes the response body
26
+ - `cause: nil` on the malformed-response path, because the original exception
27
+ still held the remote text
28
+ - `Net::HTTPBadResponse` now maps to `APIError`. It used to reach callers raw,
29
+ with the remote status line in its message
30
+ - `NetworkError` still interpolates the underlying error message. That text is
31
+ the gem's own hostname and OS resolver output, not server content
32
+
33
+ ### Fixed
34
+
35
+ - **Error classes were unreachable**
36
+ - In `Client#make_request`, `Net::TimeoutError` does not exist in the locked
37
+ net-http 0.6.0, so evaluating that rescue clause raised `NameError` and
38
+ masked the real error
39
+ - Every `APIError` and `NetworkError` the gem documented was unreachable on
40
+ that path
41
+ - Added `spec/moon_phase_tracker/client_spec.rb` covering the error paths
42
+
10
43
  ## [1.3.2] - 2025-08-04
11
44
 
12
45
  ### Changed
data/README.md CHANGED
@@ -96,6 +96,38 @@ all_year_phases = MoonPhaseTracker.all_phases_for_year(2025)
96
96
  extended_phases = MoonPhaseTracker.all_phases_from_date("2025-08-01", 2)
97
97
  ```
98
98
 
99
+ #### Filtering Intermediate Phases
100
+
101
+ To extract only the 4 calculated intermediate phases from a month:
102
+
103
+ ```ruby
104
+ require 'moon_phase_tracker'
105
+
106
+ begin
107
+ all_phases = MoonPhaseTracker.all_phases_for_month(2025, 8)
108
+ rescue MoonPhaseTracker::NetworkError, MoonPhaseTracker::APIError => e
109
+ puts "API unavailable: #{e.message}"
110
+ all_phases = []
111
+ end
112
+
113
+ interpolated = all_phases.select(&:interpolated)
114
+
115
+ interpolated.each do |phase|
116
+ puts "#{phase.symbol} #{phase.name} — #{phase.formatted_date} (source: #{phase.source})"
117
+ end
118
+ # => 🌒 Waxing Crescent — 2025-08-08 (source: interpolated)
119
+ # => 🌔 Waxing Gibbous — 2025-08-15 (source: interpolated)
120
+ # => 🌖 Waning Gibbous — 2025-08-22 (source: interpolated)
121
+ # => 🌘 Waning Crescent — 2025-08-29 (source: interpolated)
122
+ ```
123
+
124
+ **Edge cases to handle:**
125
+ - A month at the boundary of the USNO data range may return fewer than 4 major phases, which means fewer interpolated phases (or none)
126
+ - `all_phases_for_month` can return between 4 and 8 phases depending on how many intermediate phases fall within the calendar month
127
+ - The `interpolated` attribute is always `false` for API phases and `true` for calculated intermediates — there's no ambiguous state
128
+
129
+ **Dependencies:** The gem requires Ruby >= 4.0. Install via `gem install moon_phase_tracker` or add `gem 'moon_phase_tracker'` to your Gemfile. No external services needed for `LunarCalculator` methods; only the `phases_for_*` and `all_phases_for_*` methods require network access to the USNO API.
130
+
99
131
  ### 🔮 Instant Moon Phase - No API, No Waiting
100
132
 
101
133
  *What phase is the moon right now? How bright is it? Pure math, instant answer.*
@@ -205,18 +237,47 @@ phase.in_year?(2025) # => true (definitely a 2025 vintage)
205
237
 
206
238
  *Even celestial bodies have bad days. Here's how to handle lunar tantrums gracefully.*
207
239
 
240
+ All errors inherit from `MoonPhaseTracker::Error`, so you can rescue broadly or specifically:
241
+
242
+ | Error Class | Raised When | Example Trigger |
243
+ |-------------|-------------|-----------------|
244
+ | `NetworkError` | Connection timeout, DNS failure, socket error | USNO API is down, no internet |
245
+ | `APIError` | Non-200 response or invalid JSON from the API | 500 server error, malformed response |
246
+ | `InvalidDateError` | Input validation fails before any API call | Month 13, year 1500, unparseable string |
247
+
208
248
  ```ruby
209
249
  begin
210
250
  phases = MoonPhaseTracker.phases_for_month(2025, 8)
211
251
  rescue MoonPhaseTracker::NetworkError => e
212
- puts "Network hiccup: #{e.message}" # The internet is having a moment
252
+ puts "Network hiccup: #{e.message}"
213
253
  rescue MoonPhaseTracker::APIError => e
214
- puts "API tantrum: #{e.message}" # The Navy API is feeling moody
254
+ puts "API tantrum: #{e.message}"
215
255
  rescue MoonPhaseTracker::InvalidDateError => e
216
- puts "Time travel error: #{e.message}" # That date doesn't exist in this dimension
256
+ puts "Time travel error: #{e.message}"
217
257
  end
218
258
  ```
219
259
 
260
+ Since `LunarCalculator` is pure math (no network), it makes a natural fallback when the API is unavailable:
261
+
262
+ ```ruby
263
+ def moon_phases_for(year, month)
264
+ MoonPhaseTracker.all_phases_for_month(year, month)
265
+ rescue MoonPhaseTracker::NetworkError, MoonPhaseTracker::APIError
266
+ # API down — generate approximate phases from the calculator
267
+ first_day = Date.new(year, month, 1)
268
+ last_day = first_day.next_month - 1
269
+ calculator = MoonPhaseTracker::LunarCalculator.new
270
+
271
+ (first_day..last_day).each_with_object([]) do |date, phases|
272
+ phase = calculator.phase_at(date)
273
+ prev = phases.last
274
+ phases << phase if prev.nil? || prev.name != phase.name
275
+ end
276
+ end
277
+ ```
278
+
279
+ The fallback returns one Phase per named transition in the month. The `source` field will be `:calculated` instead of `:api`, so downstream code can distinguish degraded results.
280
+
220
281
  ### 🎪 Real-World Lunar Magic
221
282
 
222
283
  *Because theory is nice, but seeing the moon phases in action is where the real magic happens.*
@@ -331,6 +392,174 @@ phase.illumination # => 65.3 (percent)
331
392
  phase.lunar_age # => 10.2 (days since last new moon)
332
393
  ```
333
394
 
395
+ ### 🔬 Accuracy & Validation
396
+
397
+ #### Interpolated Phases — Known Limitations
398
+
399
+ The 4 intermediate phases (Waxing Crescent, Waxing Gibbous, Waning Gibbous, Waning Crescent) are **not** from the USNO API. They're calculated by splitting the time interval between two consecutive major phases in half.
400
+
401
+ This approach assumes **uniform phase spacing** within each quarter of the lunar cycle. In reality, the Moon's orbit is elliptical — it moves faster at perigee and slower at apogee. The practical consequences:
402
+
403
+ | Limitation | Impact | Magnitude |
404
+ |------------|--------|-----------|
405
+ | Phase timing error | Interpolated dates can drift from true astronomical timing | Up to ~12 hours |
406
+ | Illumination gap | The calculator's cosine model smooths over orbital eccentricity | ~2-5% near quarter phases |
407
+ | Boundary misclassification | Near phase transitions, the named phase may differ from USNO | Within ~6 hours of boundaries |
408
+ | No libration modeling | The synodic model ignores lunar libration and perturbations | Negligible for phase naming |
409
+
410
+ **For precision-critical applications** (astronomical scheduling, scientific observations, tidal calculations), always use the `:api` source phases. The interpolated and calculated paths are designed for **display and UX** — calendars, widgets, badges, content scheduling.
411
+
412
+ #### Calculator (Synodic Model) — What It Can and Can't Do
413
+
414
+ The `LunarCalculator` uses a fixed synodic month of 29.530588853 days anchored to a known New Moon epoch (January 6, 2000, 18:14 UTC). It gives you:
415
+
416
+ - **Correct named phase ~99% of the time** — the 8 phase boundaries divide the cycle into equal 1/8th arcs
417
+ - **Illumination via cosine curve** — `(1 - cos(2π × fraction)) / 2` approximates the visual illumination percentage
418
+ - **Instant results for any date from 1800 to 2100** — no network, no rate limits
419
+
420
+ What it doesn't model: orbital eccentricity, solar perturbations, atmospheric refraction, or the equation of time. These factors accumulate over centuries, so dates far from the epoch will drift more.
421
+
422
+ #### Validating Against USNO Data
423
+
424
+ You can cross-check any calculated phase against the authoritative API data:
425
+
426
+ ```ruby
427
+ require 'moon_phase_tracker'
428
+
429
+ date = Date.new(2025, 8, 19)
430
+
431
+ # Calculator path (instant, approximate)
432
+ calc = MoonPhaseTracker.phase_at(date)
433
+
434
+ # API path (network call, authoritative)
435
+ api_phases = MoonPhaseTracker.phases_for_month(2025, 8)
436
+ api = api_phases.find { |p| p.date == date }
437
+
438
+ if api
439
+ puts "Calculator: #{calc.name} (#{calc.illumination.round(1)}%)"
440
+ puts "USNO API: #{api.name}"
441
+ puts "Phase match: #{calc.name == api.name}"
442
+ puts "Date delta: #{(calc.date - api.date).to_i} days"
443
+ end
444
+ ```
445
+
446
+ For systematic validation, compare an entire year's calculated phases against API data:
447
+
448
+ ```ruby
449
+ tracker = MoonPhaseTracker::Tracker.new
450
+ api_phases = tracker.phases_for_year(2025)
451
+ calculator = MoonPhaseTracker::LunarCalculator.new
452
+
453
+ mismatches = api_phases.count do |api_phase|
454
+ calc_phase = calculator.phase_at(api_phase.date)
455
+ calc_phase.name != api_phase.name
456
+ end
457
+
458
+ accuracy = ((api_phases.size - mismatches).to_f / api_phases.size * 100).round(1)
459
+ puts "#{accuracy}% phase name accuracy (#{mismatches}/#{api_phases.size} mismatches)"
460
+ ```
461
+
462
+ ### 📦 Multi-Year Queries, Caching, and Rate Limits
463
+
464
+ #### What the Gem Caches (and What It Doesn't)
465
+
466
+ The `Client` has one internal cache: `@uri_cache`, keyed by endpoint + params. It caches **parsed URI objects**, not API responses. Calling `phases_for_year(2025)` twice on the same `Tracker` instance reuses the parsed URI but makes two network requests.
467
+
468
+ The gem has **no built-in response cache**. This is intentional — caching strategy depends on your application (Redis, Memcached, database, in-memory), so it belongs in your layer.
469
+
470
+ #### Avoiding Redundant API Calls for the Same Month
471
+
472
+ `phases_for_month(year, month)` internally calls `phases_for_year(year)` and filters by month. This means querying January, February, and March of 2025 makes **three identical API calls** to the same year endpoint:
473
+
474
+ ```ruby
475
+ tracker = MoonPhaseTracker::Tracker.new
476
+
477
+ # BAD: 3 API calls for the same year
478
+ jan = tracker.phases_for_month(2025, 1)
479
+ feb = tracker.phases_for_month(2025, 2)
480
+ mar = tracker.phases_for_month(2025, 3)
481
+ ```
482
+
483
+ Fetch the year once and filter locally:
484
+
485
+ ```ruby
486
+ tracker = MoonPhaseTracker::Tracker.new
487
+
488
+ # GOOD: 1 API call, filter in Ruby
489
+ all_2025 = tracker.phases_for_year(2025)
490
+ jan = all_2025.select { |p| p.in_month?(2025, 1) }
491
+ feb = all_2025.select { |p| p.in_month?(2025, 2) }
492
+ mar = all_2025.select { |p| p.in_month?(2025, 3) }
493
+ ```
494
+
495
+ The same applies to `all_phases_for_month` — use `all_phases_for_year` once and filter.
496
+
497
+ #### Rate Limiter Scope
498
+
499
+ The rate limiter is **per-Tracker instance**. Each `Tracker.new` creates its own `Client` with its own token bucket. Multiple trackers (e.g. one per background worker) each enforce their own rate limit independently.
500
+
501
+ #### Multi-Year Strategy
502
+
503
+ The USNO API returns all phases for a given year in a single response (~50 phases per year). Querying 10 years means 10 API calls, not 120 month-by-month calls. Use `phases_for_year` as the batch unit:
504
+
505
+ ```ruby
506
+ # Efficient: 1 API call per year, rate limiter spaces them automatically
507
+ tracker = MoonPhaseTracker::Tracker.new
508
+
509
+ phases_by_year = (2020..2030).each_with_object({}) do |year, acc|
510
+ acc[year] = tracker.all_phases_for_year(year)
511
+ end
512
+
513
+ # 11 API calls total, ~11 seconds at default rate (1 req/sec)
514
+ # Each year returns ~50 phases (major) or ~100 phases (all 8)
515
+ ```
516
+
517
+ For faster bulk loading, increase the rate limit:
518
+
519
+ ```ruby
520
+ fast_limiter = MoonPhaseTracker::RateLimiter.new(
521
+ requests_per_second: 3.0,
522
+ burst_size: 3
523
+ )
524
+ tracker = MoonPhaseTracker::Tracker.new(rate_limiter: fast_limiter)
525
+
526
+ # Same 11 calls, now ~4 seconds
527
+ (2020..2030).each { |year| tracker.phases_for_year(year) }
528
+ ```
529
+
530
+ #### Adding a Response Cache
531
+
532
+ Lunar data is static per year, so a long TTL works well. A pattern with Rails:
533
+
534
+ ```ruby
535
+ class LunarDataService
536
+ def phases_for_year(year)
537
+ Rails.cache.fetch("lunar_phases/#{year}", expires_in: 30.days) do
538
+ MoonPhaseTracker.all_phases_for_year(year).map(&:to_h)
539
+ end
540
+ end
541
+
542
+ def phases_for_range(start_year, end_year)
543
+ (start_year..end_year).flat_map { |year| phases_for_year(year) }
544
+ end
545
+ end
546
+ ```
547
+
548
+ This gives you: one API call per year, cached for 30 days, rate-limited automatically. The `to_h` serialization ensures the cache stores plain hashes (safe for any cache backend).
549
+
550
+ #### Combining API and Calculator for Multi-Year Systems
551
+
552
+ For applications that span multiple years, the recommended architecture:
553
+
554
+ | Time Range | Source | Why |
555
+ |------------|--------|-----|
556
+ | Historical data (past years) | API, cached in database | Exact dates, fetch once, query forever |
557
+ | Current year | API, cached with shorter TTL | Re-fetch quarterly to catch USNO updates |
558
+ | Real-time display | `LunarCalculator` | No network, no cache, instant |
559
+ | Far future (> 10 years out) | `LunarCalculator` | USNO API range is limited |
560
+
561
+ The database-backed approach from the [Hybrid Architecture](#hybrid-architecture-usno-for-scheduling-calculator-for-display) example works across years — run the sync job once per year for each new year, and the `lunar_phases` table grows by ~100 rows annually.
562
+
334
563
  ## ⚓ Our Trusted Cosmic Oracle
335
564
 
336
565
  *We get our lunar wisdom from the finest source - the folks who navigate the seven seas by the stars.*
data/context7.json ADDED
@@ -0,0 +1,4 @@
1
+ {
2
+ "url": "https://context7.com/dklima/moon_phase_tracker",
3
+ "public_key": "pk_CC1a8biTz6h7RLWccvgzu"
4
+ }
@@ -50,12 +50,13 @@ module MoonPhaseTracker
50
50
  begin
51
51
  response = fetch_with_timeout(uri)
52
52
  parse_response(response)
53
- rescue Net::TimeoutError, Net::OpenTimeout, Net::ReadTimeout => e
53
+ rescue Net::OpenTimeout, Net::ReadTimeout => e
54
54
  raise NetworkError, "Request timeout: #{e.message}"
55
55
  rescue Net::HTTPError, SocketError => e
56
56
  raise NetworkError, "Network error: #{e.message}"
57
- rescue JSON::ParserError => e
58
- raise APIError, "Invalid JSON response: #{e.message}"
57
+ rescue Net::HTTPBadResponse, JSON::ParserError
58
+ # Remote text stays out of messages and causes: it can carry credentials into user logs
59
+ raise APIError, "Malformed response from API", cause: nil
59
60
  end
60
61
  end
61
62
 
@@ -78,7 +79,7 @@ module MoonPhaseTracker
78
79
  response = http.request(request)
79
80
 
80
81
  unless response.is_a?(Net::HTTPSuccess)
81
- raise APIError, "API request failed: #{response.code} - #{response.message}"
82
+ raise APIError, "API request failed with HTTP #{response.code}"
82
83
  end
83
84
 
84
85
  response
@@ -88,7 +89,8 @@ module MoonPhaseTracker
88
89
  def parse_response(response)
89
90
  data = JSON.parse(response.body)
90
91
 
91
- raise APIError, "API error: #{data['error']}" if data["error"]
92
+ # Server-supplied text stays out of messages: it can carry credentials into user logs
93
+ raise APIError, "API returned an error (HTTP #{response.code})" if data["error"]
92
94
 
93
95
  data
94
96
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module MoonPhaseTracker
4
- VERSION = "1.4.0"
4
+ VERSION = "2.0.0"
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: moon_phase_tracker
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.4.0
4
+ version: 2.0.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Daniel K Lima
@@ -51,6 +51,7 @@ files:
51
51
  - LICENSE.txt
52
52
  - README.md
53
53
  - Rakefile
54
+ - context7.json
54
55
  - examples/eight_phases_example.rb
55
56
  - examples/rate_limiting_example.rb
56
57
  - examples/usage_example.rb
@@ -88,14 +89,14 @@ required_ruby_version: !ruby/object:Gem::Requirement
88
89
  requirements:
89
90
  - - ">="
90
91
  - !ruby/object:Gem::Version
91
- version: 3.2.0
92
+ version: '4.0'
92
93
  required_rubygems_version: !ruby/object:Gem::Requirement
93
94
  requirements:
94
95
  - - ">="
95
96
  - !ruby/object:Gem::Version
96
97
  version: '0'
97
98
  requirements: []
98
- rubygems_version: 3.6.7
99
+ rubygems_version: 4.0.20
99
100
  specification_version: 4
100
101
  summary: Moon phase tracker using USNO Navy API
101
102
  test_files: []