moon_phase_tracker 1.3.2 → 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.
data/README.md CHANGED
@@ -1,23 +1,29 @@
1
- # MoonPhaseTracker 🌙
1
+ # 🌙 MoonPhaseTracker - Your Cosmic Calendar Companion
2
2
 
3
- A Ruby gem for tracking moon phases using the official US Naval Observatory (USNO) API. Perfect for creating lunar calendar-based scheduling applications.
3
+ *"Because every developer deserves to howl at the right moon."*
4
4
 
5
- **Expected accuracy: ~85-90% (suitable for lunar calendars)**
5
+ Ever wondered when to deploy your code for maximum lunar luck? Or perhaps you need to schedule that midnight debugging session during a proper New Moon? This delightful Ruby gem connects you to the cosmic dance above, using the official US Naval Observatory (USNO) API to bring celestial timing to your fingertips.
6
6
 
7
- ## Features
7
+ Whether you're building a werewolf scheduling app, a vampire calendar, or just want to impress your users with lunar-powered features, MoonPhaseTracker has got your back under every phase of the moon.
8
8
 
9
- - 🌑 Query moon phases by month, year, or from a specific date
10
- - 🌒 Complete 8-phase lunar cycle support (4 major + 4 intermediate phases)
11
- - 🌓 Simple and intuitive interface
12
- - 🌔 Accurate data from the official USNO Navy API
13
- - 🌕 Visual representation with moon phase emojis
14
- - 🌖 Interpolated intermediate phases for enhanced precision
15
- - 🌗 Visual indicators for calculated vs official phases
16
- - 🌘 Automatic caching to optimize requests
17
- - ⚡ Robust error handling
18
- - 🚦 Configurable rate limiting to respect API limits
9
+ **🎯 Accuracy: ~85-90%** *(Good enough for lunar calendars, probably too precise for howling)*
19
10
 
20
- ## Installation
11
+ ## ✨ What Makes This Gem Shine
12
+
13
+ - 🌑 **Time Travel Through Lunar Cycles** - Query moon phases by month, year, or from any date your heart desires
14
+ - 🌒 **The Full Lunar Symphony** - Complete 8-phase support (4 major crescendos + 4 melodic interludes)
15
+ - 🌓 **Simple as Moonlight** - An interface so intuitive, even a sleepy developer can use it at 3 AM
16
+ - 🌔 **Navy-Grade Precision** - Official USNO data because the Navy doesn't mess around with moon phases
17
+ - 🌕 **Emoji Magic** - Visual moon phases that spark joy in your terminal
18
+ - 🌖 **Mathematical Lunar Poetry** - Interpolated intermediate phases for when precision meets artistry
19
+ - 🌗 **Truth in Advertising** - Clear indicators showing official vs calculated phases (no moon phase imposters here!)
20
+ - 🌘 **Memory Like an Elephant** - Automatic caching because nobody likes waiting for the moon
21
+ - ⚡ **Bulletproof & Graceful** - Error handling that fails as elegantly as moonbeams
22
+ - 🚦 **API Etiquette** - Respectful rate limiting because even the Navy deserves a break
23
+
24
+ ## 🚀 Summoning the Lunar Powers
25
+
26
+ *Ready to add some celestial magic to your Ruby project?*
21
27
 
22
28
  Add this line to your application's Gemfile:
23
29
 
@@ -37,9 +43,13 @@ Or install it directly:
37
43
  gem install moon_phase_tracker
38
44
  ```
39
45
 
40
- ## Usage
46
+ ## 🎭 Lunar Adventures Await
41
47
 
42
- ### Basic Usage (4 Major Phases)
48
+ *Time to dance with the moon phases like a cosmic choreographer!*
49
+
50
+ ### 🌟 The Essential Four - Your Lunar Greatest Hits
51
+
52
+ *Start your journey with the moon's main characters: the celestial quartet that's been stealing hearts since ancient times.*
43
53
 
44
54
  ```ruby
45
55
  require 'moon_phase_tracker'
@@ -48,23 +58,26 @@ require 'moon_phase_tracker'
48
58
  phases = MoonPhaseTracker.phases_for_month(2025, 8)
49
59
  puts phases.first.to_s
50
60
  # => "🌑 New Moon - 2025-08-04 at 11:13"
