repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/ephem.rb
lib/astronoby/ephem.rb
# frozen_string_literal: true require "ephem" module Astronoby class Ephem # Download an ephemeris file. # # @param name [String] Name of the ephemeris file, supported by the Ephem # gem # @param target [String] Location where to store the file # @return [Boolean] true if the download was successful, false otherwise # # @example Downloading de440t SPK from NASA JPL # Astronoby::Ephem.download(name: "de440t.bsp", target: "tmp/de440t.bsp") def self.download(name:, target:) ::Ephem::Download.call(name: name, target: target) end # Load an ephemeris file. # # @param target [String] Path of the ephemeris file # @return [::Ephem::SPK] Ephemeris object from the Ephem gem # # @example Loading previously downloaded de440t SPK from NASA JPL # Astronoby::Ephem.load("tmp/de440t.bsp") def self.load(target) spk = ::Ephem::SPK.open(target) unless ::Ephem::SPK::TYPES.include?(spk&.type) raise( EphemerisError, "#{target} is not a valid type. Accepted: #{::Ephem::SPK::TYPES.join(", ")}" ) end spk end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/refraction.rb
lib/astronoby/refraction.rb
# frozen_string_literal: true module Astronoby class Refraction LOW_ALTITUDE_BODY_ANGLE = Angle.from_degrees(15) ZENITH = Angle.from_degrees(90) def self.angle(coordinates:) new(coordinates).refraction_angle end def self.correct_horizontal_coordinates(coordinates:) new(coordinates).refract end def initialize(coordinates) @coordinates = coordinates end # Source: # Title: Practical Astronomy with your Calculator or Spreadsheet # Authors: Peter Duffett-Smith and Jonathan Zwart # Edition: Cambridge University Press # Chapter: 37 - Refraction def refract Coordinates::Horizontal.new( azimuth: @coordinates.azimuth, altitude: @coordinates.altitude + refraction_angle, observer: @coordinates.observer ) end def refraction_angle if @coordinates.altitude > LOW_ALTITUDE_BODY_ANGLE high_altitude_angle else low_altitude_angle end end private def pressure @_pressure ||= @coordinates.observer.pressure end def temperature @_temperature ||= @coordinates.observer.temperature end def altitude_in_degrees @_altitude_in_degrees ||= @coordinates.altitude.degrees end def high_altitude_angle zenith_angle = ZENITH - @coordinates.altitude Angle.from_degrees(0.00452 * pressure * zenith_angle.tan / temperature) end def low_altitude_angle term1 = pressure * ( 0.1594 + 0.0196 * altitude_in_degrees + 0.00002 * altitude_in_degrees**2 ) term2 = temperature * ( 1 + 0.505 * altitude_in_degrees + 0.0845 * altitude_in_degrees**2 ) Angle.from_degrees(term1 / term2) end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/reference_frame.rb
lib/astronoby/reference_frame.rb
# frozen_string_literal: true module Astronoby class ReferenceFrame attr_reader :position, :velocity, :instant, :center_identifier, :target_body def initialize( position:, velocity:, instant:, center_identifier:, target_body: ) @position = position @velocity = velocity @instant = instant @center_identifier = center_identifier @target_body = target_body end def equatorial @equatorial ||= begin return Coordinates::Equatorial.zero if distance.zero? Coordinates::Equatorial.from_position_vector(@position) end end def ecliptic @ecliptic ||= begin return Coordinates::Ecliptic.zero if distance.zero? j2000 = Instant.from_terrestrial_time(JulianDate::J2000) equatorial.to_ecliptic(instant: j2000) end end def distance @distance ||= begin return Distance.zero if @position.zero? @position.magnitude end end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/precession.rb
lib/astronoby/precession.rb
# frozen_string_literal: true module Astronoby class Precession def self.matrix_for(instant) new(instant: instant).matrix end def initialize(instant:) @instant = instant end def matrix # Source: # IAU resolution in 2006 in favor of the P03 astronomical model # https://syrte.obspm.fr/iau2006/aa03_412_P03.pdf # P(t) = R3(χA) R1(−ωA) R3(−ψA) R1(ϵ0) cache.fetch(cache_key) do # Precession in right ascension psi_a = (((( -0.0000000951 * t + +0.000132851) * t + -0.00114045) * t + -1.0790069) * t + +5038.481507) * t # Precession in declination omega_a = (((( +0.0000003337 * t + -0.000000467) * t + -0.00772503) * t + +0.0512623) * t + -0.025754) * t + eps0 # Precession of the ecliptic chi_a = (((( -0.0000000560 * t + +0.000170663) * t + -0.00121197) * t + -2.3814292) * t + +10.556403) * t psi_a = Angle.from_degree_arcseconds(psi_a) omega_a = Angle.from_degree_arcseconds(omega_a) chi_a = Angle.from_degree_arcseconds(chi_a) r3_psi = rotation_z(-psi_a) r1_omega = rotation_x(-omega_a) r3_chi = rotation_z(chi_a) r1_eps0 = rotation_x(MeanObliquity.obliquity_of_reference) r3_chi * r1_omega * r3_psi * r1_eps0 end end def rotation_x(angle) c, s = angle.cos, angle.sin Matrix[ [1, 0, 0], [0, c, s], [0, -s, c] ] end def rotation_z(angle) c, s = angle.cos, angle.sin Matrix[ [c, s, 0], [-s, c, 0], [0, 0, 1] ] end # Source: # Title: Practical Astronomy with your Calculator or Spreadsheet # Authors: Peter Duffett-Smith and Jonathan Zwart # Edition: Cambridge University Press # Chapter: 34 - Precession def self.for_equatorial_coordinates(coordinates:, epoch:) precess(coordinates, epoch) end def self.precess(coordinates, epoch) matrix_a = matrix_for_epoch(coordinates.epoch) matrix_b = matrix_for_epoch(epoch).transpose vector = Vector[ coordinates.right_ascension.cos * coordinates.declination.cos, coordinates.right_ascension.sin * coordinates.declination.cos, coordinates.declination.sin ] s = matrix_a * vector w = matrix_b * s Coordinates::Equatorial.new( right_ascension: Util::Trigonometry.adjustement_for_arctangent( Angle.from_radians(w[1]), Angle.from_radians(w[0]), Angle.atan(w[1] / w[0]) ), declination: Angle.asin(w[2]), epoch: epoch ) end def self.matrix_for_epoch(epoch) t = (epoch - JulianDate::DEFAULT_EPOCH) / Constants::DAYS_PER_JULIAN_CENTURY zeta = Angle.from_degrees( 0.6406161 * t + 0.0000839 * t * t + 0.000005 * t * t * t ) z = Angle.from_degrees( 0.6406161 * t + 0.0003041 * t * t + 0.0000051 * t * t * t ) theta = Angle.from_degrees( 0.5567530 * t - 0.0001185 * t * t - 0.0000116 * t * t * t ) cx = zeta.cos sx = zeta.sin cz = z.cos sz = z.sin ct = theta.cos st = theta.sin Matrix[ [ cx * ct * cz - sx * sz, cx * ct * sz + sx * cz, cx * st ], [ -sx * ct * cz - cx * sz, -sx * ct * sz + cx * cz, -sx * st ], [ -st * cz, -st * sz, ct ] ] end private def cache_key @_cache_key ||= CacheKey.generate(:precession, @instant) end def cache Astronoby.cache end def t @t ||= Rational( @instant.tdb - JulianDate::DEFAULT_EPOCH, Constants::DAYS_PER_JULIAN_CENTURY ) end def eps0 @eps0 ||= MeanObliquity.obliquity_of_reference_in_arcseconds end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/aberration.rb
lib/astronoby/aberration.rb
# frozen_string_literal: true module Astronoby # Applies relativistic aberration corrections to an astrometric position based # on observer velocity. class Aberration # Source: # Title: Explanatory Supplement to the Astronomical Almanac # Authors: Sean E. Urban and P. Kenneth Seidelmann # Edition: University Science Books # Chapter: 7.2.3 - Aberration LIGHT_SPEED = Astronoby::Velocity.light_speed.mps # Initializes the aberration correction with position and observer velocity. # # @param astrometric_position [Astronoby::Vector<Astronoby::Distance>] The # astrometric position vector. # @param observer_velocity [Astronoby::Vector<Astronoby::Velocity>] The # velocity vector of the observer. def initialize(astrometric_position:, observer_velocity:) @position = astrometric_position @velocity = observer_velocity @distance_meters = @position.norm.m @observer_speed = @velocity.norm.mps end # Computes the aberration-corrected position. # # @return [Astronoby::Vector<Astronoby::Distance>] The corrected position # vector. def corrected_position beta = @observer_speed / LIGHT_SPEED projected_velocity = beta * aberration_angle_cos lorentz_factor_inv = lorentz_factor_inverse(beta) velocity_correction = velocity_correction_factor(projected_velocity) * velocity_mps normalization_factor = 1.0 + projected_velocity position_scaled = position_meters * lorentz_factor_inv Distance.vector_from_meters( (position_scaled + velocity_correction) / normalization_factor ) end private def aberration_angle_cos denominator = [@distance_meters * @observer_speed, 1e-20].max Util::Maths.dot_product(position_meters, velocity_mps) / denominator end def position_meters @position.map(&:meters) end def velocity_mps @velocity.map(&:mps) end def lorentz_factor_inverse(beta) Math.sqrt(1.0 - beta**2) end def velocity_correction_factor(projected_velocity) lorentz_inv = lorentz_factor_inverse(projected_velocity) (1.0 + projected_velocity / (1.0 + lorentz_inv)) * (@distance_meters / LIGHT_SPEED) end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/cache.rb
lib/astronoby/cache.rb
# frozen_string_literal: true require "monitor" require "singleton" module Astronoby class Cache include Singleton Entry = Struct.new(:key, :value, :prev, :next) DEFAULT_MAX_SIZE = 10_000 attr_reader :max_size # @param max_size [Integer] Maximum number of entries allowed in the cache # @return [void] def initialize(max_size = DEFAULT_MAX_SIZE) @max_size = max_size @hash = {} @head = nil @tail = nil @mutex = Monitor.new end # @param key [Object] the cache key # @return [Object, nil] the value, or nil if not found def [](key) @mutex.synchronize do entry = @hash[key] if entry move_to_head(entry) entry.value end end end # @param key [Object] # @param value [Object] # @return [Object] the value set def []=(key, value) @mutex.synchronize do entry = @hash[key] if entry entry.value = value move_to_head(entry) else entry = Entry.new(key, value) add_to_head(entry) @hash[key] = entry evict_last_recently_used if @hash.size > @max_size end end end # @param key [Object] # @yieldreturn [Object] Value to store if key is missing. # @return [Object] Cached or computed value. def fetch(key) return self[key] if @mutex.synchronize { @hash.key?(key) } value = yield @mutex.synchronize do self[key] = value unless @hash.key?(key) end value end # @return [void] def clear @mutex.synchronize do @hash.clear @head = @tail = nil end end # @return [Integer] def size @mutex.synchronize { @hash.size } end # @param new_size [Integer] the new cache limit. # @return [void] def max_size=(new_size) raise ArgumentError, "max_size must be positive" unless new_size > 0 @mutex.synchronize do @max_size = new_size while @hash.size > @max_size evict_last_recently_used end end end private def add_to_head(entry) entry.prev = nil entry.next = @head @head.prev = entry if @head @head = entry @tail ||= entry end def move_to_head(entry) return if @head == entry # Unlink entry.prev.next = entry.next if entry.prev entry.next.prev = entry.prev if entry.next # Update tail if needed @tail = entry.prev if @tail == entry # Insert as new head entry.prev = nil entry.next = @head @head.prev = entry if @head @head = entry end def evict_last_recently_used if @tail @hash.delete(@tail.key) if @tail.prev @tail = @tail.prev @tail.next = nil else @head = @tail = nil end end end end class NullCache include Singleton def [](key) nil end def []=(key, value) value end def fetch(key) yield end def clear end def size 0 end def max_size=(new_size) end end class CacheKey class << self # Generate a cache key with appropriate precision # @param type [Symbol] The calculation type (e.g., :geometric, :nutation) # @param instant [Astronoby::Instant] The time instant # @param components [Array] Additional components for the key # @return [Array] The complete cache key def generate(type, instant, *components) return nil unless Astronoby.configuration.cache_enabled? precision = Astronoby.configuration.cache_precision(type) rounded_tt = round_terrestrial_time(instant.tt, precision) [type, rounded_tt, *components] end # Round terrestrial time to specified precision # @param tt [Numeric] Terrestrial time value # @param precision [Numeric] Precision in seconds # @return [Numeric] Rounded time value def round_terrestrial_time(tt, precision) return tt if precision <= 0 tt.round(precision) end end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/true_obliquity.rb
lib/astronoby/true_obliquity.rb
# frozen_string_literal: true module Astronoby class TrueObliquity def self.at(instant) mean_obliquity = MeanObliquity.at(instant) nutation = Nutation.new(instant: instant).nutation_in_obliquity mean_obliquity + nutation end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/bodies/deep_sky_object_position.rb
lib/astronoby/bodies/deep_sky_object_position.rb
# frozen_string_literal: true module Astronoby class DeepSkyObjectPosition DEFAULT_DISTANCE = Distance.from_parsecs(1e9) attr_reader :instant, :apparent # @param instant [Astronoby::Instant] Instant of the observation # @param equatorial_coordinates [Astronoby::Coordinates::Equatorial] # Equatorial coordinates at epoch J2000.0 # @param proper_motion_ra [Astronoby::AngularVelocity, nil] Proper motion in # right ascension # @param proper_motion_dec [Astronoby::AngularVelocity, nil] Proper motion # in declination # @param parallax [Astronoby::Angle, nil] Parallax angle # @param radial_velocity [Astronoby::Velocity, nil] Radial velocity def initialize( instant:, equatorial_coordinates:, ephem: nil, proper_motion_ra: nil, proper_motion_dec: nil, parallax: nil, radial_velocity: nil ) @instant = instant @initial_equatorial_coordinates = equatorial_coordinates @proper_motion_ra = proper_motion_ra @proper_motion_dec = proper_motion_dec @parallax = parallax @radial_velocity = radial_velocity if ephem @earth_geometric = Earth.geometric(ephem: ephem, instant: @instant) end compute_apparent end # @return [Astronoby::Astrometric] Astrometric position of the object def astrometric @astrometric ||= Astrometric.new( instant: @instant, position: astrometric_position, velocity: astrometric_velocity, center_identifier: SolarSystemBody::EARTH, target_body: self ) end def observed_by(observer) Topocentric.build_from_apparent( apparent: @apparent, observer: observer, instant: @instant, target_body: self ) end private def astrometric_position @astrometric_position ||= if use_stellar_propagation? stellar_propagation.position else astronomical_distance = DEFAULT_DISTANCE.meters right_ascension = @initial_equatorial_coordinates.right_ascension declination = @initial_equatorial_coordinates.declination Distance.vector_from_meters([ declination.cos * right_ascension.cos * astronomical_distance, declination.cos * right_ascension.sin * astronomical_distance, declination.sin * astronomical_distance ]) end end def astrometric_velocity @astrometric_velocity ||= if use_stellar_propagation? stellar_propagation.velocity_vector else Velocity.vector_from_meters_per_second([0.0, 0.0, 0.0]) end end def use_stellar_propagation? @proper_motion_ra && @proper_motion_dec && @parallax && @radial_velocity end def stellar_propagation @stellar_propagation ||= StellarPropagation.new( equatorial_coordinates: @initial_equatorial_coordinates, proper_motion_ra: @proper_motion_ra, proper_motion_dec: @proper_motion_dec, parallax: @parallax, radial_velocity: @radial_velocity, instant: @instant, earth_geometric: @earth_geometric ) end def compute_apparent @apparent = if @earth_geometric Apparent.build_from_astrometric( instant: @instant, target_astrometric: astrometric, earth_geometric: @earth_geometric, target_body: self ) else precession_matrix = Precession.matrix_for(@instant) nutation_matrix = Nutation.matrix_for(@instant) corrected_position = Distance.vector_from_meters( precession_matrix * nutation_matrix * astrometric.position.map(&:m) ) corrected_velocity = Velocity.vector_from_mps( precession_matrix * nutation_matrix * astrometric.velocity.map(&:mps) ) Apparent.new( position: corrected_position, velocity: corrected_velocity, instant: @instant, center_identifier: SolarSystemBody::EARTH, target_body: self ) end end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/bodies/saturn.rb
lib/astronoby/bodies/saturn.rb
# frozen_string_literal: true module Astronoby class Saturn < SolarSystemBody EQUATORIAL_RADIUS = Distance.from_meters(60_268_000) ABSOLUTE_MAGNITUDE = -8.914 def self.ephemeris_segments(_ephem_source) [[SOLAR_SYSTEM_BARYCENTER, SATURN_BARYCENTER]] end def self.absolute_magnitude ABSOLUTE_MAGNITUDE end private # Source: # Title: Computing Apparent Planetary Magnitudes for The Astronomical # Almanac (2018) # Authors: Anthony Mallama and James L. Hilton def magnitude_correction_term phase_angle_degrees = phase_angle.degrees if phase_angle_degrees <= 6 -0.036 - 3.7 * 10**-4 * phase_angle_degrees + 6.16 * 10**-4 * phase_angle_degrees * phase_angle_degrees else 0.026 + 2.446 * 10**-4 * phase_angle_degrees + 2.672 * 10**-4 * phase_angle_degrees * phase_angle_degrees - 1.505 * 10**-6 * phase_angle_degrees**3 + 4.767 * 10**-9 * phase_angle_degrees**4 end end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/bodies/deep_sky_object.rb
lib/astronoby/bodies/deep_sky_object.rb
# frozen_string_literal: true module Astronoby class DeepSkyObject # @param equatorial_coordinates [Astronoby::Coordinates::Equatorial] # Equatorial coordinates at epoch J2000.0 # @param proper_motion_ra [Astronoby::AngularVelocity, nil] Proper motion in # right ascension # @param proper_motion_dec [Astronoby::AngularVelocity, nil] Proper motion # in declination # @param parallax [Astronoby::Angle, nil] Parallax angle # @param radial_velocity [Astronoby::Velocity, nil] Radial velocity def initialize( equatorial_coordinates:, proper_motion_ra: nil, proper_motion_dec: nil, parallax: nil, radial_velocity: nil ) @initial_equatorial_coordinates = equatorial_coordinates @proper_motion_ra = proper_motion_ra @proper_motion_dec = proper_motion_dec @parallax = parallax @radial_velocity = radial_velocity end # @param instant [Astronoby::Instant] Instant of the observation # @param ephem [Astronoby::Ephemeris, nil] Ephemeris to use for Earth # position calculation # @return [Astronoby::DeepSkyObjectPosition] Position of the deep-sky object # at the given instant def at(instant, ephem: nil) DeepSkyObjectPosition.new( instant: instant, equatorial_coordinates: @initial_equatorial_coordinates, ephem: ephem, proper_motion_ra: @proper_motion_ra, proper_motion_dec: @proper_motion_dec, parallax: @parallax, radial_velocity: @radial_velocity ) end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/bodies/sun.rb
lib/astronoby/bodies/sun.rb
# frozen_string_literal: true module Astronoby class Sun < SolarSystemBody EQUATORIAL_RADIUS = Distance.from_meters(695_700_000) ABSOLUTE_MAGNITUDE = -26.74 def self.ephemeris_segments(_ephem_source) [[SOLAR_SYSTEM_BARYCENTER, SUN]] end def self.absolute_magnitude ABSOLUTE_MAGNITUDE end # Source: # Title: Explanatory Supplement to the Astronomical Almanac # Authors: Sean E. Urban and P. Kenneth Seidelmann # Edition: University Science Books # Chapter: 10.3 - Phases and Magnitudes # Apparent magnitude of the body, as seen from Earth. # @return [Float] Apparent magnitude of the body. def apparent_magnitude @apparent_magnitude ||= self.class.absolute_magnitude + 5 * Math.log10(astrometric.distance.au) end # Source: # Title: Astronomical Algorithms # Author: Jean Meeus # Edition: 2nd edition # Chapter: 28 - Equation of Time # @return [Integer] Equation of time in seconds def equation_of_time right_ascension = apparent.equatorial.right_ascension t = (@instant.julian_date - JulianDate::J2000) / Constants::DAYS_PER_JULIAN_MILLENIA l0 = (280.4664567 + 360_007.6982779 * t + 0.03032028 * t**2 + t**3 / 49_931 - t**4 / 15_300 - t**5 / 2_000_000) % Constants::DEGREES_PER_CIRCLE nutation = Nutation.new(instant: instant).nutation_in_longitude obliquity = TrueObliquity.at(@instant) ( Angle .from_degrees( l0 - Constants::EQUATION_OF_TIME_CONSTANT - right_ascension.degrees + nutation.degrees * obliquity.cos ).hours * Constants::SECONDS_PER_HOUR ).round end private def requires_sun_data? false end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/bodies/mars.rb
lib/astronoby/bodies/mars.rb
# frozen_string_literal: true module Astronoby class Mars < SolarSystemBody EQUATORIAL_RADIUS = Distance.from_meters(3_396_200) ABSOLUTE_MAGNITUDE = -1.601 def self.ephemeris_segments(_ephem_source) [[SOLAR_SYSTEM_BARYCENTER, MARS_BARYCENTER]] end def self.absolute_magnitude ABSOLUTE_MAGNITUDE end private # Source: # Title: Computing Apparent Planetary Magnitudes for The Astronomical # Almanac (2018) # Authors: Anthony Mallama and James L. Hilton def magnitude_correction_term phase_angle_degrees = phase_angle.degrees 2.267 * 10**-2 * phase_angle_degrees - 1.302 * 10**-4 * phase_angle_degrees * phase_angle_degrees end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/bodies/mercury.rb
lib/astronoby/bodies/mercury.rb
# frozen_string_literal: true module Astronoby class Mercury < SolarSystemBody EQUATORIAL_RADIUS = Distance.from_meters(2_439_700) ABSOLUTE_MAGNITUDE = -0.613 def self.ephemeris_segments(_ephem_source) [[SOLAR_SYSTEM_BARYCENTER, MERCURY_BARYCENTER]] end def self.absolute_magnitude ABSOLUTE_MAGNITUDE end private # Source: # Title: Computing Apparent Planetary Magnitudes for The Astronomical # Almanac (2018) # Authors: Anthony Mallama and James L. Hilton def magnitude_correction_term phase_angle_degrees = phase_angle.degrees 6.328 * 10**-2 * phase_angle_degrees - 1.6336 * 10**-3 * phase_angle_degrees * phase_angle_degrees + 3.3634 * 10**-5 * phase_angle_degrees**3 - 3.4265 * 10**-7 * phase_angle_degrees**4 + 1.6893 * 10**-9 * phase_angle_degrees**5 - 3.0334 * 10**-12 * phase_angle_degrees**6 end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/bodies/venus.rb
lib/astronoby/bodies/venus.rb
# frozen_string_literal: true module Astronoby class Venus < SolarSystemBody EQUATORIAL_RADIUS = Distance.from_meters(6_051_800) ABSOLUTE_MAGNITUDE = -4.384 def self.ephemeris_segments(_ephem_source) [[SOLAR_SYSTEM_BARYCENTER, VENUS_BARYCENTER]] end def self.absolute_magnitude ABSOLUTE_MAGNITUDE end private # Source: # Title: Computing Apparent Planetary Magnitudes for The Astronomical # Almanac (2018) # Authors: Anthony Mallama and James L. Hilton def magnitude_correction_term phase_angle_degrees = phase_angle.degrees if phase_angle_degrees < 163.7 -1.044 * 10**-3 * phase_angle_degrees + 3.687 * 10**-4 * phase_angle_degrees * phase_angle_degrees - 2.814 * 10**-6 * phase_angle_degrees**3 + 8.938 * 10**-9 * phase_angle_degrees**4 else 240.44228 - 2.81914 * phase_angle_degrees + 8.39034 * 10**-3 * phase_angle_degrees * phase_angle_degrees end end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/bodies/earth.rb
lib/astronoby/bodies/earth.rb
# frozen_string_literal: true module Astronoby class Earth < SolarSystemBody def self.ephemeris_segments(ephem_source) if ephem_source == ::Ephem::SPK::JPL_DE [ [SOLAR_SYSTEM_BARYCENTER, EARTH_MOON_BARYCENTER], [EARTH_MOON_BARYCENTER, EARTH] ] elsif ephem_source == ::Ephem::SPK::INPOP [ [SOLAR_SYSTEM_BARYCENTER, EARTH] ] end end def phase_angle nil end private # Attributes that require Sun data like phase angle or magnitude are not # applicable for Earth. def requires_sun_data? true end def compute_astrometric(_ephem) Astrometric.new( position: Vector[ Distance.zero, Distance.zero, Distance.zero ], velocity: Vector[ Velocity.zero, Velocity.zero, Velocity.zero ], instant: @instant, center_identifier: EARTH, target_body: self.class ) end def compute_mean_of_date(_ephem) MeanOfDate.new( position: Vector[ Distance.zero, Distance.zero, Distance.zero ], velocity: Vector[ Velocity.zero, Velocity.zero, Velocity.zero ], instant: @instant, center_identifier: EARTH, target_body: self.class ) end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/bodies/jupiter.rb
lib/astronoby/bodies/jupiter.rb
# frozen_string_literal: true module Astronoby class Jupiter < SolarSystemBody EQUATORIAL_RADIUS = Distance.from_meters(71_492_000) ABSOLUTE_MAGNITUDE = -9.395 def self.ephemeris_segments(_ephem_source) [[SOLAR_SYSTEM_BARYCENTER, JUPITER_BARYCENTER]] end def self.absolute_magnitude ABSOLUTE_MAGNITUDE end private # Source: # Title: Computing Apparent Planetary Magnitudes for The Astronomical # Almanac (2018) # Authors: Anthony Mallama and James L. Hilton def magnitude_correction_term phase_angle_degrees = phase_angle.degrees -3.7 * 10**-4 * phase_angle_degrees + 6.16 * 10**-4 * phase_angle_degrees * phase_angle_degrees end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/bodies/moon.rb
lib/astronoby/bodies/moon.rb
# frozen_string_literal: true module Astronoby class Moon < SolarSystemBody SEMIDIAMETER_VARIATION = 0.7275 EQUATORIAL_RADIUS = Distance.from_meters(1_737_400) ABSOLUTE_MAGNITUDE = 0.28 def self.ephemeris_segments(ephem_source) if ephem_source == ::Ephem::SPK::JPL_DE [ [SOLAR_SYSTEM_BARYCENTER, EARTH_MOON_BARYCENTER], [EARTH_MOON_BARYCENTER, MOON] ] elsif ephem_source == ::Ephem::SPK::INPOP [ [SOLAR_SYSTEM_BARYCENTER, EARTH], [EARTH, MOON] ] end end # Source: # Title: Astronomical Algorithms # Author: Jean Meeus # Edition: 2nd edition # Chapter: 49 - Phases of the Moon # @param year [Integer] Requested year # @param month [Integer] Requested month # @return [Array<Astronoby::MoonPhase>] Moon phases for the requested year def self.monthly_phase_events(year:, month:) Events::MoonPhases.phases_for(year: year, month: month) end def self.absolute_magnitude ABSOLUTE_MAGNITUDE end # @return [Float] Phase fraction, from 0 to 1 def current_phase_fraction mean_elongation.degrees / Constants::DEGREES_PER_CIRCLE end # @return [Boolean] True if the body is approaching the primary # body (Earth), false otherwise. def approaching_primary? relative_position = (geometric.position - @earth_geometric.position).map(&:m) relative_velocity = (geometric.velocity - @earth_geometric.velocity).map(&:mps) radial_velocity_component = Astronoby::Util::Maths .dot_product(relative_position, relative_velocity) distance = Math.sqrt( Astronoby::Util::Maths.dot_product(relative_position, relative_position) ) radial_velocity_component / distance < 0 end # @return [Boolean] True if the body is receding from the primary # body (Earth), false otherwise. def receding_from_primary? !approaching_primary? end private # Source: # Title: Astronomical Algorithms # Author: Jean Meeus # Edition: 2nd edition # Chapter: 48 - Illuminated Fraction of the Moon's Disk def mean_elongation @mean_elongation ||= Angle.from_degrees( ( 297.8501921 + 445267.1114034 * elapsed_centuries - 0.0018819 * elapsed_centuries**2 + elapsed_centuries**3 / 545868 - elapsed_centuries**4 / 113065000 ) % 360 ) end def elapsed_centuries (@instant.tt - JulianDate::DEFAULT_EPOCH) / Constants::DAYS_PER_JULIAN_CENTURY end private # Source: # Title: Computing Apparent Planetary Magnitudes for The Astronomical # Almanac (2018) # Authors: Anthony Mallama and James L. Hilton def magnitude_correction_term phase_angle_degrees = phase_angle.degrees if phase_angle_degrees <= 150 && current_phase_fraction <= 0.5 2.9994 * 10**-2 * phase_angle_degrees - 1.6057 * 10**-4 * phase_angle_degrees**2 + 3.1543 * 10**-6 * phase_angle_degrees**3 - 2.0667 * 10**-8 * phase_angle_degrees**4 + 6.2553 * 10**-11 * phase_angle_degrees**5 elsif phase_angle_degrees <= 150 && current_phase_fraction > 0.5 3.3234 * 10**-2 * phase_angle_degrees - 3.0725 * 10**-4 * phase_angle_degrees**2 + 6.1575 * 10**-6 * phase_angle_degrees**3 - 4.7723 * 10**-8 * phase_angle_degrees**4 + 1.4681 * 10**-10 * phase_angle_degrees**5 else super end end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/bodies/uranus.rb
lib/astronoby/bodies/uranus.rb
# frozen_string_literal: true module Astronoby class Uranus < SolarSystemBody EQUATORIAL_RADIUS = Distance.from_meters(25_559_000) ABSOLUTE_MAGNITUDE = -7.11 def self.ephemeris_segments(_ephem_source) [[SOLAR_SYSTEM_BARYCENTER, URANUS_BARYCENTER]] end def self.absolute_magnitude ABSOLUTE_MAGNITUDE end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/bodies/neptune.rb
lib/astronoby/bodies/neptune.rb
# frozen_string_literal: true module Astronoby class Neptune < SolarSystemBody EQUATORIAL_RADIUS = Distance.from_meters(24_764_000) ABSOLUTE_MAGNITUDE = -7.0 def self.ephemeris_segments(_ephem_source) [[SOLAR_SYSTEM_BARYCENTER, NEPTUNE_BARYCENTER]] end def self.absolute_magnitude ABSOLUTE_MAGNITUDE end private # Source: # Title: Computing Apparent Planetary Magnitudes for The Astronomical # Almanac (2018) # Authors: Anthony Mallama and James L. Hilton def magnitude_correction_term phase_angle_degrees = phase_angle.degrees if phase_angle_degrees < 133 && @instant.tt > JulianDate::J2000 7.944 * 10**-3 * phase_angle_degrees + 9.617 * 10**-5 * phase_angle_degrees * phase_angle_degrees else super end end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/bodies/solar_system_body.rb
lib/astronoby/bodies/solar_system_body.rb
# frozen_string_literal: true module Astronoby class SolarSystemBody SOLAR_SYSTEM_BARYCENTER = 0 SUN = 10 MERCURY_BARYCENTER = 1 MERCURY = 199 VENUS_BARYCENTER = 2 VENUS = 299 EARTH_MOON_BARYCENTER = 3 EARTH = 399 MOON = 301 MARS_BARYCENTER = 4 JUPITER_BARYCENTER = 5 SATURN_BARYCENTER = 6 URANUS_BARYCENTER = 7 NEPTUNE_BARYCENTER = 8 attr_reader :geometric, :instant def self.at(instant, ephem:) new(ephem: ephem, instant: instant) end def self.geometric(ephem:, instant:) compute_geometric(ephem: ephem, instant: instant) end def self.compute_geometric(ephem:, instant:) segments = ephemeris_segments(ephem.type) segment1 = segments[0] segment2 = segments[1] if segments.size == 2 cache_key = CacheKey.generate(:geometric, instant, segment1, segment2) Astronoby.cache.fetch(cache_key) do state1 = ephem[*segment1].state_at(instant.tt) if segment2 state2 = ephem[*segment2].state_at(instant.tt) position = state1.position + state2.position velocity = state1.velocity + state2.velocity else position = state1.position velocity = state1.velocity end position_vector = Vector[ Distance.from_kilometers(position.x), Distance.from_kilometers(position.y), Distance.from_kilometers(position.z) ] velocity_vector = Vector[ Velocity.from_kilometers_per_day(velocity.x), Velocity.from_kilometers_per_day(velocity.y), Velocity.from_kilometers_per_day(velocity.z) ] Geometric.new( position: position_vector, velocity: velocity_vector, instant: instant, target_body: self ) end end def self.ephemeris_segments(_ephem_source) raise NotImplementedError end def self.absolute_magnitude nil end def initialize(ephem:, instant:) @instant = instant @geometric = compute_geometric(ephem) @earth_geometric = Earth.geometric(ephem: ephem, instant: instant) @light_time_corrected_position, @light_time_corrected_velocity = Correction::LightTimeDelay.compute( center: @earth_geometric, target: @geometric, ephem: ephem ) compute_sun(ephem) if requires_sun_data? end def astrometric @astrometric ||= Astrometric.build_from_geometric( instant: @instant, earth_geometric: @earth_geometric, light_time_corrected_position: @light_time_corrected_position, light_time_corrected_velocity: @light_time_corrected_velocity, target_body: self ) end def mean_of_date @mean_of_date ||= MeanOfDate.build_from_geometric( instant: @instant, target_geometric: @geometric, earth_geometric: @earth_geometric, target_body: self ) end def apparent @apparent ||= Apparent.build_from_astrometric( instant: @instant, target_astrometric: astrometric, earth_geometric: @earth_geometric, target_body: self ) end def observed_by(observer) Topocentric.build_from_apparent( apparent: apparent, observer: observer, instant: @instant, target_body: self ) end # Returns the constellation of the body # @return [Astronoby::Constellation, nil] def constellation @constellation ||= Constellations::Finder.find( Precession.for_equatorial_coordinates( coordinates: astrometric.equatorial, epoch: JulianDate::B1875 ) ) end # Source: # Title: Astronomical Algorithms # Author: Jean Meeus # Edition: 2nd edition # Chapter: 48 - Illuminated Fraction of the Moon's Disk # @return [Astronoby::Angle, nil] Phase angle of the body def phase_angle return unless @sun @phase_angle ||= begin geocentric_elongation = Angle.acos( @sun.apparent.equatorial.declination.sin * apparent.equatorial.declination.sin + @sun.apparent.equatorial.declination.cos * apparent.equatorial.declination.cos * ( @sun.apparent.equatorial.right_ascension - apparent.equatorial.right_ascension ).cos ) term1 = @sun.astrometric.distance.km * geocentric_elongation.sin term2 = astrometric.distance.km - @sun.astrometric.distance.km * geocentric_elongation.cos angle = Angle.atan(term1 / term2) Astronoby::Util::Trigonometry .adjustement_for_arctangent(term1, term2, angle) end end # Fraction between 0 and 1 of the body's disk that is illuminated. # @return [Float, nil] Body's illuminated fraction, between 0 and 1. def illuminated_fraction return unless phase_angle @illuminated_fraction ||= (1 + phase_angle.cos) / 2.0 end # Source: # Title: Astronomical Algorithms # Author: Jean Meeus # Edition: 2nd edition # Chapter: 48 - Illuminated Fraction of the Moon's Disk # Apparent magnitude of the body, as seen from Earth. # @return [Float, nil] Apparent magnitude of the body. def apparent_magnitude return unless self.class.absolute_magnitude @apparent_magnitude ||= begin body_sun_distance = (astrometric.position - @sun.astrometric.position).magnitude self.class.absolute_magnitude + 5 * Math.log10(body_sun_distance.au * astrometric.distance.au) + magnitude_correction_term end end # Angular diameter of the body, as seen from Earth. Based on the apparent # position of the body. # @return [Astronoby::Angle] Angular diameter of the body def angular_diameter @angular_radius ||= begin return if apparent.position.zero? Angle.from_radians( Math.asin(self.class::EQUATORIAL_RADIUS.m / apparent.distance.m) * 2 ) end end # @return [Boolean] True if the body is approaching the primary # body (Sun), false otherwise. def approaching_primary? relative_position = (geometric.position - @sun.geometric.position).map(&:m) relative_velocity = (geometric.velocity - @sun.geometric.velocity).map(&:mps) radial_velocity_component = Astronoby::Util::Maths .dot_product(relative_position, relative_velocity) distance = Math.sqrt( Astronoby::Util::Maths.dot_product(relative_position, relative_position) ) radial_velocity_component / distance < 0 end # @return [Boolean] True if the body is receding from the primary # body (Sun), false otherwise. def receding_from_primary? !approaching_primary? end private # By default, Solar System bodies expose attributes that are dependent on # the Sun's position, such as phase angle and illuminated fraction. # If a body does not require Sun data, it should override this method to # return false. def requires_sun_data? true end def compute_geometric(ephem) self.class.compute_geometric(ephem: ephem, instant: @instant) end def compute_sun(ephem) @sun ||= Sun.new(instant: @instant, ephem: ephem) end # Source: # Title: Explanatory Supplement to the Astronomical Almanac # Authors: Sean E. Urban and P. Kenneth Seidelmann # Edition: University Science Books # Chapter: 10.3 - Phases and Magnitudes def magnitude_correction_term -2.5 * Math.log10(illuminated_fraction) end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/util/time.rb
lib/astronoby/util/time.rb
# frozen_string_literal: true module Astronoby module Util module Time OLD_LEAP_SECONDS = { 2378496.5 => 13.188148343557259, # 1800-01-01T00:00:00+00:00 2378677.5 => 12.977779959648615, 2378861.5 => 12.789307379498496, 2379042.5 => 12.627219619724201, 2379226.5 => 12.484534330869792, 2379407.5 => 12.364396579316235, 2379591.5 => 12.261337343137711, 2379772.5 => 12.1773053980869, 2379956.5 => 12.108106397237862, 2380138.5 => 12.054387758878875, 2380322.5 => 12.013603253144538, 2380503.5 => 11.98543684683682, 2380687.5 => 11.96762962192588, 2380868.5 => 11.959480197547236, 2381052.5 => 11.959422685911704, 2381233.5 => 11.966206580204016, 2381417.5 => 11.978793920316093, 2381599.5 => 11.99566047854023, 2381783.5 => 12.015950798828271, 2381964.5 => 12.037916332170425, 2382148.5 => 12.061120228798245, 2382329.5 => 12.083698914131674, 2382513.5 => 12.10530703765835, 2382694.5 => 12.12421078250918, 2382878.5 => 12.140030777663924, 2383060.5 => 12.151364887780801, 2383244.5 => 12.157556479887717, 2383425.5 => 12.15765329658825, 2383609.5 => 12.150876665651595, 2383790.5 => 12.136746181382478, 2383974.5 => 12.114144526847667, 2384155.5 => 12.083243093009514, 2384339.5 => 12.042512500593148, 2384521.5 => 11.992558943176846, 2384705.5 => 11.931929977163236, 2384886.5 => 11.862085932760237, 2385070.5 => 11.78051543343463, 2385251.5 => 11.689763871143441, 2385435.5 => 11.586784825234645, 2385616.5 => 11.474975813831406, 2385800.5 => 11.350748372411545, 2385982.5 => 11.21758410586699, 2386166.5 => 11.072826269341022, 2386347.5 => 10.920825074952518, 2386531.5 => 10.756952695481232, 2386712.5 => 10.587020134840714, 2386896.5 => 10.405935512304495, 2387077.5 => 10.22019193469896, 2387261.5 => 10.024289426956784, 2387443.5 => 9.824194633200023, 2387627.5 => 9.616270032883222, 2387808.5 => 9.406995099559936, 2387992.5 => 9.190269937098492, 2388173.5 => 8.974012950570796, 2388357.5 => 8.751953043760295, 2388538.5 => 8.532231137086455, 2388722.5 => 8.308500055015429, 2388904.5 => 8.087772834055613, 2389088.5 => 7.866155700010495, 2389269.5 => 7.650592317289465, 2389453.5 => 7.434884049415814, 2389634.5 => 7.226980347727022, 2389818.5 => 7.020908291692649, 2389999.5 => 6.824264827564548, 2390183.5 => 6.631400447266969, 2390365.5 => 6.448439782438527, 2390549.5 => 6.272163832553815, 2390730.5 => 6.1080329005421845, 2390914.5 => 5.951314816355762, 2391095.5 => 5.807762833132756, 2391279.5 => 5.67321983816305, 2391460.5 => 5.552603443019962, 2391644.5 => 5.442394451603377, 2391826.5 => 5.346096742151303, 2392010.5 => 5.261939180030367, 2392191.5 => 5.192368075351851, 2392375.5 => 5.135275347080096, 2392556.5 => 5.092642595328925, 2392740.5 => 5.0631020675593845, 2392921.5 => 5.047585133826715, 2393105.5 => 5.045466038021345, 2393287.5 => 5.056725300162157, 2393471.5 => 5.0813396174220316, 2393652.5 => 5.118191578710935, 2393836.5 => 5.168077283418484, 2394017.5 => 5.228879316252119, 2394201.5 => 5.302037309391551, 2394382.5 => 5.384531632259211, 2394566.5 => 5.478379147577186, 2394748.5 => 5.580335613932505, 2394932.5 => 5.691789788972983, 2395113.5 => 5.80875494138661, 2395297.5 => 5.934144330408458, 2395478.5 => 6.062875593983534, 2395662.5 => 6.198153542957755, 2395843.5 => 6.334486342631209, 2396027.5 => 6.475251951900248, 2396209.5 => 6.615483952215641, 2396393.5 => 6.757060416676296, 2396574.5 => 6.894941705629094, 2396758.5 => 7.032466496923803, 2396939.5 => 7.163937749348335, 2397123.5 => 7.292473172750462, 2397304.5 => 7.412673143453404, 2397488.5 => 7.527299162998588, 2397670.5 => 7.631984548218753, 2397854.5 => 7.727845571025242, 2398035.5 => 7.811233918589153, 2398219.5 => 7.883805096017731, 2398400.5 => 7.942151870516433, 2398584.5 => 7.9871958259539895, 2398765.5 => 8.016533772126351, 2398949.5 => 8.030246708433822, 2399131.5 => 8.02701838727982, 2399315.5 => 8.00602743589197, 2399496.5 => 7.967334857492741, 2399680.5 => 7.909076736075594, 2399861.5 => 7.832672030889775, 2400045.5 => 7.73519070466137, 2400226.5 => 7.619518664506842, 2400410.5 => 7.4816235218118, 2400592.5 => 7.324994613580456, 2400776.5 => 7.146202934871676, 2400957.5 => 6.9503926382285375, 2401141.5 => 6.73130493384776, 2401322.5 => 6.496419397354267, 2401506.5 => 6.238403444540144, 2401687.5 => 5.966222444405794, 2401871.5 => 5.671527091411464, 2402053.5 => 5.362950462274329, 2402237.5 => 5.034600715553276, 2402418.5 => 4.6965018330360175, 2402602.5 => 4.3385322957757895, 2402783.5 => 3.973519127096933, 2402967.5 => 3.5906303869208167, 2403148.5 => 3.2036725995868243, 2403332.5 => 2.8012444581490232, 2403514.5 => 2.3956847018984218, 2403698.5 => 1.9796421127117891, 2403879.5 => 1.5660461742034346, 2404063.5 => 1.1428361434845933, 2404244.5 => 0.7254582284581174, 2404428.5 => 0.30178135991199984, 2404609.5 => -0.11270006148430323, 2404793.5 => -0.5300097435221406, 2404975.5 => -0.9370907950094551, 2405159.5 => -1.3412024731958803, 2405340.5 => -1.7298134540480932, 2405524.5 => -2.1142122995718458, 2405705.5 => -2.480366366734088, 2405889.5 => -2.83895781510422, 2406070.5 => -3.176956105380124, 2406254.5 => -3.504300154151409, 2406436.5 => -3.8108248494746757, 2406620.5 => -4.10223814009868, 2406801.5 => -4.3699035350160695, 2406985.5 => -4.621958792228032, 2407166.5 => -4.849622707292203, 2407350.5 => -5.060038124929611, 2407531.5 => -5.2461236702027385, 2407715.5 => -5.414009715942285, 2407897.5 => -5.559113801802489, 2408081.5 => -5.684979055402733, 2408262.5 => -5.788896181101112, 2408446.5 => -5.875063703703072, 2408627.5 => -5.941604136061755, 2408811.5 => -5.99187142911113, 2408992.5 => -6.025534115559931, 2409176.5 => -6.045223454604344, 2409358.5 => -6.051947540372789, 2409542.5 => -6.047693019280377, 2409723.5 => -6.034585530924514, 2409907.5 => -6.014253694220111, 2410088.5 => -5.989451801657724, 2410272.5 => -5.9615356388374785, 2410453.5 => -5.933547174681333, 2410637.5 => -5.9066933163237305, 2410819.5 => -5.883732076789566, 2411003.5 => -5.866053442239031, 2411184.5 => -5.855727871403548, 2411368.5 => -5.8537912883455165, 2411549.5 => -5.861293927323844, 2411733.5 => -5.879036033749507, 2411914.5 => -5.906436546760297, 2412098.5 => -5.9437407187970415, 2412280.5 => -5.988588134352584, 2412464.5 => -6.039608414140064, 2412645.5 => -6.092048605632098, 2412829.5 => -6.143066911075388, 2413010.5 => -6.18519588086268, 2413194.5 => -6.212372490839427, 2413375.5 => -6.214734852478125, 2413559.5 => -6.1812687926510375, 2413741.5 => -6.0995165979128165, 2413925.5 => -5.95200691711783, 2414106.5 => -5.725411356266838, 2414290.5 => -5.391101186767492, 2414471.5 => -4.936214592188059, 2414655.5 => -4.31790503046886, 2414836.5 => -3.52545025806083, 2415020.5 => -2.4388055967284674, 2415201.5 => -1.9866921101473605, 2415385.5 => -1.4881903065314066, 2415566.5 => -0.9618691218134782, 2415750.5 => -0.39284264593890794, 2415931.5 => 0.19767418413824753, 2416115.5 => 0.8264165244917904, 2416296.5 => 1.4700172355479844, 2416480.5 => 2.1468253465826375, 2416662.5 => 2.835652766092306, 2416846.5 => 3.5486047317343434, 2417027.5 => 4.263231363098808, 2417211.5 => 5.000259983924892, 2417392.5 => 5.732816046006328, 2417576.5 => 6.482353812962369, 2417757.5 => 7.221751119829495, 2417941.5 => 7.972880371561444, 2418123.5 => 8.712831317161704, 2418307.5 => 9.455454046423558, 2418488.5 => 10.178387509185434, 2418672.5 => 10.903463404820002, 2418853.5 => 11.605090872859282, 2419037.5 => 12.304684798828276, 2419218.5 => 12.977775178916021, 2419402.5 => 13.64513190798989, 2419584.5 => 14.287108978143385, 2419768.5 => 14.916572237369076, 2419949.5 => 15.515510607554367, 2420133.5 => 16.10284118737613, 2420314.5 => 16.65863855961404, 2420498.5 => 17.20068006434343, 2420679.5 => 17.710794402822042, 2420863.5 => 18.205520004226692, 2421045.5 => 18.67098146138676, 2421229.5 => 19.11729362430148, 2421410.5 => 19.53253120288024, 2421594.5 => 19.930579247056528, 2421775.5 => 20.29868147462184, 2421959.5 => 20.649370571074524, 2422140.5 => 20.971627610669987, 2422324.5 => 21.276649743274778, 2422506.5 => 21.55655418126106, 2422690.5 => 21.818167846062344, 2422871.5 => 22.055281124221217, 2423055.5 => 22.27655644857247, 2423236.5 => 22.47561690120095, 2423420.5 => 22.65996646290686, 2423601.5 => 22.82452002838678, 2423785.5 => 22.97571425952653, 2423967.5 => 23.110308267157464, 2424151.5 => 23.23229795912879, 2424332.5 => 23.339511501395894, 2424516.5 => 23.436563200676833, 2424697.5 => 23.52133058525957, 2424881.5 => 23.597688707429405, 2425062.5 => 23.664184372246805, 2425246.5 => 23.72407135482779, 2425428.5 => 23.776681991877023, 2425612.5 => 23.82419274912977, 2425793.5 => 23.866331353902197, 2425977.5 => 23.905460169259943, 2426158.5 => 23.941218197004247, 2426342.5 => 23.975692579033176, 2426523.5 => 24.008605928439557, 2426707.5 => 24.04187605377498, 2426889.5 => 24.07537378002682, 2427073.5 => 24.11058140261558, 2427254.5 => 24.14721547072987, 2427438.5 => 24.187142464135416, 2427619.5 => 24.229652439984108, 2427803.5 => 24.276712008407983, 2427984.5 => 24.327284837979363, 2428168.5 => 24.38350825339512, 2428350.5 => 24.44430127350479, 2428534.5 => 24.511366094895674, 2428715.5 => 24.583145405760572, 2428899.5 => 24.662288857343256, 2429080.5 => 24.74643544094861, 2429264.5 => 24.838554819441654, 2429445.5 => 24.935777490385995, 2429629.5 => 25.041422412562163, 2429811.5 => 25.15273021858507, 2429995.5 => 25.27216643328502, 2430176.5 => 25.39641349476654, 2430360.5 => 25.529540768204548, 2430541.5 => 25.667128929194487, 2430725.5 => 25.81363084582551, 2430906.5 => 25.96413859864814, 2431090.5 => 26.123484991687462, 2431272.5 => 26.287217201519887, 2431456.5 => 26.458739053598578, 2431637.5 => 26.63313685630417, 2431821.5 => 26.815971902751684, 2432002.5 => 27.00105856424981, 2432186.5 => 27.19429786593409, 2432367.5 => 27.38915617204269, 2432551.5 => 27.591855093366206, 2432733.5 => 27.796691496947233, 2432917.5 => 28.007936001208634, 2433098.5 => 28.219596370060827, 2433282.5 => 28.4384765624998, 2433463.5 => 28.65724359589477, 2433647.5 => 28.882964215782437, 2433828.5 => 29.108113222396952, 2434012.5 => 29.34000446979161, 2434194.5 => 29.57223350574489, 2434378.5 => 29.809796836408253, 2434559.5 => 30.046134632450332, 2434743.5 => 30.289022739879897, 2434924.5 => 30.53050884062472, 2435108.5 => 30.778591836086775, 2435289.5 => 31.025202633417564, 2435473.5 => 31.27856475284625, 2435655.5 => 31.53189044630176, 2435839.5 => 31.79085168727164, 2436020.5 => 32.04851687044061, 2436204.5 => 32.31358519491181, 2436385.5 => 32.57759273374779, 2436569.5 => 32.84949938063994, 2436750.5 => 33.12066519162579, 2436934.5 => 33.40033242784773, 2437116.5 => 33.68120412544363, 2437300.5 => 33.96974573155137, 2437481.5 => 34.258379750810946, 2437665.5 => 34.5569937600327, 2437846.5 => 34.85617296641749, 2438030.5 => 35.16617185935229, 2438211.5 => 35.47721532145181, 2438395.5 => 35.799955711962184, 2438577.5 => 36.12601075254611, 2438761.5 => 36.46287982255012, 2438942.5 => 36.801664953153704, 2439126.5 => 37.1539031471541, 2439307.5 => 37.50838994184596, 2439491.5 => 37.877141110449884, 2439672.5 => 38.24836458592608, 2439856.5 => 38.634572113308195, 2440038.5 => 39.02550887261282, 2440222.5 => 39.42989718222407, 2440403.5 => 39.83675728105027, 2440587.5 => 40.25961253333708, 2440768.5 => 40.68465798505122, 2440952.5 => 41.12591019247293, 2441133.5 => 41.568849508274525, 2441317.5 => 42.02796103684432, 2441499.5 => 42.49057858125434, 2441683.5 => 42.966532268043466, 2441864.5 => 43.442420967015096, 2442048.5 => 43.93353617862613, 2442229.5 => 44.42331491540972, 2442413.5 => 44.92735455766797, 2442594.5 => 45.428517738630035, 2442778.5 => 45.942622367844706, 2442960.5 => 46.454873246740135, 2443144.5 => 46.97557507852889, 2443325.5 => 47.489552682778594, 2443509.5 => 48.012750281605804, 2443690.5 => 48.52697224120766, 2443874.5 => 49.048043614533526, 2444055.5 => 49.557725033980205, 2444239.5 => 50.0715895041767, 2444421.5 => 50.574294001573435, 2444605.5 => 51.0754922955166, 2444786.5 => 51.56024559759862, 2444970.5 => 52.04321620585506, 2445151.5 => 52.50729086053434, 2445335.5 => 52.966488008352826, 2445516.5 => 53.4045449379355, 2445700.5 => 53.83473382284683, 2445882.5 => 54.24409727758939, 2446066.5 => 54.64058576938987, 2446247.5 => 55.01268563318263, 2446431.5 => 55.37200611165099, 2446612.5 => 55.706320752291504, 2446796.5 => 56.02643064426229, 2446977.5 => 56.321893441388966, 2447161.5 => 56.602817056686035, 2447343.5 => 56.8620766468739, 2447527.5 => 57.106458937032585, 2447708.5 => 57.330978845137, 2447892.5 => 57.54513390577631, 2448073.5 => 57.744507716448425, 2448257.5 => 57.93896314871017, 2448438.5 => 58.126022272994305, 2448622.5 => 58.316598521993, 2448804.5 => 58.51100219137879, 2448988.5 => 58.72000281988949, 2449169.5 => 58.94513761608323, 2449353.5 => 59.20242227252311, 2449534.5 => 59.492985772485554, 2449718.5 => 59.83746411076572, 2449899.5 => 60.236736812592426, 2450083.5 => 60.717905576806515, 2450265.5 => 61.2837935622083, 2450449.5 => 61.96410528309934, 2450630.5 => 62.7581330776884, 2450814.5 => 62.966, 2450995.5 => 63.284, 2451179.5 => 63.467, 2451360.5 => 63.664 # 1999-07-01T00:00:00+00:00 }.freeze RECENT_LEAP_SECONDS = { 2451544.5 => 63.829, # 2000-01-01T00:00:00+00:00 2451726.5 => 63.980, 2451910.5 => 64.091, 2452091.5 => 64.212, 2452275.5 => 64.300, 2452456.5 => 64.413, 2452640.5 => 64.473, 2452821.5 => 64.551, 2453005.5 => 64.574, 2453187.5 => 64.653, 2453371.5 => 64.688, 2453552.5 => 64.799, 2453736.5 => 64.845, 2453917.5 => 64.989, 2454101.5 => 65.146, 2454282.5 => 65.341, 2454466.5 => 65.457, 2454648.5 => 65.629, 2454832.5 => 65.777, 2455013.5 => 65.951, 2455197.5 => 66.070, 2455378.5 => 66.241, 2455562.5 => 66.325, 2455743.5 => 66.475, 2455927.5 => 66.603, 2456109.5 => 66.771, 2456293.5 => 66.907, 2456474.5 => 67.127, 2456658.5 => 67.281, 2456839.5 => 67.486, 2457023.5 => 67.644, 2457204.5 => 67.861, 2457388.5 => 68.102, 2457570.5 => 68.396, 2457754.5 => 68.593, 2457935.5 => 68.824, 2458119.5 => 68.968, 2458300.5 => 69.113, 2458484.5 => 69.220, 2458665.5 => 69.358, 2458849.5 => 69.361, 2459031.5 => 69.424, 2459215.5 => 69.359, 2459396.5 => 69.351, 2459580.5 => 69.294, 2459761.5 => 69.253, 2459945.5 => 69.204, 2460126.5 => 69.220, 2460310.5 => 69.175, 2460492.5 => 69.188, 2460676.5 => 69.138, 2460857.5 => 69.139 # 2025-07-01T00:00:00+00:00 }.freeze OLDEST_JD = 2378496.5 FIRST_RECENT_JD = 2451544.5 MOST_RECENT_JD = 2460857.5 # @param date [Date] # @param decimal [Numeric] Hour of the day, in decimal hours # @return [::Time] Date and time def self.decimal_hour_to_time(date, utc_offset, decimal) absolute_hour = decimal.abs hour = absolute_hour.floor unless hour.between?(0, Constants::HOURS_PER_DAY) raise( IncompatibleArgumentsError, "Hour must be between 0 and #{Constants::HOURS_PER_DAY.to_i}, got #{hour}" ) end decimal_minute = Constants::MINUTES_PER_HOUR * (absolute_hour - hour) absolute_decimal_minute = ( Constants::MINUTES_PER_HOUR * (absolute_hour - hour) ).abs minute = decimal_minute.floor second = Constants::SECONDS_PER_MINUTE * (absolute_decimal_minute - absolute_decimal_minute.floor) date_in_local_time = ::Time .utc(date.year, date.month, date.day, hour, minute, second) .getlocal(utc_offset) .to_date if date_in_local_time < date date = date.next_day elsif date_in_local_time > date date = date.prev_day end ::Time.utc(date.year, date.month, date.day, hour, minute, second).round end # @param instant [Numeric, Time, Date, DateTime] # @return [Integer, Float] Number of leap seconds for the given instant def self.terrestrial_universal_time_delta(instant) # Source: # Title: Astronomical Algorithms # Author: Jean Meeus # Edition: 2nd edition # Chapter: 10 - Dynamical Time and Universal Time jd = case instant when Numeric instant when ::Time, ::Date, ::DateTime JulianDate.from_time(instant) else raise IncompatibleArgumentsError, "Expected a Numeric, Time, Date or DateTime object, got #{instant.class}" end return RECENT_LEAP_SECONDS[MOST_RECENT_JD] if jd >= MOST_RECENT_JD return 0 if jd < OLDEST_JD if jd >= FIRST_RECENT_JD closest_jd = RECENT_LEAP_SECONDS.keys.bsearch { |key| key >= jd } leap_seconds = RECENT_LEAP_SECONDS[closest_jd] else closest_jd = OLD_LEAP_SECONDS.keys.bsearch { |key| key >= jd } leap_seconds = OLD_LEAP_SECONDS[closest_jd] end return leap_seconds if leap_seconds 0.0 end end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/util/trigonometry.rb
lib/astronoby/util/trigonometry.rb
# frozen_string_literal: true module Astronoby module Util module Trigonometry class << self # Source: # Title: Celestial Calculations # Author: J. L. Lawrence # Edition: MIT Press # Chapter: 4 - Orbits and Coordinate Systems def adjustement_for_arctangent(y, x, angle) return angle if y.positive? && x.positive? if y.negative? && x.positive? return Angle.from_degrees( angle.degrees + Constants::DEGREES_PER_CIRCLE ) end Angle.from_degrees(angle.degrees + Constants::DEGREES_PER_CIRCLE / 2) end end end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/util/maths.rb
lib/astronoby/util/maths.rb
# frozen_string_literal: true module Astronoby module Util module Maths module_function def dot_product(a, b) a.zip(b).sum { |x, y| x * y } end # Find maximum altitude using quadratic interpolation # @param t1, t2, t3 [Time] Three consecutive times # @param alt1, alt2, alt3 [Float] Corresponding altitudes # @return [::Time] Time of maximum altitude def quadratic_maximum(t1, t2, t3, alt1, alt2, alt3) # Convert to float seconds for arithmetic x1, x2, x3 = t1.to_f, t2.to_f, t3.to_f y1, y2, y3 = alt1, alt2, alt3 # Quadratic interpolation formula denom = (x1 - x2) * (x1 - x3) * (x2 - x3) a = (x3 * (y2 - y1) + x2 * (y1 - y3) + x1 * (y3 - y2)) / denom b = (x3 * x3 * (y1 - y2) + x2 * x2 * (y3 - y1) + x1 * x1 * (y2 - y3)) / denom # Maximum is at -b/2a max_t = -b / (2 * a) ::Time.at(max_t) end # Linear interpolation between two points # @param x1 [Numeric] First x value # @param x2 [Numeric] Second x value # @param y1 [Numeric] First y value # @param y2 [Numeric] Second y value # @param target_y [Numeric] Target y value (default: 0) # @return [Numeric] Interpolated x value where y=target_y def self.linear_interpolate(x1, x2, y1, y2, target_y = 0) # Handle horizontal line case (avoid division by zero) if (y2 - y1).abs < 1e-10 # If target_y matches the line's y-value (within precision), return # midpoint. Otherwise, return one of the endpoints (no unique solution # exists) return ((target_y - y1).abs < 1e-10) ? (x1 + x2) / 2.0 : x1 end # Handle vertical line case if (x2 - x1).abs < 1e-10 # For a vertical line, there's only one x-value possible return x1 end # Standard linear interpolation formula x1 + (target_y - y1) * (x2 - x1) / (y2 - y1) end # Creates an array of evenly spaced values between start and stop. # @param start [Numeric] The starting value of the sequence # @param stop [Numeric] The end value of the sequence # @param num [Integer] Number of samples to generate. Default is 50 # @param endpoint [Boolean] If true, stop is the last sample. Otherwise, # it is not included. Default is true # @return [Array<Numeric>] Array of evenly spaced values # @raise [ArgumentError] If num is less than 1 def linspace(start, stop, num = 50, endpoint = true) raise ArgumentError, "Number of samples must be at least 1" if num < 1 return [start] if num == 1 step = if endpoint (stop - start) / (num - 1).to_f else (stop - start) / num.to_f end result = Array.new(num) current = start (num - 1).times do |i| result[i] = current current += step end result[num - 1] = endpoint ? stop : current result end end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/corrections/light_time_delay.rb
lib/astronoby/corrections/light_time_delay.rb
# frozen_string_literal: true module Astronoby module Correction class LightTimeDelay LIGHT_SPEED_CORRECTION_MAXIMUM_ITERATIONS = 10 LIGHT_SPEED_CORRECTION_PRECISION = 1e-12 def self.compute(center:, target:, ephem:) new(center: center, target: target, ephem: ephem).compute end def initialize(center:, target:, ephem:) @center = center @target = target @ephem = ephem end def delay @_delay ||= begin compute @delay end end def compute @corrected_position ||= begin corrected_position = Vector[ Distance.zero, Distance.zero, Distance.zero ] corrected_velocity = Vector[ Velocity.zero, Velocity.zero, Velocity.zero ] @delay = initial_delta_in_seconds LIGHT_SPEED_CORRECTION_MAXIMUM_ITERATIONS.times do new_instant = Instant.from_terrestrial_time( instant.tt - @delay / Constants::SECONDS_PER_DAY ) corrected = @target .target_body .geometric(ephem: @ephem, instant: new_instant) corrected_position = corrected.position corrected_velocity = corrected.velocity corrected_distance_in_km = Math.sqrt( (corrected_position.x.km - position.x.km)**2 + (corrected_position.y.km - position.y.km)**2 + (corrected_position.z.km - position.z.km)**2 ) new_delay = corrected_distance_in_km / Velocity.light_speed.kmps break if (new_delay - @delay).abs < LIGHT_SPEED_CORRECTION_PRECISION @delay = new_delay end [corrected_position, corrected_velocity] end end private def position @position ||= @center.position end def instant @center.instant end def initial_delta_in_seconds distance_between_bodies_in_km / Velocity.light_speed.kmps end def distance_between_bodies_in_km Math.sqrt( (@target.position.x.km - position.x.km)**2 + (@target.position.y.km - position.y.km)**2 + (@target.position.z.km - position.z.km)**2 ) end end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/astronomical_models/moon_phases_periodic_terms.rb
lib/astronoby/astronomical_models/moon_phases_periodic_terms.rb
# frozen_string_literal: true module Astronoby class MoonPhasesPeriodicTerms # Lunar Solution ELP 2000-82B (Chapront-Touze+, 1988) # Source: # Title: Astronomical Algorithms # Author: Jean Meeus # Edition: 2nd edition # Chapter: 49 - Phases of the Moon # @param julian_centuries [Float] Julian centuries # @param time [Float] Time # @param eccentricity_correction [Float] Eccentricity correction # @param moon_mean_anomaly [Float] Moon mean anomaly # @param sun_mean_anomaly [Float] Sun mean anomaly # @param moon_argument_of_latitude [Float] Moon argument of latitude # @param longitude_of_the_ascending_node [Float] Longitude of the ascending node def initialize( julian_centuries:, time:, eccentricity_correction:, moon_mean_anomaly:, sun_mean_anomaly:, moon_argument_of_latitude:, longitude_of_the_ascending_node: ) @julian_centuries = julian_centuries @time = time @eccentricity_correction = eccentricity_correction @moon_mean_anomaly = moon_mean_anomaly @sun_mean_anomaly = sun_mean_anomaly @moon_argument_of_latitude = moon_argument_of_latitude @longitude_of_the_ascending_node = longitude_of_the_ascending_node end # @return [Float] New moon correction def new_moon_correction ecc = @eccentricity_correction mma = @moon_mean_anomaly.radians sma = @sun_mean_anomaly.radians maol = @moon_argument_of_latitude.radians lotan = @longitude_of_the_ascending_node.radians [ [-0.40720, mma], [0.17241 * ecc, sma], [0.01608, 2 * mma], [0.01039, 2 * maol], [0.00739 * ecc, mma - sma], [-0.00514 * ecc, mma + sma], [0.00208 * ecc * ecc, 2 * sma], [-0.00111, mma - 2 * maol], [-0.00057, mma + 2 * maol], [0.00056 * ecc, 2 * mma + sma], [-0.00042, 3 * mma], [0.00042 * ecc, sma + 2 * maol], [0.00038 * ecc, sma - 2 * maol], [-0.00024 * ecc, 2 * mma - sma], [-0.00017, lotan], [-0.00007, mma + 2 * sma], [0.00004, 2 * mma - 2 * maol], [0.00004, 3 * sma], [0.00003, mma + sma - 2 * maol], [0.00003, 2 * mma + 2 * maol], [-0.00003, mma + sma + 2 * maol], [0.00003, mma - sma + 2 * maol], [-0.00002, mma - sma - 2 * maol], [-0.00002, 3 * mma + sma], [0.00002, 4 * mma] ].map { _1.first * Math.sin(_1.last) }.sum end # @return [Float] First quarter correction def first_quarter_correction first_and_last_quarter_correction + first_and_last_quarter_final_correction end # @return [Float] Full moon correction def full_moon_correction ecc = @eccentricity_correction mma = @moon_mean_anomaly.radians sma = @sun_mean_anomaly.radians maol = @moon_argument_of_latitude.radians lotan = @longitude_of_the_ascending_node.radians [ [-0.40614, mma], [0.17302 * ecc, sma], [0.01614, 2 * mma], [0.01043, 2 * maol], [0.00734 * ecc, mma - sma], [-0.00515 * ecc, mma + sma], [0.00209 * ecc * ecc, 2 * sma], [-0.00111, mma - 2 * maol], [-0.00057, mma + 2 * maol], [0.00056 * ecc, 2 * mma + sma], [-0.00042, 3 * mma], [0.00042 * ecc, sma + 2 * maol], [0.00038 * ecc, sma - 2 * maol], [-0.00024 * ecc, 2 * mma - sma], [-0.00017, lotan], [-0.00007, mma + 2 * sma], [0.00004, 2 * mma - 2 * maol], [0.00004, 3 * sma], [0.00003, mma + sma - 2 * maol], [0.00003, 2 * mma + 2 * maol], [-0.00003, mma + sma + 2 * maol], [0.00003, mma - sma + 2 * maol], [-0.00002, mma - sma - 2 * maol], [-0.00002, 3 * mma + sma], [0.00002, 4 * mma] ].map { _1.first * Math.sin(_1.last) }.sum end # @return [Float] Last quarter correction def last_quarter_correction first_and_last_quarter_correction - first_and_last_quarter_final_correction end # @return [Float] Additional corrections def additional_corrections [ [0.000325, a1], [0.000165, a2], [0.000164, a3], [0.000126, a4], [0.000110, a5], [0.000062, a6], [0.000060, a7], [0.000056, a8], [0.000047, a9], [0.000042, a10], [0.000040, a11], [0.000037, a12], [0.000035, a13], [0.000023, a14] ].map { _1.first * _1.last.sin }.sum end private def a1 Angle.from_degrees( ( 299.77 + 0.107408 * @time - 0.009173 * @julian_centuries**2 ) % 360 ) end def a2 Angle.from_degrees (251.88 + 0.016321 * @time) % 360 end def a3 Angle.from_degrees (251.83 + 26.651886 * @time) % 360 end def a4 Angle.from_degrees (349.42 + 36.412478 * @time) % 360 end def a5 Angle.from_degrees (84.66 + 18.206239 * @time) % 360 end def a6 Angle.from_degrees (141.74 + 53.303771 * @time) % 360 end def a7 Angle.from_degrees (207.14 + 2.453732 * @time) % 360 end def a8 Angle.from_degrees (154.84 + 7.306860 * @time) % 360 end def a9 Angle.from_degrees (34.52 + 27.261239 * @time) % 360 end def a10 Angle.from_degrees (207.19 + 0.121824 * @time) % 360 end def a11 Angle.from_degrees (291.34 + 1.844379 * @time) % 360 end def a12 Angle.from_degrees (161.72 + 24.198154 * @time) % 360 end def a13 Angle.from_degrees (239.56 + 25.513099 * @time) % 360 end def a14 Angle.from_degrees (331.55 + 3.592518 * @time) % 360 end def first_and_last_quarter_final_correction 0.00306 - 0.00038 * @eccentricity_correction * @sun_mean_anomaly.cos + 0.00026 * @moon_mean_anomaly.cos - 0.00002 * (@moon_mean_anomaly - @sun_mean_anomaly).cos + 0.00002 * (@moon_mean_anomaly + @sun_mean_anomaly).cos + 0.00002 * Math.cos(2 * @moon_argument_of_latitude.radians) end def first_and_last_quarter_correction ecc = @eccentricity_correction mma = @moon_mean_anomaly.radians sma = @sun_mean_anomaly.radians maol = @moon_argument_of_latitude.radians lotan = @longitude_of_the_ascending_node.radians [ [-0.62801, mma], [0.17172 * ecc, sma], [-0.01183, mma + sma], [0.00862, 2 * mma], [0.00804, 2 * maol], [0.00454 * ecc, mma - sma], [0.00204 * ecc**2, 2 * sma], [-0.00180, mma - 2 * maol], [-0.00070, mma + 2 * maol], [-0.00040, 3 * mma], [-0.00034 * ecc, 2 * mma - sma], [0.00032 * ecc, sma + 2 * maol], [0.00032, sma - 2 * maol], [-0.00028 * ecc**2, mma + 2 * sma], [0.00027 * ecc, 2 * mma + sma], [-0.00017, lotan], [-0.00005, mma - sma - 2 * maol], [0.00004, 2 * mma + 2 * maol], [-0.00004, mma + sma + 2 * maol], [0.00004, mma - 2 * sma], [0.00003, mma + sma - 2 * maol], [0.00003, 3 * sma], [0.00002, 2 * mma - 2 * maol], [0.00002, mma - sma + 2 * maol], [-0.00002, 3 * mma + sma] ].map { _1.first * Math.sin(_1.last) }.sum end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/constellations/data.rb
lib/astronoby/constellations/data.rb
# frozen_string_literal: true module Astronoby module Constellations class Data def self.sorted_right_ascensions @sorted_right_ascensions ||= read_file("sorted_right_ascensions.dat").map(&:to_f) end def self.sorted_declinations @sorted_declinations ||= read_file("sorted_declinations.dat").map(&:to_f) end def self.radec_to_index @radec_to_index ||= read_file("radec_to_index.dat").map do |line| line.split.map(&:to_i) end end def self.indexed_abbreviations @indexed_abbreviations ||= read_file("indexed_abbreviations.dat") end def self.constellation_names @constellation_names ||= read_file("constellation_names.dat").map(&:split) end def self.read_file(filename) File.readlines(data_path(filename)).map(&:strip) end def self.data_path(filename) File.join(__dir__, "..", "data", "constellations", filename) end end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/constellations/repository.rb
lib/astronoby/constellations/repository.rb
# frozen_string_literal: true module Astronoby module Constellations class Repository # Returns a constellation object for the given abbreviation. # @param abbreviation [String] The abbreviation of the constellation. # @return [Astronoby::Constellation, nil] The constellation object or nil # if not found. def self.get(abbreviation) @constellations ||= Data.constellation_names.map do |abbr, name| constellation = Constellation.new(name, abbr) [abbr, constellation] end.to_h @constellations[abbreviation] end end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/constellations/finder.rb
lib/astronoby/constellations/finder.rb
# frozen_string_literal: true module Astronoby module Constellations class Finder # Finds the constellation that contains the given B1875 equatorial # coordinates. # @param equatorial_coordinates [Astronoby::Coordinates::Equatorial] The # B1875 coordinates to search for. # @return [Astronoby::Constellation, nil] The constellation that contains # the coordinates, or nil if none is found. def self.find(equatorial_coordinates) ra_hours = equatorial_coordinates.right_ascension.hours dec_degrees = equatorial_coordinates.declination.degrees ra_index = Data .sorted_right_ascensions .bsearch_index { _1 >= ra_hours } dec_index = Data .sorted_declinations .bsearch_index { _1 > dec_degrees } return if ra_index.nil? || dec_index.nil? abbreviation_index = Data.radec_to_index.dig(ra_index, dec_index) return if abbreviation_index.nil? constellation_abbreviation = Data.indexed_abbreviations[abbreviation_index] Repository.get(constellation_abbreviation) end end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/time/local_sidereal_time.rb
lib/astronoby/time/local_sidereal_time.rb
# frozen_string_literal: true module Astronoby class LocalSiderealTime < SiderealTime attr_reader :longitude def self.from_gst(gst:, longitude:) case gst.type when MEAN LocalMeanSiderealTime.from_gst(gst: gst, longitude: longitude) when APPARENT LocalApparentSiderealTime.from_gst(gst: gst, longitude: longitude) end end def self.from_utc(utc, longitude:, type: MEAN) validate_type!(type) case type when MEAN LocalMeanSiderealTime.from_utc(utc, longitude: longitude) when APPARENT LocalApparentSiderealTime.from_utc(utc, longitude: longitude) end end def initialize(date:, time:, longitude:, type: MEAN) super(date: date, time: time, type: type) @longitude = longitude end def to_gst case @type when MEAN lst = LocalMeanSiderealTime.new( date: @date, time: @time, longitude: @longitude ) lst.to_gst when APPARENT last = LocalApparentSiderealTime.new( date: @date, time: @time, longitude: @longitude ) last.to_gst end end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/time/local_mean_sidereal_time.rb
lib/astronoby/time/local_mean_sidereal_time.rb
# frozen_string_literal: true module Astronoby class LocalMeanSiderealTime < LocalSiderealTime # Source: # Title: Practical Astronomy with your Calculator or Spreadsheet # Authors: Peter Duffett-Smith and Jonathan Zwart # Edition: Cambridge University Press # Chapter: 14 - Local sidereal time (LST) def self.from_gst(gst:, longitude:) unless gst.mean? raise ArgumentError, "GST must be mean sidereal time" end date = gst.date time = normalize_time(gst.time + longitude.hours) new(date: date, time: time, longitude: longitude) end def self.from_utc(utc, longitude:) gmst = GreenwichMeanSiderealTime.from_utc(utc) from_gst(gst: gmst, longitude: longitude) end def initialize(date:, time:, longitude:) super(date: date, time: time, longitude: longitude, type: MEAN) end # Source: # Title: Practical Astronomy with your Calculator or Spreadsheet # Authors: Peter Duffett-Smith and Jonathan Zwart # Edition: Cambridge University Press # Chapter: 15 - Converting LST to GST def to_gst date = @date time = normalize_time(@time - @longitude.hours) GreenwichMeanSiderealTime.new(date: date, time: time) end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/time/local_apparent_sidereal_time.rb
lib/astronoby/time/local_apparent_sidereal_time.rb
# frozen_string_literal: true module Astronoby class LocalApparentSiderealTime < LocalSiderealTime # Source: # Title: Practical Astronomy with your Calculator or Spreadsheet # Authors: Peter Duffett-Smith and Jonathan Zwart # Edition: Cambridge University Press # Chapter: 14 - Local sidereal time (LST) def self.from_gst(gst:, longitude:) unless gst.apparent? raise ArgumentError, "GST must be apparent sidereal time" end date = gst.date time = normalize_time(gst.time + longitude.hours) new(date: date, time: time, longitude: longitude) end def self.from_utc(utc, longitude:) gast = GreenwichApparentSiderealTime.from_utc(utc) from_gst(gst: gast, longitude: longitude) end def initialize(date:, time:, longitude:) super(date: date, time: time, longitude: longitude, type: APPARENT) end # Source: # Title: Practical Astronomy with your Calculator or Spreadsheet # Authors: Peter Duffett-Smith and Jonathan Zwart # Edition: Cambridge University Press # Chapter: 15 - Converting LST to GST def to_gst date = @date time = normalize_time(@time - @longitude.hours) GreenwichApparentSiderealTime.new(date: date, time: time) end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/time/greenwich_apparent_sidereal_time.rb
lib/astronoby/time/greenwich_apparent_sidereal_time.rb
# frozen_string_literal: true module Astronoby class GreenwichApparentSiderealTime < GreenwichSiderealTime def self.from_utc(utc) gmst = GreenwichMeanSiderealTime.from_utc(utc) instant = Instant.from_time(utc) nutation = Nutation.new(instant: instant) mean_obliquity = MeanObliquity.at(instant) equation_of_equinoxes = nutation.nutation_in_longitude.hours * mean_obliquity.cos gast_time = normalize_time(gmst.time + equation_of_equinoxes) new(date: gmst.date, time: gast_time) end def initialize(date:, time:) super(date: date, time: time, type: APPARENT) end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/time/greenwich_sidereal_time.rb
lib/astronoby/time/greenwich_sidereal_time.rb
# frozen_string_literal: true module Astronoby class GreenwichSiderealTime < SiderealTime def self.from_utc(utc, type: MEAN) validate_type!(type) case type when MEAN GreenwichMeanSiderealTime.from_utc(utc) when APPARENT GreenwichApparentSiderealTime.from_utc(utc) end end def self.mean_from_utc(utc) GreenwichMeanSiderealTime.from_utc(utc) end def self.apparent_from_utc(utc) GreenwichApparentSiderealTime.from_utc(utc) end def to_utc unless mean? raise NotImplementedError, "UTC conversion only supported for mean sidereal time" end gmst = GreenwichMeanSiderealTime.new(date: @date, time: @time) gmst.to_utc end def to_lst(longitude:) LocalSiderealTime.from_gst(gst: self, longitude: longitude) end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/time/greenwich_mean_sidereal_time.rb
lib/astronoby/time/greenwich_mean_sidereal_time.rb
# frozen_string_literal: true module Astronoby class GreenwichMeanSiderealTime < GreenwichSiderealTime JULIAN_CENTURIES_EXPONENTS = [ 6.697374558, 2400.051336, 0.000025862 ].freeze SIDEREAL_MINUTE_IN_UT_MINUTE = 0.9972695663 # Source: # Title: Practical Astronomy with your Calculator or Spreadsheet # Authors: Peter Duffett-Smith and Jonathan Zwart # Edition: Cambridge University Press # Chapter: 12 - Conversion of UT to Greenwich sidereal time (GST) def self.from_utc(utc) date = utc.to_date julian_day = utc.to_date.ajd t = (julian_day - JulianDate::J2000) / Constants::DAYS_PER_JULIAN_CENTURY t0 = ( (JULIAN_CENTURIES_EXPONENTS[0] + (JULIAN_CENTURIES_EXPONENTS[1] * t) + (JULIAN_CENTURIES_EXPONENTS[2] * t * t)) % Constants::HOURS_PER_DAY ).abs ut_in_hours = utc.hour + utc.min / Constants::MINUTES_PER_HOUR + (utc.sec + utc.subsec) / Constants::SECONDS_PER_HOUR gmst = normalize_time(1.002737909 * ut_in_hours + t0) new(date: date, time: gmst) end def initialize(date:, time:) super(date: date, time: time, type: MEAN) end # Source: # Title: Practical Astronomy with your Calculator or Spreadsheet # Authors: Peter Duffett-Smith and Jonathan Zwart # Edition: Cambridge University Press # Chapter: 13 - Conversion of GST to UT def to_utc date = @date julian_day = @date.ajd t = (julian_day - JulianDate::J2000) / Constants::DAYS_PER_JULIAN_CENTURY t0 = ( (JULIAN_CENTURIES_EXPONENTS[0] + (JULIAN_CENTURIES_EXPONENTS[1] * t) + (JULIAN_CENTURIES_EXPONENTS[2] * t * t)) % Constants::HOURS_PER_DAY ).abs a = normalize_time(@time - t0) utc = SIDEREAL_MINUTE_IN_UT_MINUTE * a Util::Time.decimal_hour_to_time(date, 0, utc) end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/time/sidereal_time.rb
lib/astronoby/time/sidereal_time.rb
# frozen_string_literal: true module Astronoby class SiderealTime TYPES = [ MEAN = :mean, APPARENT = :apparent ].freeze attr_reader :date, :time, :type def self.normalize_time(time) time += Constants::HOURS_PER_DAY if time.negative? time -= Constants::HOURS_PER_DAY if time > Constants::HOURS_PER_DAY time end def self.validate_type!(type) unless TYPES.include?(type) raise ArgumentError, "Invalid type: #{type}. Must be one of #{TYPES}" end end def initialize(date:, time:, type: MEAN) @date = date @time = time @type = type end def mean? @type == MEAN end def apparent? @type == APPARENT end def normalize_time(time) self.class.normalize_time(time) end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/reference_frames/topocentric.rb
lib/astronoby/reference_frames/topocentric.rb
# frozen_string_literal: true module Astronoby class Topocentric < ReferenceFrame def self.build_from_apparent( apparent:, observer:, instant:, target_body: ) matrix = observer.earth_fixed_rotation_matrix_for(instant) observer_position = Distance.vector_from_meters( matrix * observer.geocentric_position.map(&:m) ) observer_velocity = Velocity.vector_from_mps( matrix * observer.geocentric_velocity.map(&:mps) ) position = apparent.position - observer_position velocity = apparent.velocity - observer_velocity new( position: position, velocity: velocity, instant: instant, center_identifier: [observer.longitude, observer.latitude], target_body: target_body, observer: observer ) end def initialize( position:, velocity:, instant:, center_identifier:, target_body:, observer: ) super( position: position, velocity: velocity, instant: instant, center_identifier: center_identifier, target_body: target_body ) @observer = observer end def ecliptic @ecliptic ||= begin return Coordinates::Ecliptic.zero if distance.zero? equatorial.to_ecliptic(instant: @instant) end end def horizontal(refraction: false) horizontal = equatorial.to_horizontal( time: @instant.to_time, observer: @observer ) if refraction Refraction.correct_horizontal_coordinates(coordinates: horizontal) else horizontal end end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/reference_frames/mean_of_date.rb
lib/astronoby/reference_frames/mean_of_date.rb
# frozen_string_literal: true module Astronoby class MeanOfDate < ReferenceFrame def self.build_from_geometric( instant:, target_geometric:, earth_geometric:, target_body: ) position = target_geometric.position - earth_geometric.position velocity = target_geometric.velocity - earth_geometric.velocity precession_matrix = Precession.matrix_for(instant) corrected_position = Distance.vector_from_m( precession_matrix * position.map(&:m) ) corrected_velocity = Velocity.vector_from_mps( precession_matrix * velocity.map(&:mps) ) new( position: corrected_position, velocity: corrected_velocity, instant: instant, center_identifier: SolarSystemBody::EARTH, target_body: target_body ) end def ecliptic @ecliptic ||= begin return Coordinates::Ecliptic.zero if distance.zero? equatorial.to_ecliptic(instant: @instant) end end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/reference_frames/geometric.rb
lib/astronoby/reference_frames/geometric.rb
# frozen_string_literal: true module Astronoby class Geometric < ReferenceFrame def initialize( position:, velocity:, instant:, target_body: ) super( position: position, velocity: velocity, instant: instant, center_identifier: SolarSystemBody::SOLAR_SYSTEM_BARYCENTER, target_body: target_body ) end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/reference_frames/apparent.rb
lib/astronoby/reference_frames/apparent.rb
# frozen_string_literal: true module Astronoby class Apparent < ReferenceFrame def self.build_from_astrometric( instant:, target_astrometric:, earth_geometric:, target_body: ) position = target_astrometric.position velocity = target_astrometric.velocity precession_matrix = Precession.matrix_for(instant) nutation_matrix = Nutation.matrix_for(instant) corrected_position = Distance.vector_from_meters( precession_matrix * nutation_matrix * position.map(&:m) ) corrected_position = Aberration.new( astrometric_position: corrected_position, observer_velocity: earth_geometric.velocity ).corrected_position # In theory, here we should also apply light deflection. However, so far # the deflection algorithm hasn't shown any significant changes to the # apparent position. Therefore, for now, we are saving some computation # time by not applying it, and we will investigate if the algorithm is # correct or if the deflection is indeed negligible. corrected_velocity = Velocity.vector_from_mps( precession_matrix * nutation_matrix * velocity.map(&:mps) ) new( position: corrected_position, velocity: corrected_velocity, instant: instant, center_identifier: SolarSystemBody::EARTH, target_body: target_body ) end def ecliptic @ecliptic ||= begin return Coordinates::Ecliptic.zero if distance.zero? equatorial.to_ecliptic(instant: @instant) end end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/reference_frames/astrometric.rb
lib/astronoby/reference_frames/astrometric.rb
# frozen_string_literal: true module Astronoby class Astrometric < ReferenceFrame def self.build_from_geometric( instant:, earth_geometric:, light_time_corrected_position:, light_time_corrected_velocity:, target_body: ) new( position: light_time_corrected_position - earth_geometric.position, velocity: light_time_corrected_velocity - earth_geometric.velocity, instant: instant, center_identifier: SolarSystemBody::EARTH, target_body: target_body ) end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/events/twilight_event.rb
lib/astronoby/events/twilight_event.rb
# frozen_string_literal: true module Astronoby class TwilightEvent attr_reader :morning_civil_twilight_time, :evening_civil_twilight_time, :morning_nautical_twilight_time, :evening_nautical_twilight_time, :morning_astronomical_twilight_time, :evening_astronomical_twilight_time def initialize( morning_civil_twilight_time: nil, evening_civil_twilight_time: nil, morning_nautical_twilight_time: nil, evening_nautical_twilight_time: nil, morning_astronomical_twilight_time: nil, evening_astronomical_twilight_time: nil ) @morning_civil_twilight_time = morning_civil_twilight_time @evening_civil_twilight_time = evening_civil_twilight_time @morning_nautical_twilight_time = morning_nautical_twilight_time @evening_nautical_twilight_time = evening_nautical_twilight_time @morning_astronomical_twilight_time = morning_astronomical_twilight_time @evening_astronomical_twilight_time = evening_astronomical_twilight_time end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/events/extremum_calculator.rb
lib/astronoby/events/extremum_calculator.rb
# frozen_string_literal: true module Astronoby # Calculates extrema (minima and maxima) in the distance between two # celestial bodies over a given time range using adaptive sampling and golden # section search refinement. class ExtremumCalculator # Mathematical constants PHI = (1 + Math.sqrt(5)) / 2 INVPHI = 1 / PHI GOLDEN_SECTION_TOLERANCE = 1e-5 # Algorithm parameters MIN_SAMPLES_PER_PERIOD = 20 DUPLICATE_THRESHOLD_DAYS = 0.5 BOUNDARY_BUFFER_DAYS = 0.01 # Orbital periods ORBITAL_PERIODS = { "Astronoby::Moon" => 27.504339, "Astronoby::Mercury" => 87.969, "Astronoby::Venus" => 224.701, "Astronoby::Earth" => 365.256, "Astronoby::Mars" => 686.98, "Astronoby::Jupiter" => 4332.59, "Astronoby::Saturn" => 10759.22, "Astronoby::Uranus" => 30688.5, "Astronoby::Neptune" => 60182.0 }.freeze # @param ephem [::Ephem::SPK] Ephemeris data source # @param body [Astronoby::SolarSystemBody] The celestial body to track # @param primary_body [Astronoby::SolarSystemBody] The reference body # (e.g., Sun for planetary orbits) # @param samples_per_period [Integer] Number of samples to take per orbital # period def initialize( body:, primary_body:, ephem:, samples_per_period: 60 ) @ephem = ephem @body = body @primary_body = primary_body @orbital_period = ORBITAL_PERIODS.fetch(body.name) @samples_per_period = samples_per_period end # Finds all apoapsis events between two times # @param start_time [Time] Start time # @param end_time [Time] End time # @return [Array<Astronoby::ExtremumEvent>] Array of apoapsis events def apoapsis_events_between(start_time, end_time) find_extrema( Astronoby::Instant.from_time(start_time).tt, Astronoby::Instant.from_time(end_time).tt, type: :maximum ) end # Finds all periapsis events between two times # @param start_time [Time] Start time # @param end_time [Time] End time # @return [Array<Astronoby::ExtremumEvent>] Array of periapsis events def periapsis_events_between(start_time, end_time) find_extrema( Astronoby::Instant.from_time(start_time).tt, Astronoby::Instant.from_time(end_time).tt, type: :minimum ) end # Finds extrema (minima or maxima) in the distance between bodies within # a time range # @param start_jd [Float] Start time in Julian Date (Terrestrial Time) # @param end_jd [Float] End time in Julian Date (Terrestrial Time) # @param type [Symbol] :maximum or :minimum # @return [Array<Astronoby::ExtremumEvent>] Array of extrema events def find_extrema(start_jd, end_jd, type: :maximum) # 1: Find extrema candidates through adaptive sampling candidates = find_extrema_candidates(start_jd, end_jd, type) # 2: Refine each candidate using golden section search refined_extrema = candidates .map { |candidate| refine_extremum(candidate, type) } .compact # 3: Remove duplicates and boundary artifacts refined_extrema = remove_duplicates(refined_extrema) filter_boundary_artifacts(refined_extrema, start_jd, end_jd) end private def distance_at(jd) instant = Instant.from_terrestrial_time(jd) body_geometric = @body.geometric(ephem: @ephem, instant: instant) primary_geometric = @primary_body .geometric(ephem: @ephem, instant: instant) distance_vector = body_geometric.position - primary_geometric.position distance_vector.magnitude end def find_extrema_candidates(start_jd, end_jd, type) samples = collect_samples(start_jd, end_jd) find_local_extrema_in_samples(samples, type) end def collect_samples(start_jd, end_jd) duration = end_jd - start_jd sample_count = calculate_sample_count(duration) step = duration / sample_count (0..sample_count).map do |i| jd = start_jd + (i * step) {jd: jd, value: distance_at(jd)} end end def calculate_sample_count(duration) # Adaptive sampling: scale with duration and orbital period periods_in_range = duration / @orbital_period base_samples = (periods_in_range * @samples_per_period).to_i # Ensure minimum sample density for short ranges [base_samples, MIN_SAMPLES_PER_PERIOD].max end def find_local_extrema_in_samples(samples, type) candidates = [] # Check each interior point for local extrema (1...samples.length - 1).each do |i| if local_extremum?(samples, i, type) candidates << { start_jd: samples[i - 1][:jd], end_jd: samples[i + 1][:jd], center_jd: samples[i][:jd] } end end candidates end def local_extremum?(samples, index, type) current_val = samples[index][:value].m prev_val = samples[index - 1][:value].m next_val = samples[index + 1][:value].m if type == :maximum current_val > prev_val && current_val > next_val else current_val < prev_val && current_val < next_val end end def refine_extremum(candidate, type) golden_section_search(candidate[:start_jd], candidate[:end_jd], type) end def golden_section_search(a, b, type) return nil if b <= a tol = GOLDEN_SECTION_TOLERANCE * (b - a).abs # Initial points using golden ratio x1 = a + (1 - INVPHI) * (b - a) x2 = a + INVPHI * (b - a) f1 = distance_at(x1).m f2 = distance_at(x2).m while (b - a).abs > tol should_keep_left = (type == :maximum) ? (f1 > f2) : (f1 < f2) if should_keep_left b = x2 x2 = x1 f2 = f1 x1 = a + (1 - INVPHI) * (b - a) f1 = distance_at(x1).m else a = x1 x1 = x2 f1 = f2 x2 = a + INVPHI * (b - a) f2 = distance_at(x2).m end end mid = (a + b) / 2 ExtremumEvent.new( Instant.from_terrestrial_time(mid), distance_at(mid) ) end def remove_duplicates(extrema) return extrema if extrema.length <= 1 cleaned = [extrema.first] extrema.each_with_index do |current, i| next if i == 0 is_duplicate = cleaned.any? do |existing| time_diff = ( current.instant.tt - existing.instant.tt ).abs time_diff < DUPLICATE_THRESHOLD_DAYS end cleaned << current unless is_duplicate end cleaned end def filter_boundary_artifacts(extrema, start_jd, end_jd) extrema.reject do |extreme| start_diff = (extreme.instant.tt - start_jd).abs end_diff = (extreme.instant.tt - end_jd).abs too_close_to_start = start_diff < BOUNDARY_BUFFER_DAYS too_close_to_end = end_diff < BOUNDARY_BUFFER_DAYS too_close_to_start || too_close_to_end end end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/events/extremum_event.rb
lib/astronoby/events/extremum_event.rb
# frozen_string_literal: true module Astronoby # Represents an extremum event with its timing and value class ExtremumEvent attr_reader :instant, :value # @param instant [Astronoby::Instant] When the event occurs # @param value [Object] The extreme value def initialize(instant, value) @instant = instant @value = value end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/events/rise_transit_set_calculator.rb
lib/astronoby/events/rise_transit_set_calculator.rb
# frozen_string_literal: true module Astronoby class RiseTransitSetCalculator class PotentialEvent attr_reader :hour_angle, :can_occur def initialize(hour_angle, can_occur) @hour_angle = hour_angle @can_occur = can_occur end def negated self.class.new(-@hour_angle, @can_occur) end end TAU = Math::PI * 2 SAMPLE_THRESHOLD = 0.8 REFINEMENT_ITERATIONS = 3 MIN_TIME_ADJUSTMENT = Constants::MICROSECOND_IN_DAYS STANDARD_REFRACTION_ANGLE = -Angle.from_dms(0, 34, 0) SUN_REFRACTION_ANGLE = -Angle.from_dms(0, 50, 0) EVENT_TYPES = [:rising, :transit, :setting].freeze # @param body [Astronoby::SolarSystemBody, Astronoby::DeepSkyObject] # Celestial body for which to calculate events # @param observer [Astronoby::Observer] Observer location # @param ephem [::Ephem::SPK, nil] Ephemeris data source def initialize(body:, observer:, ephem: nil) @body = body @observer = observer @ephem = ephem end def event_on(date, utc_offset: 0) events = events_on(date, utc_offset: utc_offset) RiseTransitSetEvent.new( events.rising_times.first, events.transit_times.first, events.setting_times.first ) end def events_on(date, utc_offset: 0) start_time = Time.new( date.year, date.month, date.day, 0, 0, 0, utc_offset ) end_time = Time.new( date.year, date.month, date.day, 23, 59, 59, utc_offset ) events_between(start_time, end_time) end def events_between(start_time, end_time) reset_state @start_instant = Instant.from_time(start_time) @end_instant = Instant.from_time(end_time) events end private def events rising_events = calculate_initial_positions.map do |position| calculate_rising_event(position) end setting_events = rising_events.map(&:negated) transit_event = PotentialEvent.new(Angle.zero, true) event_data = { rising: rising_events, transit: [transit_event], setting: setting_events } results = EVENT_TYPES.each_with_object({}) do |event_type, results| results[event_type] = calculate_event_times( event_type, event_data[event_type] ) end RiseTransitSetEvents.new( results[:rising], results[:transit], results[:setting] ) end def calculate_rising_event(position) declination = position.equatorial.declination latitude = @observer.latitude altitude = horizon_angle(position.distance) # Calculate the unmodified ratio to check if the body rises/sets numerator = altitude.sin - latitude.sin * declination.sin denominator = latitude.cos * declination.cos ratio = numerator / denominator # Determine if the body can rise/set and calculate the hour angle can_rise_set = ratio.abs <= 1.0 angle = can_rise_set ? -Angle.acos(ratio.clamp(-1.0, 1.0)) : Angle.zero PotentialEvent.new(angle, can_rise_set) end def calculate_event_times(event_type, events) desired_hour_angles = events.map(&:hour_angle) # Calculate differences between current and desired hour angles angle_differences = calculate_angle_differences( calculate_initial_hour_angles, desired_hour_angles ) # Find intervals where the body crosses the desired hour angle crossing_indexes = find_crossing_intervals(angle_differences) # Skip if no relevant crossing points found return [] if crossing_indexes.empty? valid_crossings = if events.size == 1 # For transit (single event), all crossings are valid crossing_indexes.map { true } else # For rise/set, check if each crossing corresponds to a valid event crossing_indexes.map { |i| events[i].can_occur } end old_hour_angles = calculate_initial_hour_angles .values_at(*crossing_indexes) old_instants = sample_instants.values_at(*crossing_indexes) # Initial estimate of event times using linear interpolation new_instants = interpolate_initial_times( crossing_indexes, angle_differences ) # Refine the estimates through iteration refined_times = refine_time_estimates( event_type, new_instants, old_hour_angles, old_instants ) # Filter out times for bodies that never rise/set refined_times .zip(valid_crossings) .filter_map { |time, valid| time if valid } end def sample_count @sample_count ||= ((@end_instant.tt - @start_instant.tt) / SAMPLE_THRESHOLD).ceil + 1 end def sample_instants @sample_instants ||= Util::Maths.linspace( @start_instant.tt, @end_instant.tt, sample_count ).map { |tt| Instant.from_terrestrial_time(tt) } end def calculate_initial_positions @initial_positions ||= calculate_positions_at_instants(sample_instants) end def calculate_initial_hour_angles @initial_hour_angles ||= calculate_hour_angles(calculate_initial_positions) end def calculate_angle_differences(hour_angles, angles) hour_angles.each_with_index.map do |hour_angle, i| angle = (angles.size == 1) ? angles[0] : angles[i] Angle.from_radians((angle - hour_angle).radians % TAU) end end def find_crossing_intervals(differences) differences .each_cons(2) .map { |a, b| b - a } .each_with_index .filter_map { |diff, i| i if diff.radians > 0.0 } end def interpolate_initial_times(crossing_indexes, angle_differences) crossing_indexes.map do |index| a = angle_differences[index].radians b = TAU - angle_differences[index + 1].radians c = sample_instants[index].tt d = sample_instants[index + 1].tt # Linear interpolation formula tt = (b * c + a * d) / (a + b) Instant.from_terrestrial_time(tt) end end def refine_time_estimates( event_type, new_instants, old_hour_angles, old_instants ) REFINEMENT_ITERATIONS.times do |iteration| # Calculate positions at current estimates apparent_positions = calculate_positions_at_instants(new_instants) # Calculate current hour angles current_hour_angles = calculate_hour_angles(apparent_positions) # Calculate desired hour angles based on current positions desired_hour_angles = calculate_desired_hour_angles( event_type, apparent_positions ) # Calculate hour angle adjustments hour_angle_adjustments = calculate_hour_angle_adjustments( current_hour_angles, desired_hour_angles ) # Calculate hour angle changes for rate determination hour_angle_changes = calculate_hour_angle_changes( current_hour_angles, old_hour_angles, iteration ) # Calculate time differences time_differences_in_days = new_instants.each_with_index.map do |instant, i| instant.tt - old_instants[i].tt end # Calculate hour angle rate (radians per day) hour_angle_rates = hour_angle_changes.each_with_index.map do |angle, i| denominator = time_differences_in_days[i] angle.radians / denominator end # Store current values for next iteration old_hour_angles = current_hour_angles old_instants = new_instants # Calculate time adjustments time_adjustments = hour_angle_adjustments .each_with_index .map do |angle, i| ratio = angle.radians / hour_angle_rates[i] time_adjustment = (ratio.nan? || ratio.infinite?) ? 0 : ratio [time_adjustment, MIN_TIME_ADJUSTMENT].max end # Apply time adjustments new_instants = new_instants.each_with_index.map do |instant, i| Instant.from_terrestrial_time(instant.tt + time_adjustments[i]) end end new_instants.map { _1.to_time.round } end def calculate_positions_at_instants(instants) if Astronoby.configuration.cache_enabled? instants.map do |instant| cache_key = CacheKey.generate( :observed_by, instant, @body.to_s, @observer.hash ) Astronoby.cache.fetch(cache_key) do @body .at(instant, ephem: @ephem) .observed_by(@observer) end end else @positions_cache ||= {} precision = Astronoby.configuration.cache_precision(:observed_by) instants.map do |instant| rounded_instant = Instant.from_terrestrial_time( instant.tt.round(precision) ) @positions_cache[rounded_instant] ||= @body .at(rounded_instant, ephem: @ephem) .observed_by(@observer) end end end def calculate_hour_angles(positions) positions.map do |position| position.equatorial.compute_hour_angle( time: position.instant.to_time, longitude: @observer.longitude ) end end def calculate_desired_hour_angles(event_type, positions) positions.map do |position| if event_type == :transit Angle.zero else declination = position.equatorial.declination ha = rising_hour_angle( @observer.latitude, declination, horizon_angle(position.distance) ) (event_type == :rising) ? ha : -ha end end end def calculate_hour_angle_adjustments(current_angles, angles) current_angles.each_with_index.map do |angle, i| radians = ((angles[i] - angle).radians + Math::PI) % TAU - Math::PI Angle.from_radians(radians) end end def calculate_hour_angle_changes(current_angles, old_angles, iteration) current_angles.each_with_index.map do |angle, i| radians = angle.radians - old_angles[i].radians if iteration == 0 radians %= TAU else radians = (radians + Math::PI) % TAU - Math::PI end Angle.from_radians(radians) end end def rising_hour_angle(latitude, declination, altitude) numerator = altitude.sin - latitude.sin * declination.sin denominator = latitude.cos * declination.cos ratio = (numerator / denominator).clamp(-1.0, 1.0) -Angle.acos(ratio) end def horizon_angle(distance) if @body == Astronoby::Sun SUN_REFRACTION_ANGLE elsif @body == Astronoby::Moon STANDARD_REFRACTION_ANGLE - Angle.from_radians(Moon::EQUATORIAL_RADIUS.m / distance.m) else STANDARD_REFRACTION_ANGLE end end def reset_state @initial_hour_angles = nil @initial_positions = nil @sample_count = nil @sample_instants = nil @start_instant = nil @end_instant = nil @positions_cache = nil end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/events/rise_transit_set_events.rb
lib/astronoby/events/rise_transit_set_events.rb
# frozen_string_literal: true module Astronoby class RiseTransitSetEvents attr_reader :rising_times, :transit_times, :setting_times def initialize(risings, transits, settings) @rising_times = risings @transit_times = transits @setting_times = settings end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/events/twilight_calculator.rb
lib/astronoby/events/twilight_calculator.rb
# frozen_string_literal: true module Astronoby class TwilightCalculator TWILIGHTS = [ CIVIL = :civil, NAUTICAL = :nautical, ASTRONOMICAL = :astronomical ].freeze TWILIGHT_ANGLES = { CIVIL => Angle.from_degrees(96), NAUTICAL => Angle.from_degrees(102), ASTRONOMICAL => Angle.from_degrees(108) }.freeze PERIODS_OF_THE_DAY = [ MORNING = :morning, EVENING = :evening ].freeze def initialize(observer:, ephem:) @observer = observer @ephem = ephem end def event_on(date, utc_offset: 0) start_time = Time .new(date.year, date.month, date.day, 0, 0, 0, utc_offset) end_time = Time .new(date.year, date.month, date.day, 23, 59, 59, utc_offset) events = events_between(start_time, end_time) TwilightEvent.new( morning_civil_twilight_time: events.morning_civil_twilight_times.first, evening_civil_twilight_time: events.evening_civil_twilight_times.first, morning_nautical_twilight_time: events.morning_nautical_twilight_times.first, evening_nautical_twilight_time: events.evening_nautical_twilight_times.first, morning_astronomical_twilight_time: events.morning_astronomical_twilight_times.first, evening_astronomical_twilight_time: events.evening_astronomical_twilight_times.first ) end def events_between(start_time, end_time) rts_events = Astronoby::RiseTransitSetCalculator.new( body: Sun, observer: @observer, ephem: @ephem ).events_between(start_time, end_time) equatorial_by_time = {} (rts_events.rising_times + rts_events.setting_times) .compact .each do |event_time| rounded_time = event_time.round next if equatorial_by_time.key?(rounded_time) instant = Instant.from_time(rounded_time) sun_at_time = Sun.new(instant: instant, ephem: @ephem) equatorial_by_time[rounded_time] = sun_at_time.apparent.equatorial end morning_civil = [] evening_civil = [] morning_nautical = [] evening_nautical = [] morning_astronomical = [] evening_astronomical = [] arrays_by_period = { MORNING => { CIVIL => morning_civil, NAUTICAL => morning_nautical, ASTRONOMICAL => morning_astronomical }, EVENING => { CIVIL => evening_civil, NAUTICAL => evening_nautical, ASTRONOMICAL => evening_astronomical } } [ [rts_events.rising_times, MORNING], [rts_events.setting_times, EVENING] ].each do |times, period| times.each do |event_time| next unless event_time equatorial_coordinates = equatorial_by_time[event_time.round] TWILIGHT_ANGLES.each do |twilight, angle| arrays_by_period[period][twilight] << compute_twilight_time_from( period, angle, event_time, equatorial_coordinates ) end end end within_range = ->(time) { time && time >= start_time && time <= end_time } TwilightEvents.new( morning_civil.select(&within_range), evening_civil.select(&within_range), morning_nautical.select(&within_range), evening_nautical.select(&within_range), morning_astronomical.select(&within_range), evening_astronomical.select(&within_range) ) end def time_for_zenith_angle( date:, period_of_the_day:, zenith_angle:, utc_offset: 0 ) unless PERIODS_OF_THE_DAY.include?(period_of_the_day) raise IncompatibleArgumentsError, "Only #{PERIODS_OF_THE_DAY.join(" or ")} are allowed as " \ "period_of_the_day, got #{period_of_the_day}" end observation_events = get_observation_events(date, utc_offset: utc_offset) midday_instant = create_midday_instant(date, utc_offset: utc_offset) sun_at_midday = Sun.new(instant: midday_instant, ephem: @ephem) equatorial_coordinates = sun_at_midday.apparent.equatorial compute_twilight_time( period_of_the_day, zenith_angle, observation_events, equatorial_coordinates ) end private def create_midday_instant(date, utc_offset: 0) time = Time.new(date.year, date.month, date.day, 12, 0, 0, utc_offset) Instant.from_time(time) end def get_observation_events(date, utc_offset: 0) Astronoby::RiseTransitSetCalculator.new( body: Sun, observer: @observer, ephem: @ephem ).event_on(date, utc_offset: utc_offset) end def compute_twilight_time( period_of_the_day, zenith_angle, observation_events, equatorial_coordinates ) period_time = if period_of_the_day == MORNING observation_events.rising_time else observation_events.setting_time end compute_twilight_time_from( period_of_the_day, zenith_angle, period_time, equatorial_coordinates ) end def compute_twilight_time_from( period_of_the_day, zenith_angle, period_time, equatorial_coordinates ) # If the sun doesn't rise or set on this day, we can't calculate twilight return nil unless period_time hour_angle_at_period = equatorial_coordinates .compute_hour_angle(time: period_time, longitude: @observer.longitude) term1 = zenith_angle.cos - @observer.latitude.sin * equatorial_coordinates.declination.sin term2 = @observer.latitude.cos * equatorial_coordinates.declination.cos hour_angle_ratio_at_twilight = term1 / term2 # Check if twilight occurs at this location and date return nil unless hour_angle_ratio_at_twilight.between?(-1, 1) hour_angle_at_twilight = Angle.acos(hour_angle_ratio_at_twilight) time_sign = -1 if period_of_the_day == MORNING hour_angle_at_twilight = Angle.from_degrees( Constants::DEGREES_PER_CIRCLE - hour_angle_at_twilight.degrees ) time_sign = 1 end twilight_in_hours = time_sign * (hour_angle_at_twilight - hour_angle_at_period).hours * GreenwichMeanSiderealTime::SIDEREAL_MINUTE_IN_UT_MINUTE twilight_in_seconds = time_sign * twilight_in_hours * Constants::SECONDS_PER_HOUR (period_time + twilight_in_seconds).round end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/events/moon_phases.rb
lib/astronoby/events/moon_phases.rb
# frozen_string_literal: true module Astronoby module Events class MoonPhases BASE_YEAR = 2000 # Source: # Title: Astronomical Algorithms # Author: Jean Meeus # Edition: 2nd edition # Chapter: 49 - Phases of the Moon # @param year [Integer] Requested year # @param month [Integer] Requested month # @return [Array<Astronoby::MoonPhase>] List of Moon phases def self.phases_for(year:, month:) Astronoby.cache.fetch([:moon_phases, year, month]) do [ MoonPhase.first_quarter(new(year, month, :first_quarter, -0.75).time), MoonPhase.full_moon(new(year, month, :full_moon, -0.5).time), MoonPhase.last_quarter(new(year, month, :last_quarter, -0.25).time), MoonPhase.new_moon(new(year, month, :new_moon, 0).time), MoonPhase.first_quarter(new(year, month, :first_quarter, 0.25).time), MoonPhase.full_moon(new(year, month, :full_moon, 0.5).time), MoonPhase.last_quarter(new(year, month, :last_quarter, 0.75).time), MoonPhase.new_moon(new(year, month, :new_moon, 1).time), MoonPhase.first_quarter(new(year, month, :first_quarter, 1.25).time) ].select { _1.time.month == month } end end # @param year [Integer] Requested year # @param month [Integer] Requested month # @param phase [Symbol] Moon phase # @param phase_increment [Float] Phase increment def initialize(year, month, phase, phase_increment) @year = year @month = month @phase = phase @phase_increment = phase_increment end # @return [Time] Time of the Moon phase def time correction = moon_phases_periodic_terms .public_send(:"#{@phase}_correction") terrestrial_time = Instant.from_terrestrial_time( julian_ephemeris_day + correction + moon_phases_periodic_terms.additional_corrections ) terrestrial_time.to_time.round end private def portion_of_year days_in_year = Date.new(@year, 12, 31) - Date.new(@year, 1, 1) mid_month = Date.new(@year, @month, 15) mid_month.yday / days_in_year.to_f end def approximate_time ((@year + portion_of_year - BASE_YEAR) * 12.3685).floor + @phase_increment end def julian_centuries approximate_time / 1236.85 end def julian_ephemeris_day 2451550.09766 + 29.530588861 * approximate_time + 0.00015437 * julian_centuries**2 - 0.000000150 * julian_centuries**3 + 0.00000000073 * julian_centuries**4 end def eccentricity_correction 1 - 0.002516 * julian_centuries - 0.0000074 * julian_centuries**2 end def sun_mean_anomaly Angle.from_degrees( ( 2.5534 + 29.10535670 * approximate_time - 0.0000014 * julian_centuries**2 - 0.00000011 * julian_centuries**3 ) % 360 ) end def moon_mean_anomaly Angle.from_degrees( ( 201.5643 + 385.81693528 * approximate_time + 0.0107582 * julian_centuries**2 + 0.00001238 * julian_centuries**3 - 0.000000058 * julian_centuries**4 ) % 360 ) end def moon_argument_of_latitude Angle.from_degrees( ( 160.7108 + 390.67050284 * approximate_time - 0.0016118 * julian_centuries**2 - 0.00000227 * julian_centuries**3 + 0.000000011 * julian_centuries**4 ) % 360 ) end def longitude_of_the_ascending_node Angle.from_degrees( ( 124.7746 - 1.56375588 * approximate_time + 0.0020672 * julian_centuries**2 + 0.00000215 * julian_centuries**3 ) % 360 ) end def moon_phases_periodic_terms MoonPhasesPeriodicTerms.new( julian_centuries: julian_centuries, time: approximate_time, eccentricity_correction: eccentricity_correction, moon_mean_anomaly: moon_mean_anomaly, sun_mean_anomaly: sun_mean_anomaly, moon_argument_of_latitude: moon_argument_of_latitude, longitude_of_the_ascending_node: longitude_of_the_ascending_node ) end end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/events/twilight_events.rb
lib/astronoby/events/twilight_events.rb
# frozen_string_literal: true module Astronoby class TwilightEvents attr_reader :morning_civil_twilight_times, :evening_civil_twilight_times, :morning_nautical_twilight_times, :evening_nautical_twilight_times, :morning_astronomical_twilight_times, :evening_astronomical_twilight_times def initialize( morning_civil, evening_civil, morning_nautical, evening_nautical, morning_astronomical, evening_astronomical ) @morning_civil_twilight_times = morning_civil @evening_civil_twilight_times = evening_civil @morning_nautical_twilight_times = morning_nautical @evening_nautical_twilight_times = evening_nautical @morning_astronomical_twilight_times = morning_astronomical @evening_astronomical_twilight_times = evening_astronomical end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/events/rise_transit_set_event.rb
lib/astronoby/events/rise_transit_set_event.rb
# frozen_string_literal: true module Astronoby class RiseTransitSetEvent attr_reader :rising_time, :transit_time, :setting_time def initialize(rising, transit, setting) @rising_time = rising @transit_time = transit @setting_time = setting end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/coordinates/equatorial.rb
lib/astronoby/coordinates/equatorial.rb
# frozen_string_literal: true module Astronoby module Coordinates class Equatorial attr_reader :declination, :right_ascension, :hour_angle, :epoch def initialize( declination:, right_ascension:, hour_angle: nil, epoch: JulianDate::DEFAULT_EPOCH ) @right_ascension = right_ascension @declination = declination @hour_angle = hour_angle @epoch = epoch end def self.zero new(declination: Angle.zero, right_ascension: Angle.zero) end def self.from_position_vector(position) return zero if position.zero? term1 = position.z.m term2 = position.magnitude.m declination = Angle.asin(term1 / term2) term1 = position.y.m term2 = position.x.m angle = Angle.atan(term1 / term2) right_ascension = Astronoby::Util::Trigonometry.adjustement_for_arctangent( term1, term2, angle ) new(declination: declination, right_ascension: right_ascension) end def compute_hour_angle(time:, longitude:) last = LocalApparentSiderealTime.from_utc(time.utc, longitude: longitude) ha = (last.time - @right_ascension.hours) ha += Constants::HOURS_PER_DAY if ha.negative? Angle.from_hours(ha) end def to_horizontal(time:, observer:) latitude = observer.latitude longitude = observer.longitude ha = @hour_angle || compute_hour_angle(time: time, longitude: longitude) t0 = @declination.sin * latitude.sin + @declination.cos * latitude.cos * ha.cos altitude = Angle.asin(t0) t1 = @declination.sin - latitude.sin * altitude.sin t2 = t1 / (latitude.cos * altitude.cos) t2 = t2.clamp(-1, 1) azimuth = Angle.acos(t2) if ha.sin.positive? azimuth = Angle.from_degrees(Constants::DEGREES_PER_CIRCLE - azimuth.degrees) end Horizontal.new( azimuth: azimuth, altitude: altitude, observer: observer ) end # Source: # Title: Celestial Calculations # Author: J. L. Lawrence # Edition: MIT Press # Chapter: 4 - Orbits and Coordinate Systems def to_ecliptic(instant:) mean_obliquity = MeanObliquity.at(instant) y = Angle.from_radians( @right_ascension.sin * mean_obliquity.cos + @declination.tan * mean_obliquity.sin ) x = Angle.from_radians(@right_ascension.cos) r = Angle.atan(y.radians / x.radians) longitude = Util::Trigonometry.adjustement_for_arctangent(y, x, r) latitude = Angle.asin( @declination.sin * mean_obliquity.cos - @declination.cos * mean_obliquity.sin * @right_ascension.sin ) Ecliptic.new( latitude: latitude, longitude: longitude ) end end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/coordinates/horizontal.rb
lib/astronoby/coordinates/horizontal.rb
# frozen_string_literal: true module Astronoby module Coordinates class Horizontal attr_reader :azimuth, :altitude, :observer def initialize( azimuth:, altitude:, observer: ) @azimuth = azimuth @altitude = altitude @observer = observer end end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/coordinates/ecliptic.rb
lib/astronoby/coordinates/ecliptic.rb
# frozen_string_literal: true module Astronoby module Coordinates class Ecliptic attr_reader :latitude, :longitude def initialize(latitude:, longitude:) @latitude = latitude @longitude = longitude end def self.zero new(latitude: Angle.zero, longitude: Angle.zero) end end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/angles/hms.rb
lib/astronoby/angles/hms.rb
# frozen_string_literal: true module Astronoby class Hms attr_reader :hours, :minutes, :seconds def initialize(hours, minutes, seconds) @hours = hours @minutes = minutes @seconds = seconds end def format(precision: 4) "#{hours}h #{minutes}m #{seconds.floor(precision)}s" end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
rhannequin/astronoby
https://github.com/rhannequin/astronoby/blob/8d0575dc373ae74b473ec7e0766396810d1fde6c/lib/astronoby/angles/dms.rb
lib/astronoby/angles/dms.rb
# frozen_string_literal: true module Astronoby class Dms attr_reader :sign, :degrees, :minutes, :seconds def initialize(sign, degrees, minutes, seconds) @sign = sign @degrees = degrees @minutes = minutes @seconds = seconds end def format(precision: 4) "#{sign}#{degrees}° #{minutes}′ #{seconds.floor(precision)}″" end end end
ruby
MIT
8d0575dc373ae74b473ec7e0766396810d1fde6c
2026-01-04T17:42:41.845693Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/spec/spec_helper.rb
spec/spec_helper.rb
# frozen_string_literal: true begin require "debug" unless ENV["CI"] == "true" rescue LoadError end ENV["RAILS_ENV"] = "test" require "bundler" require "combustion" require "callback_hell" begin Bundler.require :default, :development # See https://github.com/pat/combustion Combustion.initialize!(:active_record, :active_model) do config.logger = Logger.new(nil) config.log_level = :fatal end rescue => e # Fail fast if application couldn't be loaded $stdout.puts "Failed to load the app: #{e.message}\n#{e.backtrace.take(5).join("\n")}" exit(1) end Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].sort.each { |f| require f } require "rspec/rails" # Stub IO console for table_tennis if it's not available # https://github.com/gurgeous/table_tennis/blob/c26968ce003cf766afa9e8511f9e040d5071d519/test/test_helper.rb#L90 # rubocop:disable Layout/EmptyLineBetweenDefs class FakeConsole def fileno = 123 def getbyte = fakeread.shift def raw = yield def syswrite(str) = fakewrite << str def winsize = [2400, 800] def fakeread = (@fakeread ||= []) def fakewrite = (@fakewrite ||= StringIO.new) end # rubocop:enable Layout/EmptyLineBetweenDefs if IO.console.nil? IO.define_singleton_method(:console) { FakeConsole.new } end RSpec.configure do |config| config.mock_with :rspec config.example_status_persistence_file_path = "tmp/rspec_examples.txt" config.filter_run :focus config.run_all_when_everything_filtered = true config.order = :random Kernel.srand config.seed config.after(:each) do ENV.delete("format") ENV.delete("model") ENV.delete("path") ENV.delete("sort") ENV.delete("mode") end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/spec/support/shared_contexts/callbacks.rb
spec/support/shared_contexts/callbacks.rb
# frozen_string_literal: true RSpec.shared_context "test callbacks" do let(:model_class) { Class.new(ApplicationRecord) { def self.name "TestModel" end } } let(:callbacks) do [ CallbackHell::Callback.new( model: model_class, rails_callback: double( "Callback", kind: :before, filter: :regular_callback, instance_variable_get: nil ), name: "save", defining_class: model_class ), CallbackHell::Callback.new( model: model_class, rails_callback: double( "Callback", kind: :after, filter: :conditional_callback, instance_variable_get: ->(var) { (var == :@if) ? [:condition] : nil } ), name: "save", defining_class: model_class ), CallbackHell::Callback.new( model: model_class, rails_callback: double( "Callback", kind: :before, filter: ActiveRecord::Validations::PresenceValidator.new(attributes: [:parent]), instance_variable_get: nil ), name: "validation", defining_class: model_class ).tap { |cb| allow(cb).to receive(:origin).and_return(:rails) allow(cb).to receive(:association_generated).and_return(true) allow(cb).to receive(:attribute_generated).and_return(true) # Added this allow(cb).to receive(:inherited).and_return(true) }, CallbackHell::Callback.new( model: model_class, rails_callback: double( "Callback", kind: :after, filter: :gem_callback, instance_variable_get: ->(var) { (var == :@if) ? [:condition] : nil } ), name: "commit", defining_class: Class.new { def self.name "GemModule" end } ).tap { |cb| allow(cb).to receive(:inherited).and_return(true) } ] end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/spec/support/shared_contexts/validations.rb
spec/support/shared_contexts/validations.rb
# frozen_string_literal: true RSpec.shared_context "test validation callbacks" do let(:model_class) { Class.new(ApplicationRecord) { def self.name "TestModel" end } } let(:validation_callbacks) do [ # A presence validator CallbackHell::Callback.new( model: model_class, rails_callback: double( "Callback", kind: :before, filter: ActiveModel::Validations::PresenceValidator.new(attributes: [:name]), instance_variable_get: ->(var) { (var == :@if) ? [:condition] : nil } ), name: "validate", defining_class: model_class ).tap { |cb| allow(cb).to receive(:association_generated).and_return(true) allow(cb).to receive(:attribute_generated).and_return(true) allow(cb).to receive(:inherited).and_return(true) }, # A custom validation method CallbackHell::Callback.new( model: model_class, rails_callback: double( "Callback", kind: :before, filter: :validate_publish_date_must_be_in_december, instance_variable_get: nil ), name: "validate", defining_class: model_class ), # An associated records validation CallbackHell::Callback.new( model: model_class, rails_callback: double( "Callback", kind: :before, filter: :validate_associated_records_for_comments, instance_variable_get: nil ), name: "validate", defining_class: model_class ) ] end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/spec/support/matchers/callback_matchers.rb
spec/support/matchers/callback_matchers.rb
# frozen_string_literal: true # RSpec.describe "Rails default callbacks" do # let(:application_record) { ApplicationRecord } # let(:callbacks) { CallbackHell::Collector.new(application_record).collect } # # it "has inherited callbacks from a module" do # expect(bar).to have_callback( # callback_name: :after_commit, # method_name: :be_annoying, # inherited: true # ) # end # # it "has default Rails callbacks" do # # Using glob pattern # expect(callbacks).to have_callback( # method_name: "*_encrypted_attributes_*", # origin: :rails, # inherited: :own # ) # # # Using regex # expect(callbacks).to have_callback( # method_name: /normalize_.*_attributes/, # origin: :rails, # inherited: :own # ) # end # end # # # RSpec.describe "Rails default callbacks" do # let(:application_record) { ApplicationRecord } # let(:callbacks) { CallbackHell::Collector.new(application_record).collect } # # it "has specific callbacks" do # # Complete absence of a callback # expect(callbacks).not_to have_callback( # method_name: "nonexistent_callback" # ) # # # Has a callback with specific attributes but different origin # expect(callbacks).to have_callback( # method_name: "*_encrypted_attributes_*" # ).but_with(origin: :own) # # # More complex example # expect(callbacks).to have_callback( # method_name: /normalize_.*_attributes/, # origin: :rails # ).but_with(inherited: :inherited) # end # end RSpec::Matchers.define :have_callback do |expected| match do |callbacks| @callbacks = callbacks.is_a?(Array) ? callbacks : [callbacks] @mismatches = [] @callbacks.any? do |callback| @current_callback = callback matches = expected.all? do |key, value| result = case key when :callback_name kind, group = value.to_s.split("_", 2) callback.kind.to_s == kind && callback.callback_group.to_s == group else actual = callback.public_send(key) case value when String, Symbol File.fnmatch?(value.to_s, actual.to_s) when Regexp value.match?(actual.to_s) else actual == value end end unless result actual = case key when :callback_name "#{callback.kind}_#{callback.callback_group}" else callback.public_send(key) end @mismatches << "#{key}: expected #{value.inspect}, got #{actual.inspect}" end result end if @but_with && matches matches = @but_with.all? do |key, value| actual = callback.public_send(key) result = actual.to_s != value.to_s @mismatches << "#{key}: expected not #{value.inspect}, got #{actual.inspect}" unless result result end end if matches @matching_callback = callback true else @mismatches << "---" false end end end chain :but_with do |additional| @but_with = additional end failure_message do |_callbacks| message = ["expected to find callback matching #{expected.inspect}"] message << "but with #{@but_with.inspect}" if @but_with message << "\nMismatches:" message += @mismatches.uniq message.join("\n") end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/spec/support/matchers/validation_matchers.rb
spec/support/matchers/validation_matchers.rb
# frozen_string_literal: true # RSpec.describe "Validations" do # let(:callbacks) { CallbackHell::Collector.new(model, kind: :validations).collect } # it "has presence validation" do # expect(callbacks).to have_validation( # type: "presence", # method_name: "validates_presence_of" # ) # end # it "has custom validation" do # expect(callbacks).to have_validation( # type: "custom", # inherited: true # ) # end # # With negation # it "has presence validation but not inherited" do # expect(callbacks).to have_validation( # type: "presence" # ).but_with(inherited: true) # end # end RSpec::Matchers.define :have_validation do |expected| match do |callbacks| @callbacks = callbacks.is_a?(Array) ? callbacks : [callbacks] @mismatches = [] @callbacks.any? do |callback| next unless callback.callback_group == "validate" @current_callback = callback matches = expected.all? do |key, value| result = case key when :type callback.validation_type.to_s == value.to_s else actual = callback.public_send(key) case value when String, Symbol File.fnmatch?(value.to_s, actual.to_s) when Regexp value.match?(actual.to_s) else actual == value end end unless result actual = case key when :type callback.validation_type else callback.public_send(key) end @mismatches << "#{key}: expected #{value.inspect}, got #{actual.inspect}" end result end if @but_with && matches matches = @but_with.all? do |key, value| actual = callback.public_send(key) result = actual.to_s != value.to_s @mismatches << "#{key}: expected not #{value.inspect}, got #{actual.inspect}" unless result result end end if matches @matching_callback = callback true else @mismatches << "---" false end end end chain :but_with do |additional| @but_with = additional end failure_message do |_callbacks| message = ["expected to find validation matching #{expected.inspect}"] message << "but with #{@but_with.inspect}" if @but_with message << "\nMismatches:" message += @mismatches.uniq message.join("\n") end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/spec/modelscope/tasks/modelscope_rake_spec.rb
spec/modelscope/tasks/modelscope_rake_spec.rb
# frozen_string_literal: true require "rake" RSpec.describe "rake ch:callbacks" do let(:task_name) { "ch:callbacks" } before(:all) do Rake::Task.clear load "lib/tasks/callback_hell.rake" end around do |example| original_stdout = $stdout $stdout = StringIO.new example.run $stdout = original_stdout end it "runs with default parameters" do expect(CallbackHell::Runner).to receive(:run) .with(kind: :callbacks, mode: :default) Rake::Task[task_name].execute end it "accepts format parameter" do ENV["format"] = "line" expect(CallbackHell::Runner).to receive(:run) .with(format: "line", kind: :callbacks, mode: :default) Rake::Task[task_name].execute end it "accepts sort parameter" do ENV["sort"] = "name:asc" expect(CallbackHell::Runner).to receive(:run) .with(kind: :callbacks, sort_by: :name, sort_order: :asc, mode: :default) Rake::Task[task_name].execute end it "accepts partial sort" do ENV["sort"] = "size" expect(CallbackHell::Runner).to receive(:run) .with(kind: :callbacks, sort_by: :size, sort_order: :desc, mode: :default) Rake::Task[task_name].execute end it "accepts mode parameter" do ENV["mode"] = "full" expect(CallbackHell::Runner).to receive(:run) .with(kind: :callbacks, mode: :full) Rake::Task[task_name].execute end it "accepts model parameter" do ENV["model"] = "User" expect(CallbackHell::Runner).to receive(:run) .with(model: "User", kind: :callbacks, mode: :default) Rake::Task[task_name].execute end it "accepts path parameter and converts it to Rails paths" do ENV["path"] = "app/models,lib/models" expect(CallbackHell::Runner).to receive(:run) .with( paths: [Rails.root.join("app/models"), Rails.root.join("lib/models")], kind: :callbacks, mode: :default ) Rake::Task[task_name].execute end it "accepts multiple parameters together" do ENV["format"] = "github" ENV["model"] = "Admin::User" ENV["path"] = "engines/admin/app/models" expect(CallbackHell::Runner).to receive(:run) .with( format: "github", model: "Admin::User", paths: [Rails.root.join("engines/admin/app/models")], kind: :callbacks, mode: :default ) Rake::Task[task_name].execute end end RSpec.describe "rake ch:validations" do let(:task_name) { "ch:validations" } before(:all) do Rake::Task.clear load "lib/tasks/callback_hell.rake" end before do ENV.delete("format") ENV.delete("model") ENV.delete("path") ENV.delete("sort") end around do |example| original_stdout = $stdout $stdout = StringIO.new example.run $stdout = original_stdout end it "runs with default parameters" do expect(CallbackHell::Runner).to receive(:run) .with(kind: :validations) Rake::Task[task_name].execute end it "accepts format parameter" do ENV["format"] = "line" expect(CallbackHell::Runner).to receive(:run) .with(format: "line", kind: :validations) Rake::Task[task_name].execute end it "accepts model parameter" do ENV["model"] = "User" expect(CallbackHell::Runner).to receive(:run) .with(model: "User", kind: :validations) Rake::Task[task_name].execute end it "accepts path parameter and converts it to Rails paths" do ENV["path"] = "app/models,lib/models" expect(CallbackHell::Runner).to receive(:run) .with( paths: [Rails.root.join("app/models"), Rails.root.join("lib/models")], kind: :validations ) Rake::Task[task_name].execute end end RSpec.describe "rake ch:report" do let(:task_name) { "ch:report" } before(:all) do Rake::Task.clear load "lib/tasks/callback_hell.rake" end before do ENV.delete("format") ENV.delete("model") ENV.delete("path") end around do |example| original_stdout = $stdout $stdout = StringIO.new example.run $stdout = original_stdout end it "runs with default parameters" do expect(CallbackHell::Runner).to receive(:run) .with(kind: :report) Rake::Task[task_name].execute end it "accepts format parameter" do ENV["format"] = "line" expect(CallbackHell::Runner).to receive(:run) .with(format: "line", kind: :report) Rake::Task[task_name].execute end it "accepts model parameter" do ENV["model"] = "User" expect(CallbackHell::Runner).to receive(:run) .with(model: "User", kind: :report) Rake::Task[task_name].execute end it "accepts path parameter and converts it to Rails paths" do ENV["path"] = "app/models,lib/models" expect(CallbackHell::Runner).to receive(:run) .with( paths: [Rails.root.join("app/models"), Rails.root.join("lib/models")], kind: :report ) Rake::Task[task_name].execute end end RSpec.describe "rake ch (default task)" do it "runs the report task as default" do Rake::Task.clear load "lib/tasks/callback_hell.rake" task = Rake::Task["ch"] expect(task).to be_present expect(task.prerequisites).to include("ch:report") end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/spec/modelscope/integration/association_spec.rb
spec/modelscope/integration/association_spec.rb
# frozen_string_literal: true RSpec.describe CallbackHell, "with association-caused callbacks" do subject(:foo) { CallbackHell::Collector.new(Foo, mode: :full).collect } subject(:bar) { CallbackHell::Collector.new(Bar, mode: :full).collect } it "has collection saving-related callbacks" do expect(foo).to have_callback( callback_name: :after_create, method_name: :autosave_associated_records_for_bars, association_generated: true, origin: :rails ) expect(foo).to have_callback( callback_name: :after_update, method_name: :autosave_associated_records_for_bars, association_generated: true, origin: :rails ) expect(foo).to have_callback( callback_name: :around_save, method_name: :around_save_collection_association, association_generated: true, origin: :rails ) expect(bar).to have_callback( callback_name: :before_save, method_name: :autosave_associated_records_for_foo, association_generated: true, origin: :rails ) end it "correctly marks the validations generated by associations" do expect(foo).to have_validation( type: :associated, method_name: :validate_associated_records_for_bars, origin: :rails, association_generated: true ) expect(bar).to have_validation( type: :associated, human_method_name: /^Presence.*\(foo\)/, origin: :rails, association_generated: true ) end it "has a dependent: destroy callback" do expect(foo).to have_callback( callback_name: :before_destroy, association_generated: true, origin: :rails ) end it "has an association validator" do expect(foo).to have_callback( callback_name: :before_validate, method_name: /^validate_associated/, origin: :rails ) end it "does not cause false positives when it comes to association callbacks" do expect(foo).to have_callback( callback_name: :after_validation, method_name: :noop, association_generated: false ) expect(foo).to have_callback( callback_name: :after_create, method_name: :noop, association_generated: false ) expect(foo).to have_callback( callback_name: :around_create, method_name: :noop, association_generated: false ) expect(foo).to have_validation( type: :presence, human_method_name: /Presence.*\(name\)/, association_generated: false ) expect(foo).to have_validation( type: :uniqueness, human_method_name: /Uniqueness.*\(name\)/, association_generated: false ) end context "with mode=default" do subject(:foo) { CallbackHell::Collector.new(Foo, mode: :default).collect } it "has no association callbacks" do expect(foo).not_to have_callback(association_generated: true) end end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/spec/modelscope/integration/empty_activerecord_spec.rb
spec/modelscope/integration/empty_activerecord_spec.rb
# frozen_string_literal: true RSpec.describe CallbackHell, "with an empty ActiveRecord" do def normalization_supported? ActiveRecord::Base.respond_to?(:normalizes) end let(:options) { {} } subject(:ar) { CallbackHell::Collector.new(ApplicationRecord, **options).collect } it "does not have any own or rails callbacks or validations" do expect(ar).not_to have_callback(origin: :rails) expect(ar).not_to have_callback(origin: :own) expect(ar).not_to have_validation(origin: :own) end context "with full mode" do let(:options) { {mode: :full} } it "does have callbacks on an empty ActiveRecord class" do expect(ar).to have_callback( method_name: :cant_modify_encrypted_attributes_when_frozen, origin: :rails, inherited: false ) if normalization_supported? expect(ar).to have_callback( method_name: :normalize_changed_in_place_attributes, origin: :rails, inherited: false ) end end end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/spec/modelscope/integration/external_callbacks_spec.rb
spec/modelscope/integration/external_callbacks_spec.rb
# frozen_string_literal: true RSpec.describe CallbackHell, "with external ('gem') callbacks and validations" do subject(:bar) { CallbackHell::Collector.new(Bar, mode: :full).collect } it "has callbacks" do expect(bar).to have_callback( callback_name: :after_commit, method_name: :save_tags, origin: :gems, inherited: false ) end it "has validations" do expect(bar).to have_validation( type: :custom, method_name: :validate_tags, origin: :gems, inherited: false ) end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/spec/modelscope/integration/attribute_generated_spec.rb
spec/modelscope/integration/attribute_generated_spec.rb
# frozen_string_literal: true RSpec.describe CallbackHell, "with attribute-generated callbacks and validations" do def normalization_supported? ActiveRecord::Base.respond_to?(:normalizes) end subject(:foo) { CallbackHell::Collector.new(Foo, mode: :full).collect } subject(:bar) { CallbackHell::Collector.new(Bar, mode: :full).collect } it "correctly marks the callbacks generated by attributes" do skip "Normalization not supported in this Rails version" unless normalization_supported? expect(foo).to have_callback( callback_name: :before_validate, method_name: :cant_modify_encrypted_attributes_when_frozen, attribute_generated: true, origin: :rails ) expect(foo).to have_callback( callback_name: :before_validation, method_name: :normalize_changed_in_place_attributes, attribute_generated: true, origin: :rails ) end it "does not cause false positives when it comes to attribute callbacks" do expect(foo).to have_callback( callback_name: :after_validation, method_name: :noop, attribute_generated: false, origin: :own ) expect(foo).to have_callback( callback_name: :after_create, method_name: :noop, attribute_generated: false, origin: :own ) end it "correctly marks the validations generated by attributes" do expect(foo).to have_validation( type: :custom, method_name: :cant_modify_encrypted_attributes_when_frozen, attribute_generated: true, origin: :rails ) end context "with mode=default" do subject(:foo) { CallbackHell::Collector.new(Foo, mode: :default).collect } it "has no attribute callbacks" do expect(foo).not_to have_callback(attribute_generated: true) end end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/spec/modelscope/integration/self_defined_spec.rb
spec/modelscope/integration/self_defined_spec.rb
# frozen_string_literal: true RSpec.describe CallbackHell, "with user-defined callbacks and validations" do subject(:foo) { CallbackHell::Collector.new(Foo, mode: :full).collect } subject(:bar) { CallbackHell::Collector.new(Bar, kind: :validations, mode: :full).collect } it "does have manually added callbacks" do expect(foo).to have_callback( callback_name: :before_validation, method_name: :noop, origin: :own ) expect(foo).to have_callback( callback_name: :after_validation, method_name: :noop, origin: :own ) expect(foo).to have_callback( callback_name: :before_create, method_name: :noop, origin: :own ) expect(foo).to have_callback( callback_name: :after_create, method_name: :noop, origin: :own ) end it "does have manually added callbacks with detected conditions" do expect(foo).to have_callback( callback_name: :around_create, method_name: :noop, origin: :own, conditional: true ) end it "does have manually added validations" do expect(foo).to have_validation( type: :presence, human_method_name: /\(name\)/, origin: :own ) expect(foo).to have_validation( type: :uniqueness, human_method_name: /\(name\)/, origin: :own ) expect(bar).to have_validation( type: :presence, human_method_name: /\(name\)/, origin: :own ) end it "does have manually added validations with detected conditions" do expect(foo).to have_validation( type: :presence, human_method_name: /\(title\)/, origin: :own, conditional: true ) end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/spec/modelscope/integration/inherited_spec.rb
spec/modelscope/integration/inherited_spec.rb
# frozen_string_literal: true RSpec.describe CallbackHell, "with inherited callbacks and validations" do subject(:bar) { CallbackHell.collect_callbacks(Bar) } subject(:bar_jr) { CallbackHell.collect_callbacks(BarJr) } specify do expect(bar_jr.size).to eq(bar.size) end it "has inherited callbacks and validations from a module" do expect(bar).to have_callback( callback_name: :after_commit, method_name: :be_annoying, inherited: false ) expect(bar).not_to have_validation( type: :custom, method_name: :be_annoying, inherited: false ) end it "has inherited callbacks and validations from a class" do expect(bar_jr).to have_callback( callback_name: :after_commit, method_name: :be_annoying, origin: :own, inherited: true ) expect(bar_jr).not_to have_validation( type: :presence, human_method_name: /^Presence.*\(name\)/, origin: :own, inherited: true ) expect(bar).to have_callback( callback_name: :after_commit, method_name: :noop, origin: :own, inherited: false ) expect(bar_jr).to have_callback( callback_name: :after_commit, method_name: :noop, origin: :own, inherited: true ) end context "with mode=full" do subject(:bar) { CallbackHell.collect_callbacks(Bar, mode: :full) } subject(:bar_jr) { CallbackHell.collect_callbacks(BarJr, mode: :full) } specify do expect(bar_jr.size).to eq(bar.size) end it "has inherited validation callbacks" do expect(bar).to have_validation( type: :custom, method_name: :be_annoying, inherited: false ) expect(bar_jr).to have_validation( type: :presence, human_method_name: /^Presence.*\(name\)/, origin: :own, inherited: true ) end end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/spec/modelscope/integration/modelscope_spec.rb
spec/modelscope/integration/modelscope_spec.rb
# frozen_string_literal: true RSpec.describe CallbackHell do context "with reporting" do it "supports different formats" do line = callback_hell("Foo", format: :line) expect(line).to include("after_validation") expect(line).to include("after_create") table = callback_hell("Foo", format: :table) expect(table).to_not include("after_create") expect(table).to include("all") expect(table).to include("/create") end end context "with model filtering" do it "can handle both file name and model name as a parameter" do expect(callback_hell("foo")).to eq(callback_hell("Foo")) end it "can load models both by file/name and Constant::Name" do expect(callback_hell("bar/baz")).to eq(callback_hell("Bar::Baz")) end end def callback_hell(model, format: :line) CallbackHell::Runner.run(model: model, format: format) end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/spec/modelscope/lib/stats_spec.rb
spec/modelscope/lib/stats_spec.rb
# frozen_string_literal: true RSpec.describe CallbackHell::Stats do let(:model_class) { Class.new } let(:callbacks) do [ double( "Callback", model: model_class, origin: :own, inherited: false, conditional: true, callback_group: "save", association_generated: false, attribute_generated: true ), double( "Callback", model: model_class, origin: :rails, inherited: false, conditional: false, callback_group: "validation", association_generated: true, attribute_generated: false ) ] end before do allow(model_class).to receive(:name).and_return("TestModel") end describe "#by_model" do let(:another_model_class) { Class.new } before do allow(another_model_class).to receive(:name).and_return("AnotherModel") end let(:all_callbacks) do [*callbacks, double( "Callback", model: another_model_class, origin: :rails, inherited: false, conditional: false, callback_group: "validation", association_generated: true, attribute_generated: false )] end it "groups callbacks by model name" do stats = described_class.new(all_callbacks) expect(stats.by_model["TestModel"]).to eq(callbacks) end context "with sort_by=size&sort_order=desc" do it "sorts callbacks by size in descending order" do stats = described_class.new(all_callbacks, sort_by: :size, sort_order: :desc).by_model expect(stats.first.first).to eq("TestModel") end end context "with sort_by=size&sort_order=asc" do it "sorts callbacks by size in descending order" do stats = described_class.new(all_callbacks, sort_by: :size, sort_order: :asc).by_model expect(stats.first.first).to eq("AnotherModel") end end context "with sort_by=name&sort_order=asc" do it "sorts callbacks by size in descending order" do stats = described_class.new(all_callbacks, sort_by: :name, sort_order: :asc).by_model expect(stats.first.first).to eq("AnotherModel") end end end describe "#stats_for" do subject(:stats) { described_class.new(callbacks).stats_for("TestModel") } it "counts callbacks by their properties" do expect(stats[:total]).to eq(2) expect(stats[:own]).to eq(1) expect(stats[:conditional]).to eq(1) expect(stats[:association_generated]).to eq(1) expect(stats[:attribute_generated]).to eq(1) end it "returns empty hash for unknown model" do expect(described_class.new(callbacks).stats_for("Unknown")).to eq({}) end end describe "#stats_for_group" do it "returns stats for specific callback group" do stats = described_class.new(callbacks).stats_for_group("TestModel", "save") expect(stats[:total]).to eq(1) expect(stats[:attribute_generated]).to eq(1) expect(stats[:association_generated]).to eq(0) end it "returns zero counts for unknown group" do stats = described_class.new(callbacks).stats_for_group("TestModel", "unknown") expect(stats[:total]).to eq(0) end end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/spec/modelscope/lib/collector_spec.rb
spec/modelscope/lib/collector_spec.rb
# frozen_string_literal: true RSpec.describe CallbackHell::Collector do let(:test_model) { Class.new(ApplicationRecord) } before do stub_const("TestModel", test_model) allow(ApplicationRecord).to receive(:descendants).and_return([test_model]) end describe "collecting" do it "returns array of Callback objects" do collector = described_class.new(test_model) expect(collector.collect).to all(be_a(CallbackHell::Callback)) end it "accepts array of models" do test_model2 = Class.new(ApplicationRecord) stub_const("TestModel2", test_model2) collector = described_class.new([test_model, test_model2], mode: :full) models = collector.collect.map(&:model).uniq expect(models).to match_array([test_model, test_model2]) end context "with validation kind" do it "filters only validation callbacks" do callbacks = double("Callbacks", slice: {validate: []}) allow(test_model).to receive(:__callbacks).and_return(callbacks) collector = described_class.new(test_model, kind: :validations) collector.collect expect(callbacks).to have_received(:slice).with(:validate) end end context "with callbacks kind" do it "does not filter callbacks" do callbacks = double("Callbacks") allow(callbacks).to receive(:flat_map).and_return([]) allow(callbacks).to receive(:slice) # add this allow(test_model).to receive(:__callbacks).and_return(callbacks) collector = described_class.new(test_model, kind: :callbacks) collector.collect expect(callbacks).not_to have_received(:slice) end end end describe "with models" do it "returns passed models as a set" do collector = described_class.new(test_model) expect(collector.models).to be_a(Set) expect(collector.models.first).to eq(test_model) end it "discovers application models when no models passed" do stub_const("TestModel", test_model) allow(ApplicationRecord).to receive(:descendants).and_return([test_model]) allow(Rails.application).to receive(:eager_load!) collector = described_class.new expect(collector.models.to_a).to eq([test_model]) end end describe "paths handling" do before do allow_any_instance_of(Pathname).to receive(:exist?).and_return(true) end it "accepts additional paths" do test_path = Rails.root.join("extra_models") collector = described_class.new(nil, paths: test_path) expect(collector.send(:model_paths)).to include(test_path) end it "includes Rails Engine paths" do engine_path = Rails.root.join("engine_path/app/models") engine = Class.new(Rails::Engine) do define_singleton_method(:root) { Rails.root.join("engine_path") } end allow(Rails::Engine).to receive(:subclasses).and_return([engine]) collector = described_class.new expect(collector.send(:model_paths)).to include(engine_path) end end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/spec/modelscope/lib/callback_spec.rb
spec/modelscope/lib/callback_spec.rb
# frozen_string_literal: true RSpec.describe CallbackHell::Callback do let(:base_class) do Class.new do def self.name "TestModel" end def callback_method end end end let(:method) { base_class.instance_method(:callback_method) } describe "callback origin" do before do allow(method).to receive(:owner).and_return(base_class) allow(base_class).to receive(:instance_method).with(:callback_method).and_return(method) end it "detects Rails callbacks" do allow(method).to receive(:source_location) .and_return([Gem.loaded_specs["activerecord"].full_gem_path + "/lib/active_record.rb"]) callback = described_class.new( model: base_class, rails_callback: double("Callback", kind: :before, filter: :callback_method, instance_variable_get: nil), name: :save, defining_class: base_class ) expect(callback.origin).to eq(:rails) end it "detects gem callbacks" do allow(method).to receive(:source_location).and_return(["gems/devise/lib/devise.rb"]) callback = described_class.new( model: base_class, rails_callback: double("Callback", kind: :before, filter: :callback_method, instance_variable_get: nil), name: :save, defining_class: base_class ) expect(callback.origin).to eq(:gems) end it "detects own callbacks" do allow(method).to receive(:source_location).and_return([Rails.root.join("app/models/test.rb").to_s]) callback = described_class.new( model: base_class, rails_callback: double("Callback", kind: :before, filter: :callback_method, instance_variable_get: nil), name: :save, defining_class: base_class ) expect(callback.origin).to eq(:own) end end describe "validation types" do subject(:callback) do described_class.new( model: base_class, rails_callback: double( "Callback", kind: :before, filter: method_name, instance_variable_get: nil ), name: :validate, defining_class: base_class ) end { validates_presence_of: "presence", validate_presence: "presence", validates_uniqueness_of: "uniqueness", validate_uniqueness: "uniqueness", validates_format_of: "format", validate_format: "format", validates_length_of: "length", validate_length: "length", validates_inclusion_of: "inclusion", validate_inclusion: "inclusion", validates_exclusion_of: "exclusion", validate_exclusion: "exclusion", validates_numericality_of: "numericality", validate_numericality: "numericality", validates_acceptance_of: "acceptance", validate_acceptance: "acceptance", validates_confirmation_of: "confirmation", validate_confirmation: "confirmation", validate_associated_records_for_comments: "associated", validate_associated_records_for_attachments: "associated", validate_publish_date_must_be_in_december: "custom", some_random_validation_method: "custom" }.each do |method, expected_type| context "with #{method}" do let(:method_name) { method } it "returns #{expected_type}" do expect(callback.validation_type).to eq(expected_type) end end end context "with non-standard validations" do let(:method_name) { proc { true } } it "returns custom for procs" do expect(callback.validation_type).to eq("custom") end end end describe "with humanized method names" do it "formats proc callbacks with location" do source_file = "active_record/associations/builder/belongs_to.rb" proc = proc { true } allow(proc).to receive(:source_location).and_return([source_file, 30]) callback = described_class.new( model: base_class, rails_callback: double("Callback", kind: :before, filter: proc, instance_variable_get: nil), name: :save, defining_class: base_class ) expect(callback.human_method_name).to eq("Proc (builder/belongs_to.rb:30)") end it "handles procs without source location" do proc = proc { true } allow(proc).to receive(:source_location).and_return(nil) callback = described_class.new( model: base_class, rails_callback: double("Callback", kind: :before, filter: proc, instance_variable_get: nil), name: :save, defining_class: base_class ) expect(callback.human_method_name).to eq("Proc (unknown location)") end it "formats validator callbacks with attributes" do validator = ActiveRecord::Validations::PresenceValidator.new(attributes: [:name, :email]) allow(base_class).to receive(:reflect_on_association).and_return(nil) callback = described_class.new( model: base_class, rails_callback: double("Callback", kind: :before, filter: validator, instance_variable_get: nil), name: :validation, defining_class: base_class ) expect(callback.human_method_name).to eq("PresenceValidator (name, email)") end it "returns method name for symbol callbacks" do callback = described_class.new( model: base_class, rails_callback: double("Callback", kind: :before, filter: :my_callback, instance_variable_get: nil), name: :save, defining_class: base_class ) expect(callback.human_method_name).to eq("my_callback") end end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/spec/modelscope/lib/runner_spec.rb
spec/modelscope/lib/runner_spec.rb
# frozen_string_literal: true RSpec.describe CallbackHell::Runner do let(:collector) { instance_double(CallbackHell::Collector) } let(:report) { instance_double(CallbackHell::Reports::Validations::Table) } before do allow(collector).to receive(:collect).and_return([]) allow(report).to receive(:generate).and_return("Report output") end describe "#run" do it "class delegates to instance" do expect_any_instance_of(described_class).to receive(:run) described_class.run end context "with format handling" do before do allow(CallbackHell::Collector).to receive(:new).and_return(collector) end it "uses table format by default" do expect(CallbackHell::Reports::Callbacks::Table).to receive(:new) .with(any_args) .and_return(report) described_class.new(format: nil, model: nil, paths: nil, kind: :callbacks).run end it "uses correct namespace for validations" do expect(CallbackHell::Reports::Validations::Table).to receive(:new) .with(any_args) .and_return(report) described_class.new(format: nil, model: nil, paths: nil, kind: :validations).run end it "accepts format as string" do expect(CallbackHell::Reports::Callbacks::Github).to receive(:new) .with(any_args) .and_return(report) described_class.new(format: "github", model: nil, paths: nil, kind: :callbacks).run end it "raises error for unknown format" do expect { described_class.new(format: :unknown, model: nil, paths: nil, kind: :callbacks).run }.to raise_error(CallbackHell::Error, /Unknown format/) end end context "with combined report" do let(:callbacks_collector) { instance_double(CallbackHell::Collector) } let(:validations_collector) { instance_double(CallbackHell::Collector) } let(:callbacks_report) { instance_double(CallbackHell::Reports::Callbacks::Table) } let(:validations_report) { instance_double(CallbackHell::Reports::Validations::Table) } let(:model_class) { Class.new } before do allow(CallbackHell::Collector).to receive(:new) .with(anything, hash_including(kind: :callbacks)).and_return(callbacks_collector) allow(CallbackHell::Collector).to receive(:new) .with(anything, hash_including(kind: :validations)).and_return(validations_collector) allow(callbacks_collector).to receive(:collect).and_return([]) allow(validations_collector).to receive(:collect).and_return([]) allow(CallbackHell::Reports::Callbacks::Table).to receive(:new) .and_return(callbacks_report) allow(CallbackHell::Reports::Validations::Table).to receive(:new) .and_return(validations_report) allow(callbacks_report).to receive(:generate).and_return("Callbacks report") allow(validations_report).to receive(:generate).and_return("Validations report") end it "generates both reports when kind is :report" do output = described_class.new(format: :table, model: nil, paths: nil, kind: :report).run expect(output).to eq("Callbacks report\n\nValidations report") end it "passes the model parameter to both collectors" do stub_const("User", model_class) runner = described_class.new(format: :table, model: "User", paths: nil, kind: :report) expect(CallbackHell::Collector).to receive(:new) .with(model_class, hash_including(kind: :callbacks)) .and_return(callbacks_collector) expect(CallbackHell::Collector).to receive(:new) .with(model_class, hash_including(kind: :validations)) .and_return(validations_collector) runner.run end it "passes the paths parameter to both collectors" do paths = [Rails.root.join("extra")] expect(CallbackHell::Collector).to receive(:new) .with(nil, hash_including(paths: paths, kind: :callbacks)) .and_return(callbacks_collector) expect(CallbackHell::Collector).to receive(:new) .with(nil, hash_including(paths: paths, kind: :validations)) .and_return(validations_collector) described_class.new(format: :table, model: nil, paths: paths, kind: :report).run end end context "with model resolution" do before do allow(CallbackHell::Reports::Callbacks::Table).to receive(:new).and_return(report) allow(CallbackHell::Collector).to receive(:new).and_return(collector) end it "accepts constant name" do expect(CallbackHell::Collector).to receive(:new).with(Foo, paths: nil, kind: :callbacks, mode: :default) described_class.new(format: nil, model: "Foo", paths: nil, kind: :callbacks).run end it "accepts file path and converts to constant" do stub_const("Admin::User", Class.new) expect(CallbackHell::Collector).to receive(:new).with(Admin::User, paths: nil, kind: :callbacks, mode: :default) described_class.new(format: nil, model: "admin/user", paths: nil, kind: :callbacks).run end it "fails when model cannot be found" do expect { described_class.new(format: nil, model: "NonExistent", paths: nil, kind: :callbacks).run }.to raise_error(CallbackHell::Error, /Cannot find model/) end end end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/spec/modelscope/lib/reports/callbacks/table_spec.rb
spec/modelscope/lib/reports/callbacks/table_spec.rb
# frozen_string_literal: true RSpec.describe CallbackHell::Reports::Callbacks::Table do include_context "test callbacks" subject(:report) { described_class.new(callbacks, mode: :full) } subject(:output) { report.generate } it "includes all columns" do expect(output).to include("Model") expect(output).to include("Kind") expect(output).to include("Total") expect(output).to include("Own") expect(output).to include("Inherited") expect(output).to include("Rails") expect(output).to include("Associations") expect(output).to include("Attributes") expect(output).to include("Gems") expect(output).to include("Conditional") end it "shows totals for model" do expect(output).to include("TestModel") expect(output).to include("all") expect(output).to match(/\b4\b/) # total expect(output).to match(/\b2\b/) # own expect(output).to match(/\b1\b/) # inherited expect(output).to match(/\b1\b/) # association_generated expect(output).to match(/\b1\b/) # attribute_generated end it "groups callbacks by type" do expect(output).to include("⇥") # before expect(output).to include("↦") # after expect(output).to include("save") expect(output).to include("validation") expect(output).to include("commit") end context "with mode=default" do subject(:report) { described_class.new(callbacks, mode: :default) } it "doesn't include associations and attributes" do expect(output).to include("Model") expect(output).to include("Kind") expect(output).to include("Total") expect(output).to include("Own") expect(output).to include("Inherited") expect(output).not_to include("Rails") expect(output).not_to include("Associations") expect(output).not_to include("Attributes") expect(output).to include("Gems") expect(output).to include("Conditional") end end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/spec/modelscope/lib/reports/callbacks/github_spec.rb
spec/modelscope/lib/reports/callbacks/github_spec.rb
# frozen_string_literal: true RSpec.describe CallbackHell::Reports::Callbacks::Github do include_context "test callbacks" subject(:report) { described_class.new(callbacks) } subject(:output) { report.generate } it "shows model totals" do total_line = output.lines.find { |l| l.include?("kind=all") } expect(total_line).to match(/total=4/) expect(total_line).to match(/own=2/) expect(total_line).to match(/inherited=2/) expect(total_line).to match(/conditional=2/) expect(total_line).to match(/association_generated=1/) expect(total_line).to match(/attribute_generated=1/) end it "groups callbacks correctly" do groups = output.lines.select { |l| l.include?("::debug::") } expect(groups.size).to eq(5) # "all" and four groups before_save_group = groups.find { |l| l.include?("kind=⇥/save") } after_save_group = groups.find { |l| l.include?("kind=↦/save") } validation_group = groups.find { |l| l.include?("kind=⇥/validation") } commit_group = groups.find { |l| l.include?("kind=↦/commit") } expect(before_save_group).to match(/total=1/) expect(before_save_group).to match(/own=1/) expect(before_save_group).to match(/conditional=0/) expect(after_save_group).to match(/total=1/) expect(after_save_group).to match(/own=1/) expect(after_save_group).to match(/conditional=1/) expect(validation_group).to match(/total=1/) expect(validation_group).to match(/rails=1/) expect(commit_group).to match(/total=1/) expect(commit_group).to match(/gems=1/) expect(commit_group).to match(/inherited=1/) expect(commit_group).to match(/conditional=1/) end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/spec/modelscope/lib/reports/callbacks/line_spec.rb
spec/modelscope/lib/reports/callbacks/line_spec.rb
# frozen_string_literal: true RSpec.describe CallbackHell::Reports::Callbacks::Line do include_context "test callbacks" subject(:report) { described_class.new(callbacks) } subject(:output) { report.generate } it "includes report header" do expect(output).to include("Callback Hell callbacks report:") end it "shows model name" do expect(output).to include("TestModel:") end it "shows callback details" do expect(output).to include("before_save") expect(output).to include("after_save") expect(output).to include("method_name: regular_callback") expect(output).to include("origin: own") end it "indicates conditional status" do expect(output).to include("conditional: yes") expect(output).to include("conditional: no") end it "indicates inheritance status" do expect(output).to include("inherited: inherited") expect(output).to include("inherited: own") end it "indicates source types" do expect(output).to include("association_generated: yes") expect(output).to include("attribute_generated: yes") end it "formats each callback on a new line" do lines = output.split("\n") callback_lines = lines.select { |l| l.start_with?(" ") } expect(callback_lines.size).to eq(4) end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/spec/modelscope/lib/reports/validations/table_spec.rb
spec/modelscope/lib/reports/validations/table_spec.rb
# frozen_string_literal: true RSpec.describe CallbackHell::Reports::Validations::Table do include_context "test validation callbacks" subject(:report) { described_class.new(validation_callbacks, mode: :full) } subject(:output) { report.generate } it "includes all columns" do expect(output).to include("Model") expect(output).to include("Kind") expect(output).to include("Total") expect(output).to include("Own") expect(output).to include("Inherited") expect(output).to include("Rails") expect(output).to include("Associations") expect(output).to include("Attributes") expect(output).to include("Gems") expect(output).to include("Conditional") end it "shows totals for model" do expect(output).to include("TestModel") expect(output).to include("all") expect(output).to match(/\b3\b/) # total expect(output).to match(/\b3\b/) # own expect(output).to match(/\b1\b/) # inherited expect(output).to match(/\b1\b/) # association_generated expect(output).to match(/\b1\b/) # attribute_generated end it "groups validations by type" do lines = output.lines expect(lines).to include(match(/associated/)) expect(lines).to include(match(/custom/)) end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/spec/modelscope/lib/reports/validations/github_spec.rb
spec/modelscope/lib/reports/validations/github_spec.rb
# frozen_string_literal: true RSpec.describe CallbackHell::Reports::Validations::Github do include_context "test validation callbacks" subject(:report) { described_class.new(validation_callbacks) } subject(:output) { report.generate } it "shows model totals" do total_line = output.lines.find { |l| l.include?("kind=all") } expect(total_line).to match(/total=3/) expect(total_line).to match(/own=3/) expect(total_line).to match(/inherited=1/) expect(total_line).to match(/conditional=1/) expect(total_line).to match(/association_generated=1/) expect(total_line).to match(/attribute_generated=1/) end it "groups validations by type" do debug_lines = output.lines.select { |l| l.include?("::debug::") } types = debug_lines.map { |l| l[/kind=(\w+)/, 1] } expect(types).to include("associated") expect(types).to include("custom") end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/spec/modelscope/lib/reports/validations/line_spec.rb
spec/modelscope/lib/reports/validations/line_spec.rb
# frozen_string_literal: true RSpec.describe CallbackHell::Reports::Validations::Line do include_context "test validation callbacks" subject(:report) { described_class.new(validation_callbacks) } subject(:output) { report.generate } it "includes report header" do expect(output).to include("Callback Hell validations report:") end it "shows model name" do expect(output).to include("TestModel:") end it "shows validation types" do expect(output).to include("associated") expect(output).to include("custom") end it "indicates conditional status" do expect(output).to include("conditional: yes") expect(output).to include("conditional: no") end it "indicates inheritance status" do expect(output).to include("inherited: inherited") expect(output).to include("inherited: own") end it "indicates source types" do expect(output).to include("association_generated: yes") expect(output).to include("attribute_generated: yes") end it "formats each validation on a new line" do lines = output.split("\n") validation_lines = lines.select { |l| l.start_with?(" ") } expect(validation_lines.size).to eq(3) end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/spec/internal/app/models/foo.rb
spec/internal/app/models/foo.rb
# frozen_string_literal: true class Foo < ApplicationRecord has_many :bars, dependent: :destroy validates :name, presence: true, uniqueness: true validates :title, presence: true, if: :worthy? before_validation :noop after_validation :noop before_create :noop after_create :noop around_create :noop, if: :createable? normalizes :name, with: -> { _1.strip } if respond_to?(:normalizes) def noop = true def createable? = true def worthy? = true end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/spec/internal/app/models/bar_jr.rb
spec/internal/app/models/bar_jr.rb
# frozen_string_literal: true class BarJr < Bar end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/spec/internal/app/models/application_record.rb
spec/internal/app/models/application_record.rb
# frozen_string_literal: true class ApplicationRecord < ActiveRecord::Base primary_abstract_class end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/spec/internal/app/models/bar.rb
spec/internal/app/models/bar.rb
# frozen_string_literal: true require_relative "../../vendor/gems/acts_as_taggable/acts_as_taggable" class Bar < ApplicationRecord include Annoying include ActsAsTaggable belongs_to :foo, optional: false # for whatever reason, I had to add the optional option validates :name, presence: true after_commit :noop def noop true end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/spec/internal/app/models/concerns/annoying.rb
spec/internal/app/models/concerns/annoying.rb
# frozen_string_literal: true module Annoying extend ActiveSupport::Concern included do after_commit :be_annoying validate :be_annoying end def be_annoying true end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/spec/internal/app/models/bar/baz.rb
spec/internal/app/models/bar/baz.rb
# frozen_string_literal: true class Bar::Baz < ApplicationRecord before_save :noop def noop true end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/spec/internal/vendor/gems/acts_as_taggable/acts_as_taggable.rb
spec/internal/vendor/gems/acts_as_taggable/acts_as_taggable.rb
# frozen_string_literal: true module ActsAsTaggable extend ActiveSupport::Concern included do after_commit :save_tags validate :validate_tags end def save_tags = true def validate_tags = true end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/spec/internal/db/schema.rb
spec/internal/db/schema.rb
# frozen_string_literal: true ActiveRecord::Schema.define do create_table :foos, force: true do |t| t.string :name t.string :title end create_table :bars, force: true do |t| t.references :foo t.string :name end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/spec/internal/config/routes.rb
spec/internal/config/routes.rb
# frozen_string_literal: true Rails.application.routes.draw do # Add your own routes here, or remove this file if you don't have need for it. end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/lib/callback_hell.rb
lib/callback_hell.rb
# frozen_string_literal: true require "zeitwerk" module CallbackHell class Error < StandardError; end def self.loader # @private @loader ||= Zeitwerk::Loader.for_gem.tap do |loader| loader.ignore("#{__dir__}/tasks") loader.setup end end def self.collect_callbacks(*models, **options) collector = Collector.new(**options) collector.collect(models) end def self.collect_validations(*models, **options) collector = Collector.new(**options, kind: :validations) collector.collect(models) end end CallbackHell.loader require "callback_hell/railtie" if defined?(Rails::Railtie)
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/lib/callback_hell/callback.rb
lib/callback_hell/callback.rb
# frozen_string_literal: true module CallbackHell class Callback attr_reader :model, :method_name, :conditional, :origin, :inherited, :kind, :association_generated, :attribute_generated, :callback, :defining_class, :fingerprint def initialize(model:, rails_callback:, name:, defining_class:) @model = model @callback = rails_callback @name = name @defining_class = defining_class analyzer = Analyzers::CallbackAnalyzer.new(@callback, model, defining_class) @kind = @callback.kind @method_name = @callback.filter @conditional = analyzer.conditional? @origin = analyzer.origin @inherited = analyzer.inherited? @association_generated = analyzer.association_generated? @attribute_generated = analyzer.attribute_generated? # fingerprint allows us to de-duplicate callbacks/validations; # in most cases, it's just an object_id, but for named validations/callbacks, # it's a combination of the name, kind and the method_name. # The "0" and "1" prefixes define how to handle duplicates (1 means last write wins, 0 means first write wins) @fingerprint = (@method_name.is_a?(Symbol) && @origin != :rails) ? ["1", @name, @kind, @method_name].join("-") : "0-#{@callback.object_id}" end def callback_group @name.to_s end def validation_type return nil unless callback_group == "validate" Analyzers::ValidationAnalyzer.detect_type(@callback.filter, model) end def human_method_name Analyzers::ValidationAnalyzer.human_method_name(@callback.filter) end def to_s [ "#{model.name}: #{human_method_name}", "kind=#{kind}_#{callback_group}", "origin=#{origin}", inherited ? "inherited=true" : nil, conditional ? "conditional=true" : nil, association_generated ? "association=true" : nil, attribute_generated ? "attribute=true" : nil ].compact.join(" ") end end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/lib/callback_hell/version.rb
lib/callback_hell/version.rb
# frozen_string_literal: true module CallbackHell VERSION = "0.2.1" end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/lib/callback_hell/collector.rb
lib/callback_hell/collector.rb
# frozen_string_literal: true require "set" module CallbackHell class Collector attr_reader :models def initialize(models = nil, paths: nil, kind: :callbacks, mode: :default) @paths = paths @kind = kind @mode = mode eager_load! @models = Set.new(models ? [*models] : ApplicationRecord.descendants) end def collect(select_models = models) select_models.flat_map { |model| collect_for_model(model) } end private def eager_load! Rails.application.eager_load! load_additional_paths end def collect_for_model(model) model.ancestors.select { |ancestor| ancestor < ActiveRecord::Base } # collect from parent to child to correctly handle inheritance .reverse .flat_map { |ancestor| collect_callbacks_for_class(model, ancestor) } .group_by(&:fingerprint) # merge groups .transform_values do |callbacks| probe = callbacks.first if probe.fingerprint.start_with?("1") # we must keep the last non-matching callback (i.e., if all callbacks are the same, # we must keep the first one) callbacks.each do |clbk| if clbk.callback != probe.callback probe = clbk end end end probe end .values end def collect_callbacks_for_class(model, klass) callbacks = klass.__callbacks callbacks = callbacks.slice(:validate) if @kind == :validations callbacks.flat_map do |kind, chain| chain.map { |callback| build_callback(model, callback, kind, klass) } end.then do |collected| next collected if @mode == :full collected.reject do |c| c.association_generated || c.attribute_generated || ( @kind != :validations && c.callback_group == "validate" ) end end end def build_callback(model, callback, kind, klass) Callback.new( model: model, rails_callback: callback, name: kind, defining_class: klass ) end def load_additional_paths model_paths.each do |path| Dir[File.join(path, "**", "*.rb")].sort.each { |file| require_dependency file } end end def model_paths @model_paths ||= begin paths = engine_paths paths += [@paths] if @paths paths.select(&:exist?) end end def engine_paths @engine_paths ||= Rails::Engine.subclasses.map { |engine| engine.root.join("app/models") } end end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/lib/callback_hell/stats.rb
lib/callback_hell/stats.rb
# frozen_string_literal: true module CallbackHell class Stats COUNTERS = %i[ total own inherited rails gems conditional association_generated attribute_generated ].freeze SORT = %i[size name].freeze SORT_ORDER = %i[desc asc].freeze MODE = %i[default full].freeze attr_reader :callbacks private attr_reader :sort_by, :sort_order def initialize(callbacks, sort_by: :size, sort_order: :desc, mode: :default, kind: :callbacks) @callbacks = callbacks @stats_cache = {} @sort_by = sort_by raise ArgumentError, "Invalid sort_by: #{@sort_by}. Available: #{SORT.join(", ")}" unless SORT.include?(@sort_by) @sort_order = sort_order raise ArgumentError, "Invalid sort_order: #{@sort_order}. Available: #{SORT_ORDER.join(", ")}" unless SORT_ORDER.include?(@sort_order) @mode = mode raise ArgumentError, "Invalid mode: #{@mode}. Available: #{MODE.join(", ")}" unless MODE.include?(@mode) @kind = kind end def by_model @by_model ||= callbacks.group_by { |cb| cb.model.name }.sort_by do |name, callbacks| if sort_by == :size callbacks.size elsif sort_by == :name name end end.tap do |sorted| sorted.reverse! if sort_order == :desc end.to_h end def stats_for(model_name) @stats_cache[model_name] ||= begin model_callbacks = by_model[model_name] return {} unless model_callbacks collect_stats(model_callbacks) end end def stats_for_group(model_name, group) key = "#{model_name}_#{group}" @stats_cache[key] ||= begin model_callbacks = by_model[model_name]&.select { |cb| cb.callback_group == group } return {} unless model_callbacks collect_stats(model_callbacks) end end def rails? @mode == :full || @kind == :validations end def associations? @mode == :full end def attributes? @mode == :full end private def collect_stats(callbacks) callbacks.each_with_object(initial_stats) do |cb, stats| stats[:total] += 1 stats[:own] += 1 if cb.origin == :own stats[:inherited] += 1 if cb.inherited stats[:rails] += 1 if cb.origin == :rails stats[:gems] += 1 if cb.origin == :gems stats[:conditional] += 1 if cb.conditional stats[:association_generated] += 1 if cb.association_generated stats[:attribute_generated] += 1 if cb.attribute_generated end end def initial_stats COUNTERS.to_h { |counter| [counter, 0] } end end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/lib/callback_hell/railtie.rb
lib/callback_hell/railtie.rb
# frozen_string_literal: true module CallbackHell class Railtie < ::Rails::Railtie load "tasks/callback_hell.rake" end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/lib/callback_hell/runner.rb
lib/callback_hell/runner.rb
# frozen_string_literal: true module CallbackHell class Runner DEFAULT_FORMAT = :table def self.run(format: DEFAULT_FORMAT, model: nil, paths: nil, kind: :callbacks, **opts) new(format: format, model: model, paths: paths, kind: kind, **opts).run end def initialize(format:, model:, paths:, kind: :callbacks, sort_by: :size, sort_order: :desc, mode: :default) @format = (format || DEFAULT_FORMAT).to_sym @model_name = model @paths = paths @kind = kind @sort_by = sort_by @sort_order = sort_order @mode = mode end def run if @kind == :report [:callbacks, :validations].map do |ckind| generate_report(collect_callbacks(ckind), ckind) end.join("\n\n") else generate_report(collect_callbacks(@kind), @kind) end end private def collect_callbacks(ckind) Collector.new(find_model_class, paths: @paths, kind: ckind, mode: @mode).collect end def generate_report(callbacks, ckind) find_reporter_class(ckind).new( callbacks, sort_by: @sort_by, sort_order: @sort_order, mode: @mode, kind: ckind ).generate end def find_reporter_class(ckind) namespace = ckind.to_s.capitalize format = @format.to_s.capitalize class_name = "CallbackHell::Reports::#{namespace}::#{format}" class_name.constantize rescue NameError raise CallbackHell::Error, "Unknown format: #{@format} for #{ckind}" end def find_model_class return unless @model_name if @model_name.match?(/^[A-Z]/) @model_name.constantize else @model_name.classify.constantize end rescue NameError raise CallbackHell::Error, "Cannot find model: #{@model_name}" end end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/lib/callback_hell/analyzers/validation_analyzer.rb
lib/callback_hell/analyzers/validation_analyzer.rb
# frozen_string_literal: true module CallbackHell module Analyzers class ValidationAnalyzer STANDARD_VALIDATIONS = %w[ presence uniqueness format length inclusion exclusion numericality acceptance confirmation ].freeze STANDARD_VALIDATION_PATTERN = /^validates?_(#{STANDARD_VALIDATIONS.join("|")})(?:_of)?$/ class << self def belongs_to_validator?(filter, model) presence_validator?(filter) && association_attribute?(filter.attributes.first, model, :belongs_to) end def detect_type(filter, model) return nil unless filter if belongs_to_validator?(filter, model) "associated" elsif validator?(filter) validator_type(filter) else normalize_validation_name(filter.to_s) end end def human_method_name(filter) case filter when Proc then format_proc_location(filter) when Class, ActiveModel::Validator then format_validator(filter) else filter.to_s end end private def presence_validator?(filter) filter.is_a?(ActiveRecord::Validations::PresenceValidator) end def association_attribute?(attribute, model, macro) model.reflect_on_association(attribute)&.macro == macro end def validator?(obj) obj.class <= ActiveModel::EachValidator end def validator_type(validator) validator.class.name.demodulize.sub("Validator", "").underscore end def normalize_validation_name(name) case name when STANDARD_VALIDATION_PATTERN, /^validate_(#{STANDARD_VALIDATIONS.join("|")})$/ $1 when /associated_records_for_/ "associated" else "custom" end end def format_proc_location(proc) location = proc.source_location return "Proc (unknown location)" unless location file = location.first.split("/").last(2).join("/") "Proc (#{file}:#{location.last})" end def format_validator(validator) "#{validator.class.name.split("::").last} (#{validator.attributes.join(", ")})" end end end end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/lib/callback_hell/analyzers/callback_analyzer.rb
lib/callback_hell/analyzers/callback_analyzer.rb
# frozen_string_literal: true module CallbackHell module Analyzers class CallbackAnalyzer RAILS_GEMS = %w[ actioncable actionmailbox actionmailer actionpack actiontext actionview activejob activemodel activerecord activestorage activesupport railties ].freeze RAILS_ATTRIBUTE_OWNERS = [ defined?(ActiveRecord::Normalization) && ActiveRecord::Normalization, defined?(ActiveModel::Attributes::Normalization) && ActiveModel::Attributes::Normalization, defined?(ActiveRecord::Encryption::EncryptableRecord) && ActiveRecord::Encryption::EncryptableRecord ].compact.freeze def initialize(callback, model, defining_class) @callback = callback @model = model @defining_class = defining_class @filter = callback.filter end def origin if rails_callback? :rails elsif external_class? :gems elsif !@filter.is_a?(Symbol) :own else external_method?(callback_method) ? :gems : :own end end def inherited? @model != @defining_class end def conditional? [@callback.instance_variable_get(:@if), @callback.instance_variable_get(:@unless)].any? do |condition| next false if condition.nil? [*condition].any? { |c| c.is_a?(Symbol) || c.is_a?(Proc) } end end def association_generated? generated_by_module?("GeneratedAssociationMethods") || from_rails_path?(%r{/active_record/(autosave_association\.rb|associations/builder)}) || ValidationAnalyzer.belongs_to_validator?(@filter, @model) end def attribute_generated? generated_by_module?("GeneratedAttributeMethods") || generated_by_rails_attributes? || from_rails_path?("active_record/attribute_methods/") end private def rails_callback? ValidationAnalyzer.belongs_to_validator?(@filter, @model) || standard_rails_callback? end def standard_rails_callback? case @filter when Symbol, Proc then from_rails_path? else @defining_class == ApplicationRecord end end def callback_owner @callback_owner ||= determine_owner end def determine_owner case @filter when Symbol then callback_method&.owner when Proc then nil when ActiveModel::Validator, ActiveModel::EachValidator then @defining_class else @filter.class end end def callback_method return nil unless @filter.is_a?(Symbol) || @filter.is_a?(String) @callback_method ||= begin @model.instance_method(@filter) rescue nil end end def source_location @source_location ||= case @filter when Symbol, String then callback_method&.source_location&.first when Proc then @filter.source_location&.first end.to_s end def external_class? @defining_class != @model && !@model.ancestors.include?(@defining_class) end def external_method?(method) return false unless method source = method.source_location&.first.to_s !from_app_path?(source) end def from_app_path?(path) path.start_with?(Rails.root.to_s) && !path.start_with?(Rails.root.join("vendor").to_s) end def generated_by_module?(suffix) callback_method&.owner&.name&.end_with?("::" + suffix) || false end def generated_by_rails_attributes? method = callback_method return false unless method RAILS_ATTRIBUTE_OWNERS.include?(method.owner) end def from_rails_path?(subpath = nil) return false if source_location.empty? rails_paths.any? do |rails_path| case subpath when String source_location.include?("/#{subpath}") when Regexp source_location.match?(subpath) else source_location.include?(rails_path) end end end def rails_paths @rails_paths ||= RAILS_GEMS.map { |name| Gem::Specification.find_by_name(name).full_gem_path } end def rails_module?(mod) mod.name&.start_with?("ActiveRecord::", "ActiveModel::") end def validator?(obj) obj.is_a?(ActiveModel::Validator) end end end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/lib/callback_hell/reports/line_base.rb
lib/callback_hell/reports/line_base.rb
# frozen_string_literal: true module CallbackHell module Reports class LineBase < Base def generate output = [report_title] @stats.by_model.each do |model_name, model_callbacks| output << "\n#{model_name}:" model_callbacks.sort_by(&:kind).each do |callback| output << format_callback(callback) end end output.join("\n") end private def report_title raise NotImplementedError end def format_callback(callback) [ " #{format_callback_name(callback)}", "method_name: #{callback.human_method_name}", "origin: #{callback.origin}", "association_generated: #{callback.association_generated ? "yes" : "no"}", "attribute_generated: #{callback.attribute_generated ? "yes" : "no"}", "inherited: #{callback.inherited ? "inherited" : "own"}", "conditional: #{callback.conditional ? "yes" : "no"}" ].compact.join(", ") end def format_callback_name(callback) raise NotImplementedError end end end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/lib/callback_hell/reports/github_base.rb
lib/callback_hell/reports/github_base.rb
# frozen_string_literal: true module CallbackHell module Reports class GithubBase < Base def generate output = ["::group::#{report_title}"] @stats.by_model.each_with_index do |(model_name, _), index| output << "" if index > 0 output << "::group::#{model_name}" # Add total row first total_stats = @stats.stats_for(model_name) output << format_group( "all", total_stats[:total], total_stats[:own], total_stats[:inherited], total_stats[:rails], total_stats[:association_generated], total_stats[:attribute_generated], total_stats[:gems], total_stats[:conditional] ) # Group and sort callbacks grouped_callbacks = @stats.by_model[model_name].group_by { |cb| format_group_name(cb) } grouped_callbacks.keys.sort.each do |group_name| group_callbacks = grouped_callbacks[group_name] output << format_group( group_name, group_callbacks.size, group_callbacks.count { |cb| cb.origin == :own }, group_callbacks.count(&:inherited), group_callbacks.count { |cb| cb.origin == :rails }, group_callbacks.count(&:association_generated), group_callbacks.count(&:attribute_generated), group_callbacks.count { |cb| cb.origin == :gems }, group_callbacks.count(&:conditional) ) end output << "::endgroup::" end output << "::endgroup::" output.join("\n") end private def report_title raise NotImplementedError end def format_group(name, total, own, inherited, rails, association_generated, attribute_generated, gems, conditional) "::debug::kind=#{name} total=#{total} own=#{own} inherited=#{inherited} rails=#{rails} association_generated=#{association_generated} attribute_generated=#{attribute_generated} gems=#{gems} conditional=#{conditional}" end def format_group_name(callback) raise NotImplementedError end end end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/lib/callback_hell/reports/base.rb
lib/callback_hell/reports/base.rb
# frozen_string_literal: true module CallbackHell module Reports class Base attr_reader :callbacks, :stats def initialize(callbacks, **opts) @callbacks = callbacks @stats = Stats.new(callbacks, **opts) end def generate raise NotImplementedError end end end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/lib/callback_hell/reports/table_base.rb
lib/callback_hell/reports/table_base.rb
# frozen_string_literal: true require "table_tennis" module CallbackHell module Reports class TableBase < Base def generate headers = ["Model", "Kind", "Total", "Own", "Inherited"] headers << "Rails" if stats.rails? headers << "Associations" if stats.associations? headers << "Attributes" if stats.attributes? headers.concat(["Gems", "Conditional"]) headers_mapping = headers.index_by { |h| h.parameterize.to_sym } table = TableTennis.new(generate_rows(headers_mapping.keys)) do |t| t.title = report_title t.headers = headers_mapping t.placeholder = "" t.color_scales = {total: :gr} # Don't shrink table if we run in a test environment, # we need full labels and values to test t.layout = false if defined?(Rails) && Rails.env.test? end table.to_s end private def report_title raise NotImplementedError end def generate_rows(headers) rows = [] @stats.by_model.each_with_index do |(model_name, _), index| # TODO: not supported by table_tennis # rows << :separator if index > 0 rows.concat(model_rows(model_name)) end rows.map { headers.zip(_1).to_h } end def model_rows(model_name) rows = [] total_stats = @stats.stats_for(model_name) # Add total row rows << [ model_name, "all", total_stats[:total], total_stats[:own], total_stats[:inherited], stats.rails? ? total_stats[:rails] : nil, stats.associations? ? total_stats[:association_generated] : nil, stats.attributes? ? total_stats[:attribute_generated] : nil, total_stats[:gems], total_stats[:conditional] ].compact # Group and sort callbacks grouped_callbacks = @stats.by_model[model_name].group_by { |cb| format_group_name(cb) } grouped_callbacks.keys.sort.each do |group_name| group_callbacks = grouped_callbacks[group_name] rows << [ "", group_name, group_callbacks.size, group_callbacks.count { |cb| cb.origin == :own }, group_callbacks.count(&:inherited), stats.rails? ? group_callbacks.count { |cb| cb.origin == :rails } : nil, stats.associations? ? group_callbacks.count(&:association_generated) : nil, stats.attributes? ? group_callbacks.count(&:attribute_generated) : nil, group_callbacks.count { |cb| cb.origin == :gems }, group_callbacks.count(&:conditional) ].compact end rows end def format_group_name(callback) raise NotImplementedError end end end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false
evilmartians/callback_hell
https://github.com/evilmartians/callback_hell/blob/558adc85e0de09dd7479336c74add51ddeff0c6c/lib/callback_hell/reports/callbacks/table.rb
lib/callback_hell/reports/callbacks/table.rb
# frozen_string_literal: true module CallbackHell module Reports module Callbacks class Table < TableBase private def report_title "Callback Hell callbacks report" end def format_group_name(callback) "#{timing_symbol(callback.kind)}/#{callback.callback_group}" end def timing_symbol(timing) case timing when :before, "before" then "⇥" when :after, "after" then "↦" when :around, "around" then "↔" else " " end end end end end end
ruby
MIT
558adc85e0de09dd7479336c74add51ddeff0c6c
2026-01-04T17:45:07.140490Z
false