61
+ # (Perfect timing for new beginnings!)
51
62
 
52
- # All phases for 2025
63
+ # All phases for 2025 - your yearly lunar roadmap
53
64
  year_phases = MoonPhaseTracker.phases_for_year(2025)
54
65
 
55
- # Next 6 phases from a specific date
66
+ # Next 6 phases from a specific date - peek into the future
56
67
  future_phases = MoonPhaseTracker.phases_from_date("2025-08-01", 6)
57
68
  ```
58
69
 
59
- ### Complete 8-Phase Lunar Cycle
70
+ ### 🎨 The Full Lunar Canvas - All 8 Phases in Their Glory
71
+
72
+ *For the lunar perfectionists who want the complete story, not just the highlights reel.*
60
73
 
61
74
  ```ruby
62
75
  require 'moon_phase_tracker'
63
76
 
64
- # All 8 phases for August 2025 (major + intermediate)
77
+ # All 8 phases for August 2025 - the complete lunar symphony
65
78
  all_phases = MoonPhaseTracker.all_phases_for_month(2025, 8)
66
79
  all_phases.each do |phase|
67
- indicator = phase.interpolated ? "~ " : " "
80
+ indicator = phase.interpolated ? "~ " : " " # ~ means "calculated with love"
68
81
  puts "#{indicator}#{phase}"
69
82
  end
70
83
  # => 🌑 New Moon - 2025-08-04 at 11:13
@@ -76,48 +89,128 @@ end
76
89
  # => 🌗 Last Quarter - 2025-08-26 at 09:26
77
90
  # => ~ 🌘 Waning Crescent - 2025-08-29 at 02:56
78
91
 
79
- # All 8 phases for entire year
92
+ # All 8 phases for entire year - your cosmic annual planner
80
93
  all_year_phases = MoonPhaseTracker.all_phases_for_year(2025)
81
94
 
82
- # All 8 phases from specific date (2 lunar cycles)
95
+ # All 8 phases from specific date (2 lunar cycles) - the extended edition
83
96
  extended_phases = MoonPhaseTracker.all_phases_from_date("2025-08-01", 2)
84
97
  ```
85
98
 
86
- ### Using the Tracker Class
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
+
131
+ ### 🔮 Instant Moon Phase - No API, No Waiting
132
+
133
+ *What phase is the moon right now? How bright is it? Pure math, instant answer.*
134
+
135
+ These methods use a synodic month calculation — no API calls, no network, no rate limits. Perfect for display UIs and real-time widgets.
136
+
137
+ ```ruby
138
+ require 'moon_phase_tracker'
139
+
140
+ # What's the moon doing right now?
141
+ phase = MoonPhaseTracker.current_phase
142
+ puts phase.to_s
143
+ # => "🌔 Waxing Gibbous - 2025-08-15 at 14:30"
144
+ puts phase.illumination # => 78.5 (percent)
145
+ puts phase.lunar_age # => 12.3 (days since last new moon)
146
+ puts phase.source # => :calculated
147
+
148
+ # Phase at any date/time - past or future
149
+ phase = MoonPhaseTracker.phase_at(Time.utc(2025, 6, 11, 7, 44))
150
+ puts phase.name # => "Full Moon"
151
+ puts phase.illumination # => ~100.0
152
+
153
+ # Just the illumination percentage
154
+ illum = MoonPhaseTracker.illumination(Date.today)
155
+ puts "#{illum.round(1)}% illuminated"
156
+
157
+ # Works with Date, Time, DateTime, or String
158
+ MoonPhaseTracker.phase_at(Date.new(2025, 1, 15))
159
+ MoonPhaseTracker.phase_at("2025-01-15")
160
+ MoonPhaseTracker.phase_at(DateTime.now)
161
+ ```
162
+
163
+ > **Accuracy note:** The synodic model gives the correct named phase ~99% of the time. Within ~6 hours of a phase boundary, it may differ from USNO API data. The API path gives precision for scheduling; the calculator path gives instant answers for display.
164
+
165
+ ### 🎯 The Tracker Class - Your Personal Lunar Assistant
166
+
167
+ *Think of it as your moon phase butler, always ready to serve up cosmic timing with a bow tie.*
87
168
 
88
169
  ```ruby
89
170
  tracker = MoonPhaseTracker::Tracker.new
90
171
 
91
- # Automatic formatting for display
172
+ # Automatic formatting for display - because presentation matters
92
173
  august_phases = tracker.phases_for_month(2025, 8)
93
174
  formatted = tracker.format_phases(august_phases, "August Phases")
94
175
  puts formatted
95
176
 
96
- # Next moon phase
177
+ # Next moon phase - your cosmic fortune telling
97
178
  next_phase = tracker.next_phase
98
179
  puts next_phase.to_s
99
180
 
100
- # Current month phases
181
+ # Current month phases - what's happening in your lunar neighborhood
101
182
  current_month = tracker.current_month_phases
183
+
184
+ # Instant phase at any date - no API call needed
185
+ phase = tracker.phase_at("2025-06-11")
186
+ puts phase.illumination # => Float (percent)
187
+
188
+ # Just the illumination number
189
+ illum = tracker.illumination("2025-06-11")
190
+
191
+ # Current phase right now
192
+ puts tracker.current_phase
102
193
  ```
103
194
 
104
- ### Working with Individual Phases
195
+ ### 🔍 Getting Personal with Moon Phases
196
+
197
+ *Each phase has its own personality - let's get to know them intimately.*
105
198
 
106
199
  ```ruby
107
200
  phase = phases.first
108
201
 
109
202
  # Phase information
110
203
  puts phase.name # "New Moon"
111
- puts phase.symbol # "🌑"
204
+ puts phase.symbol # "🌑" (isn't it beautiful?)
112
205
  puts phase.formatted_date # "2025-08-04"
113
- puts phase.formatted_time # "11:13"
114
- puts phase.interpolated # false (official USNO data)
206
+ puts phase.formatted_time # "11:13" (UTC - the moon doesn't do timezones)
207
+ puts phase.interpolated # false (certified genuine USNO data)
115
208
 
116
- # Working with interpolated phases
209
+ # Working with interpolated phases - the mathematically gifted ones
117
210
  interpolated_phase = all_phases.find(&:interpolated)
118
- puts interpolated_phase.interpolated # true (calculated)
211
+ puts interpolated_phase.interpolated # true (calculated with mathematical precision)
119
212
  puts interpolated_phase.name # "Waxing Crescent"
120
- puts interpolated_phase.symbol # "🌒"
213
+ puts interpolated_phase.symbol # "🌒" (still adorable)
121
214
 
122
215
  # Complete hash with all data
123
216
  details = phase.to_h
@@ -129,94 +222,388 @@ details = phase.to_h
129
222
  # symbol: "🌑",
130
223
  # iso_date: "2025-08-04",
131
224
  # utc_time: "2025-08-04T11:13:00Z",
132
- # interpolated: false
225
+ # interpolated: false,
226
+ # source: :api, # :api, :interpolated, or :calculated
227
+ # illumination: nil, # Float for calculated phases, nil for API
228
+ # lunar_age: nil # Float for calculated phases, nil for API
133
229
  # }
134
230
 
135
- # Date checks
136
- phase.in_month?(2025, 8) # => true
137
- phase.in_year?(2025) # => true
231
+ # Date checks - lunar detective work
232
+ phase.in_month?(2025, 8) # => true (August moon confirmed!)
233
+ phase.in_year?(2025) # => true (definitely a 2025 vintage)
138
234
  ```
139
235
 
140
- ### Error Handling
236
+ ### 🛡️ When the Moon Plays Hard to Get
237
+
238
+ *Even celestial bodies have bad days. Here's how to handle lunar tantrums gracefully.*
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 |
141
247
 
142
248
  ```ruby
143
249
  begin
144
250
  phases = MoonPhaseTracker.phases_for_month(2025, 8)
145
251
  rescue MoonPhaseTracker::NetworkError => e
146
- puts "Network error: #{e.message}"
252
+ puts "Network hiccup: #{e.message}"
147
253
  rescue MoonPhaseTracker::APIError => e
148
- puts "API error: #{e.message}"
254
+ puts "API tantrum: #{e.message}"
149
255
  rescue MoonPhaseTracker::InvalidDateError => e
150
- puts "Invalid date: #{e.message}"
256
+ puts "Time travel error: #{e.message}"
151
257
  end
152
258
  ```
153
259
 
154
- ### Practical Examples
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
+ ```
155
278
 
156
- See the `examples/usage_example.rb` and `examples/eight_phases_example.rb` files for complete usage examples.
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.
157
280
 
158
- ## API Reference
281
+ ### 🎪 Real-World Lunar Magic
159
282
 
160
- ### Main Methods (4 Major Phases)
283
+ *Because theory is nice, but seeing the moon phases in action is where the real magic happens.*
284
+
285
+ #### Hybrid Architecture: USNO for Scheduling, Calculator for Display
286
+
287
+ The API gives you exact dates. The calculator gives you instant answers. Use both — a background job populates a `lunar_phases` table with USNO data, and `LunarCalculator` handles the real-time display layer.
288
+
289
+ ```ruby
290
+ # app/jobs/sync_lunar_phases_job.rb
291
+ class SyncLunarPhasesJob < ApplicationJob
292
+ def perform(year = Date.current.year)
293
+ phases = MoonPhaseTracker.all_phases_for_year(year)
294
+
295
+ phases.each do |phase|
296
+ LunarPhase.upsert(
297
+ {
298
+ name: phase.name,
299
+ phase_type: phase.phase_type.to_s,
300
+ exact_at: phase.to_h[:utc_time],
301
+ source: phase.source.to_s
302
+ },
303
+ unique_by: :exact_at
304
+ )
305
+ end
306
+ end
307
+ end
308
+ ```
309
+
310
+ ```ruby
311
+ # app/models/lunar_phase.rb
312
+ class LunarPhase < ApplicationRecord
313
+ scope :upcoming, -> { where("exact_at > ?", Time.current).order(:exact_at) }
314
+ scope :next_full_moon, -> { upcoming.where(phase_type: "full_moon").first }
315
+ end
316
+ ```
317
+
318
+ ```ruby
319
+ # app/helpers/moon_helper.rb
320
+ module MoonHelper
321
+ def moon_badge(date = Date.current)
322
+ phase = MoonPhaseTracker.phase_at(date)
323
+ "#{phase.symbol} #{phase.illumination.round}%"
324
+ end
325
+ end
326
+ ```
327
+
328
+ Two data sources, each doing what they do best. The table owns scheduling precision (notifications, rituals, content triggers). The calculator owns display (emoji, illumination percentage, "what phase is it right now?"). They never step on each other's toes.
329
+
330
+ See the `examples/usage_example.rb` and `examples/eight_phases_example.rb` files for more usage examples.
331
+
332
+ ## 📚 The Lunar Grimoire - Complete API Spellbook
333
+
334
+ *Your comprehensive guide to all the lunar incantations at your disposal.*
335
+
336
+ ### 🎭 The Core Cast - 4 Major Phase Methods
337
+
338
+ *The essential methods that'll get you 80% of your lunar needs covered.*
161
339
 
162
340
  - `MoonPhaseTracker.phases_for_month(year, month)` - Major phases for a specific month
163
341
  - `MoonPhaseTracker.phases_for_year(year)` - All major phases for a year
164
342
  - `MoonPhaseTracker.phases_from_date(date, num_phases)` - Major phases from a specific date
165
343
 
166
- ### 8-Phase Methods (Major + Intermediate)
344
+ ### 🔮 Instant Lookup - No API Required
345
+
346
+ *Pure math, zero latency. For when you need the moon right now.*
347
+
348
+ - `MoonPhaseTracker.phase_at(date)` - Phase at any date/time (returns `Phase` with illumination)
349
+ - `MoonPhaseTracker.illumination(date)` - Illumination percentage (returns `Float` 0..100)
350
+ - `MoonPhaseTracker.current_phase` - Phase right now (shortcut for `phase_at(Time.now.utc)`)
351
+
352
+ No API calls — pure math under the hood.
353
+
354
+ ### 🌈 The Full Spectrum - 8-Phase Methods for Lunar Completionists
355
+
356
+ *For those who believe in doing things thoroughly (and slightly obsessively).*
167
357
 
168
358
  - `MoonPhaseTracker.all_phases_for_month(year, month)` - All 8 phases for a specific month
169
359
  - `MoonPhaseTracker.all_phases_for_year(year)` - All 8 phases for a year
170
360
  - `MoonPhaseTracker.all_phases_from_date(date, num_cycles)` - All 8 phases from a specific date
171
361
 
172
- ### Complete Phase Types
362
+ ### 🎨 Meet the Lunar Cast - All 8 Phase Personalities
363
+
364
+ #### 🏆 The Main Characters (Official USNO Data)
365
+ *These are the A-listers - certified by the Navy, guaranteed to impress.*
366
+ - 🌑 `:new_moon` - New Moon *(The mysterious beginning)*
367
+ - 🌓 `:first_quarter` - First Quarter *(Half-lit and growing strong)*
368
+ - 🌕 `:full_moon` - Full Moon *(The showstopper, the main event)*
369
+ - 🌗 `:last_quarter` - Last Quarter *(Gracefully waning)*
370
+
371
+ #### 🎭 The Supporting Cast (Interpolated ~85-90% accuracy)
372
+ *The understudies that complete the story - mathematically calculated with love.*
373
+ - 🌒 `:waxing_crescent` - Waxing Crescent *(The optimistic youngster)*
374
+ - 🌔 `:waxing_gibbous` - Waxing Gibbous *(Almost there, building anticipation)*
375
+ - 🌖 `:waning_gibbous` - Waning Gibbous *(The wise elder, still radiant)*
376
+ - 🌘 `:waning_crescent` - Waning Crescent *(The gentle farewell)*
377
+
378
+ ### 🏷️ Phase Sources - Know Where Your Data Comes From
379
+
380
+ *Every phase carries a passport stamped with its origin story.*
381
+
382
+ | Source | Meaning | When |
383
+ |--------|---------|------|
384
+ | `:api` | Official USNO data | `phases_for_month`, `phases_for_year`, etc. |
385
+ | `:interpolated` | Calculated between two API phases | `all_phases_for_month`, `all_phases_for_year`, etc. |
386
+ | `:calculated` | Pure synodic math model | `phase_at`, `illumination`, `current_phase` |
387
+
388
+ ```ruby
389
+ phase = MoonPhaseTracker.phase_at(Date.today)
390
+ phase.source # => :calculated
391
+ phase.illumination # => 65.3 (percent)
392
+ phase.lunar_age # => 10.2 (days since last new moon)
393
+ ```
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
173
413
 
174
- #### Major Phases (Official USNO Data)
175
- - 🌑 `:new_moon` - New Moon
176
- - 🌓 `:first_quarter` - First Quarter
177
- - 🌕 `:full_moon` - Full Moon
178
- - 🌗 `:last_quarter` - Last Quarter
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:
179
415
 
180
- #### Intermediate Phases (Interpolated ~85-90% accuracy)
181
- - 🌒 `:waxing_crescent` - Waxing Crescent
182
- - 🌔 `:waxing_gibbous` - Waxing Gibbous
183
- - 🌖 `:waning_gibbous` - Waning Gibbous
184
- - 🌘 `:waning_crescent` - Waning Crescent
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
185
419
 
186
- ## Data Source
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
+
563
+ ## ⚓ Our Trusted Cosmic Oracle
564
+
565
+ *We get our lunar wisdom from the finest source - the folks who navigate the seven seas by the stars.*
566
+
567
+ This gem uses the official US Naval Observatory (USNO) API - because when it comes to celestial navigation, you want the folks who've been steering ships by the stars for centuries:
187
568
 
188
- This gem uses the official US Naval Observatory (USNO) API:
189
569
  - **Base URL**: https://aa.usno.navy.mil/api/moon/phases/
190
- - **API Version**: 4.0.1
570
+ - **API Version**: 4.0.1 (battle-tested and Navy-approved)
191
571
  - **Documentation**: https://aa.usno.navy.mil/data/api
192
572
 
193
- All times are provided in Universal Time (UTC).
573
+ All times are provided in Universal Time (UTC) - because the moon doesn't care about your timezone preferences, and neither should precise astronomical data.
574
+
575
+ ## 🚦 Playing Nice with the Navy - Rate Limiting with Style
576
+
577
+ *Because even cosmic APIs need coffee breaks, and we're not monsters.*
194
578
 
195
- ## Rate Limiting
579
+ Think of rate limiting as the polite pause between questions when chatting with a wise oracle. We implement respectful rate limiting to keep the USNO Navy API happy (and responsive). By default, we're as patient as a monk - **1 request per second** with the restraint of a zen master.
196
580
 
197
- The gem implements respectful rate limiting to avoid overwhelming the USNO Navy API. By default, it allows **1 request per second** with a burst size of 1.
198
581
 
199
- ### Default Rate Limiting
582
+ ### 🧘 The Zen Approach - Default Rate Limiting
583
+
584
+ *Slow and steady wins the lunar race.*
200
585
 
201
586
  ```ruby
202
- # Default: 1 request per second
587
+ # Default: 1 request per second - the patient approach
203
588
  tracker = MoonPhaseTracker::Tracker.new
204
589
 
205
- # Check current rate limit configuration
590
+ # Check current rate limit configuration - know thy limits
206
591
  puts tracker.rate_limit_info
207
592
  # => {:requests_per_second=>1.0, :burst_size=>1, :available_tokens=>1}
208
593
 
209
- # Multiple requests will be automatically rate limited
594
+ # Multiple requests will be automatically rate limited - watch the magic
210
595
  start = Time.now
211
- tracker.phases_for_year(2025) # Immediate
212
- tracker.phases_for_year(2024) # Waits ~1 second
596
+ tracker.phases_for_year(2025) # Immediate (first one's free!)
597
+ tracker.phases_for_year(2024) # Waits ~1 second (patience, young padawan)
213
598
  puts "Total time: #{Time.now - start}s" # ~1.0 seconds
214
599
  ```
215
600
 
216
- ### Custom Rate Limiting
601
+ ### ⚡ Need for Speed? - Custom Rate Limiting
602
+
603
+ *For when you want to live life in the fast lane (but still be respectful).*
217
604
 
218
605
  ```ruby
219
- # Create custom rate limiter: 3 requests per second, burst of 2
606
+ # Create custom rate limiter: 3 requests per second, burst of 2 - living a little
220
607
  rate_limiter = MoonPhaseTracker::RateLimiter.new(
221
608
  requests_per_second: 3.0,
222
609
  burst_size: 2
@@ -224,16 +611,18 @@ rate_limiter = MoonPhaseTracker::RateLimiter.new(
224
611
 
225
612
  tracker = MoonPhaseTracker::Tracker.new(rate_limiter: rate_limiter)
226
613
 
227
- # Burst requests are immediate, then rate limited
228
- tracker.phases_for_year(2025) # Immediate
229
- tracker.phases_for_year(2024) # Immediate (burst)
230
- tracker.phases_for_year(2023) # Waits ~0.33 seconds
614
+ # Burst requests are immediate, then rate limited - controlled excitement
615
+ tracker.phases_for_year(2025) # Immediate (wheee!)
616
+ tracker.phases_for_year(2024) # Immediate (double wheee!)
617
+ tracker.phases_for_year(2023) # Waits ~0.33 seconds (and... breathe)
231
618
  ```
232
619
 
233
- ### Environment Variable Configuration
620
+ ### 🌍 Set It and Forget It - Environment Variables
621
+
622
+ *Configure once, smile forever.*
234
623
 
235
624
  ```ruby
236
- # Set via environment variables
625
+ # Set via environment variables - the lazy developer's paradise
237
626
  ENV["MOON_PHASE_RATE_LIMIT"] = "2.5"
238
627
  ENV["MOON_PHASE_BURST_SIZE"] = "3"
239
628
 
@@ -242,20 +631,24 @@ puts tracker.rate_limit_info
242
631
  # => {:requests_per_second=>2.5, :burst_size=>3, :available_tokens=>3}
243
632
  ```
244
633
 
245
- ### Disabling Rate Limiting
634
+ ### 🏁 Living Dangerously - Disabling Rate Limiting
635
+
636
+ *For the rebels and the reckless (use responsibly, dear lunar adventurer).*
246
637
 
247
638
  ```ruby
248
- # Disable rate limiting completely
639
+ # Disable rate limiting completely - for the speed demons
249
640
  ENV["MOON_PHASE_RATE_LIMIT"] = "0"
250
641
 
251
642
  tracker = MoonPhaseTracker::Tracker.new
252
- puts tracker.rate_limit_info # => nil
643
+ puts tracker.rate_limit_info # => nil (no limits, no safety net!)
253
644
 
254
- # Or pass nil explicitly
645
+ # Or pass nil explicitly - the explicit rebel
255
646
  tracker = MoonPhaseTracker::Tracker.new(rate_limiter: nil)
256
647
  ```
257
648
 
258
- ### Rate Limit Monitoring
649
+ ### 🔬 Under the Hood - Rate Limit Monitoring
650
+
651
+ *For the control freaks and performance enthusiasts among us.*
259
652
 
260
653
  ```ruby
261
654
  rate_limiter = MoonPhaseTracker::RateLimiter.new(
@@ -263,18 +656,20 @@ rate_limiter = MoonPhaseTracker::RateLimiter.new(
263
656
  burst_size: 2
264
657
  )
265
658
 
266
- # Check if request can proceed without waiting
267
- puts rate_limiter.can_proceed? # => true
659
+ # Check if request can proceed without waiting - the crystal ball
660
+ puts rate_limiter.can_proceed? # => true (or false if you've been naughty)
268
661
 
269
- # Check current token status
662
+ # Check current token status - your digital wallet
270
663
  puts rate_limiter.configuration
271
664
  # => {:requests_per_second=>1.0, :burst_size=>2, :available_tokens=>2}
272
665
 
273
- # Manual rate limiting control
274
- rate_limiter.throttle # Waits if necessary and consumes token
666
+ # Manual rate limiting control - take the wheel
667
+ rate_limiter.throttle # Waits if necessary and consumes token (om nom nom)
275
668
  ```
276
669
 
277
- ### Token Bucket Algorithm
670
+ ### 🪣 The Magic Behind the Curtain - Token Bucket Algorithm
671
+
672
+ *The elegant dance of digital tokens that keeps everything flowing smoothly.*
278
673
 
279
674
  The rate limiter uses a token bucket algorithm:
280
675
 
@@ -283,20 +678,28 @@ The rate limiter uses a token bucket algorithm:
283
678
  - **Refill Rate**: How quickly tokens are replenished
284
679
  - **Thread Safe**: Handles concurrent requests safely
285
680
 
286
- ## Development
681
+ ## 🛠️ Join the Lunar Development Cult
682
+
683
+ *Want to contribute to the cosmic cause? We welcome fellow moon enthusiasts!*
684
+
685
+ After checking out the repo, run `bin/setup` to install dependencies (like preparing your lunar laboratory). Then, run `rake spec` to run the tests (because even moon phases need quality control). You can also run `bin/console` for an interactive prompt that will allow you to experiment (perfect for midnight coding sessions under the actual moon).
287
686
 
288
- After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
687
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org) (sharing lunar magic with the world!).
289
688
 
290
- To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
689
+ ## 🤝 Become a Lunar Contributor
291
690
 
292
- ## Contributing
691
+ *Every great gem needs a community of stargazers and code wizards.*
293
692
 
294
- Bug reports and pull requests are welcome on GitHub at https://github.com/dklima/moon_phase_tracker. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/dklima/moon_phase_tracker/blob/main/CODE_OF_CONDUCT.md).
693
+ Bug reports and pull requests are welcome on GitHub at https://github.com/dklima/moon_phase_tracker. Found a bug? Think of it as discovering a new lunar crater - exciting stuff! This project is intended to be a safe, welcoming space for collaboration, where all contributors can shine as bright as a Full Moon. Contributors are expected to adhere to the [code of conduct](https://github.com/dklima/moon_phase_tracker/blob/main/CODE_OF_CONDUCT.md).
295
694
 
296
- ## License
695
+ ## 📜 Legal Lunar Stuff
696
+
697
+ *Even moon phases need proper paperwork.*
297
698
 
298
699
  The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
299
700
 
300
- ## Code of Conduct
701
+ ## 🌟 Lunar Community Guidelines
702
+
703
+ *We believe in creating a space as welcoming as moonlight on a summer evening.*
301
704
 
302
- Everyone interacting in the MoonPhaseTracker project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/dklima/moon_phase_tracker/blob/main/CODE_OF_CONDUCT.md).
705
+ Everyone interacting in the MoonPhaseTracker project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/dklima/moon_phase_tracker/blob/main/CODE_OF_CONDUCT.md). Together, we create a community as harmonious as the lunar cycles themselves.