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 |
|---|---|---|---|---|---|---|---|---|
estebanz01/ruby-statistics | https://github.com/estebanz01/ruby-statistics/blob/0ac388ab734120bd708164a10261b25b53faf29d/spec/ruby-statistics/distribution/bernoulli_spec.rb | spec/ruby-statistics/distribution/bernoulli_spec.rb | require 'spec_helper'
describe RubyStatistics::Distribution::Bernoulli do
describe '.density_function' do
it 'is not defined when the outcome is different from zero or one' do
expect(described_class.density_function(rand(2..10), rand)).to be_nil
expect(described_class.density_function(rand(-5..-1), rand)).to be_nil
end
it 'returns the expected value when the outcome is zero' do
p = rand
expect(described_class.density_function(0, p)).to eq (1.0 - p)
end
it 'returns the expected value when the outcome is one' do
p = rand
expect(described_class.density_function(1, p)).to eq p
end
end
describe '.cumulative_function' do
it 'is not defined when the outcome is different from zero or one' do
expect(described_class.cumulative_function(rand(2..10), rand)).to be_nil
expect(described_class.density_function(rand(-5..-1), rand)).to be_nil
end
it 'returns the expected value when the outcome is zero' do
p = rand
expect(described_class.cumulative_function(0, p)).to eq (1.0 - p)
end
it 'returns the expected value when the outcome is one' do
expect(described_class.cumulative_function(1, rand)).to eq 1.0
end
end
describe '.variance' do
it 'returns the expected value for the bernoulli distribution' do
p = rand
expect(described_class.variance(p)).to eq p * (1.0 - p)
end
end
describe '.skewness' do
it 'returns the expected value for the bernoulli distribution' do
p = rand
expected_value = (1.0 - 2.0*p).to_f / Math.sqrt(p * (1.0 - p))
expect(described_class.skewness(p)).to eq expected_value
end
end
describe '.kurtosis' do
it 'returns the expected value for the bernoulli distribution' do
p = rand
expected_value = (6.0 * (p ** 2) - (6 * p) + 1) / (p * (1.0 - p))
expect(described_class.kurtosis(p)).to eq expected_value
end
end
end
| ruby | MIT | 0ac388ab734120bd708164a10261b25b53faf29d | 2026-01-04T17:46:01.529291Z | false |
estebanz01/ruby-statistics | https://github.com/estebanz01/ruby-statistics/blob/0ac388ab734120bd708164a10261b25b53faf29d/spec/ruby-statistics/distribution/negative_binomial_spec.rb | spec/ruby-statistics/distribution/negative_binomial_spec.rb | require 'spec_helper'
describe RubyStatistics::Distribution::NegativeBinomial do
describe '#probability_mass_function' do
it 'is not defined for negative values' do
expect(described_class.new(0, 0).probability_mass_function(rand(-10...0))).to be_nil
end
it 'is not defined for values greater than the number of defined failures before success' do
k = rand(10)
p = rand
expect(described_class.new(k, p).probability_mass_function(k + 1)).to be_nil
end
it 'returns the expected results for the negative binomial distribution' do
# Results from R:
# dnbinom(c(1,2,3,4,5), size = 10, prob = 0.5)
# [1] 0.004882812 0.013427734 0.026855469 0.043640137 0.061096191
results = [0.00488281, 0.01342773, 0.02685547, 0.04364014, 0.06109619]
binomial = described_class.new(10, 0.5) # Number of failures: 10, probability per trial: 0.5
(1..5).each_with_index do |number, index|
expect(binomial.probability_mass_function(number)).to be_within(0.00000001).of(results[index])
end
end
end
describe '#cumulative_function' do
it 'is not defined for negative values' do
expect(described_class.new(0, 0).cumulative_function(rand(-10...0))).to be_nil
end
it 'is not defined for values greater than the number of defined failures before success' do
k = rand(10)
p = rand
expect(described_class.new(k, p).cumulative_function(k + 1)).to be_nil
end
it 'returns the expected results for the negative binomial distribution' do
# Results from R:
# pnbinom(c(1,2,3,4,5), size = 10, prob = 0.5)
# [1] 0.005859375 0.019287109 0.046142578 0.089782715 0.150878906
results = [0.005859375, 0.019287109, 0.046142578, 0.089782715, 0.150878906]
binomial = described_class.new(10, 0.5) # Number of trials: 10, probability per trial: 0.5
(1..5).each_with_index do |number, index|
expect(binomial.cumulative_function(number)).to be_within(0.000000001).of(results[index])
end
end
end
describe '#mean' do
it 'returns the expected mean for the specified values' do
n = rand(10)
p = rand
expect(described_class.new(n, p).mean).to eq (p * n)/(1 - p).to_f
end
end
describe '#variance' do
it 'returns the expected variance for the specified values' do
n = rand(10)
p = rand
expect(described_class.new(n, p).variance).to eq (p * n)/((1 - p) ** 2).to_f
end
end
describe '#mode' do
it 'returns 0.0 if the number of failures before a success is less or equal than one' do
n = rand(-10..1)
p = rand
expect(described_class.new(n, p).mode).to eq 0.0
end
it 'calculates the mode if the number of failures before a success is greather than one' do
n = 2 + rand(10)
p = rand
expect(described_class.new(n, p).mode).to eq ((p * (n - 1))/(1 - p).to_f).floor
end
end
describe '#skewness' do
it 'calculates the skewness for the negative binomial distribution' do
n = rand(10)
p = rand
expect(described_class.new(n, p).skewness).to eq ((1 + p).to_f / Math.sqrt(p * n))
end
end
end
| ruby | MIT | 0ac388ab734120bd708164a10261b25b53faf29d | 2026-01-04T17:46:01.529291Z | false |
estebanz01/ruby-statistics | https://github.com/estebanz01/ruby-statistics/blob/0ac388ab734120bd708164a10261b25b53faf29d/spec/ruby-statistics/distribution/chi_squared_spec.rb | spec/ruby-statistics/distribution/chi_squared_spec.rb | require 'spec_helper'
describe RubyStatistics::Distribution::ChiSquared do
describe '#cumulative_function' do
it 'returns the expected probabilities for the chi-squared distribution' do
results = [0.0374, 0.1509, 0.3, 0.4506, 0.5841]
chi_sq = described_class.new(5) # 5 degrees of freedom
(1..5).each_with_index do |number, index|
expect(chi_sq.cumulative_function(number)).to be_within(0.0001).of(results[index])
end
end
context 'With degrees of freedom from 1 to 30' do
it 'returns the expected probabilities for the chi-squared distribution compared to a table' do
# Values retrieved from the following table provided by the University of Arizona.
# https://math.arizona.edu/~jwatkins/chi-square-table.pdf
alpha = 0.100
# Each index represents the degrees of freedom
values = [
2.706, 4.605, 6.251, 7.779, 9.236, 10.645, 12.017, 13.362, 14.684, 15.987, 17.275,
18.549, 19.812, 21.064, 22.307, 23.542, 24.769, 25.989, 27.204, 28.412, 29.615,
30.813, 32.007, 33.196, 34.382, 35.563, 36.741, 37.916, 39.087, 40.256
]
values.each_with_index do |p, index|
result = 1.0 - described_class.new(index + 1).cumulative_function(p)
expect(result).to be_within(0.0001).of(alpha)
end
end
end
context 'With degrees of freedom from 40 to 100, with a 10 unit increment' do
it 'returns the expected probabilities for the chi-squared distribution compared to a table' do
# Values retrieved from the following table provided by the University of Arizona.
# https://math.arizona.edu/~jwatkins/chi-square-table.pdf
alpha = 0.100
# Each index represents the degrees of freedom
values = [51.805, 63.167, 74.397, 85.527, 96.578, 107.565, 118.498]
values.each_with_index do |p, index|
df = (index + 1) * 10 + 30 # we start on 40
result = 1.0 - described_class.new(df).cumulative_function(p)
expect(result).to be_within(0.0001).of(alpha)
end
end
end
context 'when the degrees of freedom is 2 for the chi-squared distribution' do
it 'performs the probability calculation using the special case instead' do
# Results gathered from R 4.0.3
# # > pchisq(1:10, df = 2)
# # [1] 0.3935 0.6321 0.7769 0.8647 0.9179 0.9502 0.9698 0.9817 0.9889 0.9933
results = [0.3935, 0.6321, 0.7769, 0.8647, 0.9179, 0.9502, 0.9698, 0.9817, 0.9889, 0.9933]
chi_sq = described_class.new(2)
(1..10).each_with_index do |number, index|
expect(chi_sq.cumulative_function(number)).to be_within(0.0001).of(results[index])
end
end
end
end
describe '#density_function' do
it' returns zero when the specified value is not defined in the chi-squared support domain' do
expect(described_class.new(rand(1..10)).density_function(rand(-5..-1))).to eq 0
end
it 'calculates the expected value for the chi-squared distribution' do
result = [0.242, 0.1038, 0.0514, 0.027, 0.0146]
(1..5).each_with_index do |number, index|
chi_sq = described_class.new(1) # 1 degree freedom
expect(chi_sq.density_function(number)).to be_within(0.0001).of(result[index])
end
end
end
describe '#mode' do
it 'returns the specific mode for the chi-squared distribution' do
(1..10).each do |k|
chi_sq = described_class.new(k)
expect(chi_sq.mode).to eq [k - 2, 0].max
end
end
end
describe '#variance' do
it 'returns the specific variance for the chi-squared distribution' do
(1..10).each do |k|
chi_sq = described_class.new(k)
expect(chi_sq.variance).to eq (2 * k)
end
end
end
end
| ruby | MIT | 0ac388ab734120bd708164a10261b25b53faf29d | 2026-01-04T17:46:01.529291Z | false |
estebanz01/ruby-statistics | https://github.com/estebanz01/ruby-statistics/blob/0ac388ab734120bd708164a10261b25b53faf29d/spec/ruby-statistics/distribution/t_student_spec.rb | spec/ruby-statistics/distribution/t_student_spec.rb | require 'spec_helper'
describe RubyStatistics::Distribution::TStudent do
describe '#cumulative_function' do
it 'returns the expected values for the T-Student distribution' do
results = [0.7886751, 0.9082483, 0.9522670, 0.9714045, 0.9811252]
t_student = described_class.new(2) # degrees of freedom: 2
(1..5).each_with_index do |number, index|
expect(t_student.cumulative_function(number)).to be_within(0.0000001).of(results[index])
end
end
end
describe '#density_function' do
it 'is not defined for degrees of freedom less or equal to zero' do
expect(described_class.new(rand(-5..0)).density_function(rand(10))).to be_nil
end
it 'returns the expected values for the T-Student distribution' do
results = [0.2196798, 0.065090310, 0.01729258, 0.00512373, 0.00175744]
(1..5).each_with_index do |number, index|
t_student = described_class.new(5) # degrees of freedom: 5
expect(t_student.density_function(number)).to be_within(0.00000001).of(results[index])
end
end
end
describe '#mean' do
it 'returns zero if the degrees of freedom is greater than one' do
expect(described_class.new(rand(2..10)).mean).to eq 0
end
it 'is not defined for degrees of freedom lesser or equal to one' do
expect(described_class.new(rand(-5..1)).mean).to be_nil
end
end
describe '#variance' do
it 'returns the expected value for degrees of freedom greater than two' do
v = rand(3..10)
expected_variance = v/(v - 2.0)
expect(described_class.new(v).variance).to eq expected_variance
end
it 'returns infinity for 1 < degrees of freedom <= 2' do
v = rand((1.0001)..2) # Awful but true
expect(described_class.new(v).variance).to eq Float::INFINITY
end
it 'is not defined for other values' do
v = rand(-10..1)
expect(described_class.new(v).variance).to be_nil
end
end
describe '#random' do
it 'generates a random number that follows a student-t distribution' do
# T sample elements generated in R with degrees of freedom 4 and seed 100
t_sample = [-0.55033048, -0.06690434, 0.11951965, -0.52008245, -1.11703451]
random_sample = described_class.new(4).random(elements: 5, seed: 100)
test = RubyStatistics::StatisticalTest::ChiSquaredTest.goodness_of_fit(0.01, t_sample, random_sample)
expect(test[:null]).to be true
expect(test[:alternative]).to be false
end
it 'does not generate a random sample that follows an uniform distribution' do
pending 'random sample follows an uniform and t-student distribution'
# Uniform sample elements generated in R with seed 100
uniform_sample = [0.30776611, 0.25767250, 0.55232243, 0.05638315, 0.46854928]
random_sample = described_class.new(4).random(elements: 5, seed: 100)
test = RubyStatistics::StatisticalTest::ChiSquaredTest.goodness_of_fit(0.01, uniform_sample, random_sample)
expect(test[:null]).to be false
expect(test[:alternative]).to be true
end
end
end
| ruby | MIT | 0ac388ab734120bd708164a10261b25b53faf29d | 2026-01-04T17:46:01.529291Z | false |
estebanz01/ruby-statistics | https://github.com/estebanz01/ruby-statistics/blob/0ac388ab734120bd708164a10261b25b53faf29d/spec/ruby-statistics/distribution/empirical_spec.rb | spec/ruby-statistics/distribution/empirical_spec.rb | require 'spec_helper'
describe RubyStatistics::Distribution::Empirical do
describe '#cumulative_function' do
it 'calculates the CDF for the specified value using a group of samples' do
# Result in R
# > cdf <- ecdf(c(1,2,3,4,5,6,7,8,9,0))
# > cdf(7)
# [1] 0.8
samples = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
x = 7
x_prob = 0.8
expect(described_class.new(samples: samples).cumulative_function(x: x)).to eq x_prob
end
end
end
| ruby | MIT | 0ac388ab734120bd708164a10261b25b53faf29d | 2026-01-04T17:46:01.529291Z | false |
estebanz01/ruby-statistics | https://github.com/estebanz01/ruby-statistics/blob/0ac388ab734120bd708164a10261b25b53faf29d/spec/ruby-statistics/distribution/normal_spec.rb | spec/ruby-statistics/distribution/normal_spec.rb | require 'spec_helper'
describe RubyStatistics::Distribution::Normal do
describe '#cumulative_function' do
it 'returns the expected probabilites for the normal distribution' do
results = [0.3445783, 0.4207403, 0.5000000, 0.5792597, 0.6554217]
normal = described_class.new(3, 5) # mean 3, std 5
(1..5).each_with_index do |number, index|
expect(normal.cumulative_function(number)).to be_within(0.0000001).of(results[index])
end
end
end
describe '#density_function' do
it 'returns the expected values for the normal distribution' do
# TODO: Find a better way to test this.
results = [0.0737, 0.0782, 0.0798, 0.0782, 0.0737]
(1..5).each_with_index do |number, index|
normal_distribution = described_class.new(3, 5) # mean = 3, std = 5
expect(normal_distribution.density_function(number)).to be_within(0.0001).of(results[index])
end
end
end
# To test random generation, we are going to use the Goodness-of-fit test
# to validate if a sample fits a normal distribution.
describe '#random' do
it 'returns a pseudo random number that belongs to a normal distribution' do
# Normal sample generated from R with mean 5, std 2.0 and seed 100
alpha = 0.01
normal_sample = [3.995615, 5.263062, 4.842166, 6.773570, 5.233943]
random_sample = described_class.new(5.0, 2.0).random(elements: 5, seed: 100)
test = RubyStatistics::StatisticalTest::ChiSquaredTest.goodness_of_fit(alpha, normal_sample, random_sample)
# Null hypothesis: Both samples belongs to the same distribution (normal in this case)
# Alternative hypotesis: Each sample is generated with a different distribution.
expect(test[:null]).to be true
expect(test[:alternative]).to be false
end
it 'does not generate a random sample that follows an uniform distribution' do
# Uniform sample elements generated in R with seed 100
uniform_sample = [0.30776611, 0.25767250, 0.55232243, 0.05638315, 0.46854928]
random_sample = described_class.new(5.0, 2.0).random(elements: 5, seed: 100)
test = RubyStatistics::StatisticalTest::ChiSquaredTest.goodness_of_fit(0.01, uniform_sample, random_sample)
expect(test[:null]).to be false
expect(test[:alternative]).to be true
end
it 'generates the specified number of random elements and store it into an array' do
elements = rand(2..5)
sample = described_class.new(5.0, 2.0).random(elements: elements)
expect(sample).to be_a Array
expect(sample.size).to eq elements
end
it 'returns a single random number when only one element is required' do
normal = described_class.new(5.0, 2.0)
sample_1 = normal.random # 1 element by default
sample_2 = normal.random(elements: 1)
expect(sample_1).to be_a Numeric
expect(sample_2).to be_a Numeric
end
end
end
describe RubyStatistics::Distribution::StandardNormal do
describe '#cumulative_function' do
it 'returns the expected probabilities for the standard normal distribution' do
results = [0.8413447, 0.9772499, 0.9986501, 0.9999683, 0.9999997]
standard = described_class.new
(1..5).each_with_index do |number, index|
expect(standard.cumulative_function(number)).to be_within(0.0000001).of(results[index])
end
end
end
describe '#density_function' do
it 'returns the expected values for the standard normal distribution with mean = 0, std = 1' do
results = [0.24197, 0.05399, 0.00443, 0.00013, 0.00000]
(1..5).each_with_index do |number, index|
standard_distribution = described_class.new
expect(standard_distribution.density_function(number)).to be_within(0.00001).of(results[index])
end
end
end
end
describe RubyStatistics::Distribution::InverseStandardNormal do
let(:standard_inverse_distribution) { described_class.new }
describe '#cumulative_function' do
it 'returns the expected probabilities for the standard normal inverse distribution' do
# results have been taken here https://www.excelfunctions.net/excel-normsinv-function.html
expect(standard_inverse_distribution.cumulative_function(-0.0000001)).to be_nil
expect(standard_inverse_distribution.cumulative_function(0)).to eq -Float::INFINITY
expect(standard_inverse_distribution.cumulative_function(0.25)).to eq -0.6744897502234195
expect(standard_inverse_distribution.cumulative_function(0.356245)).to eq -0.3685140105744644
expect(standard_inverse_distribution.cumulative_function(0.55)).to eq 0.12566134687610314
expect(standard_inverse_distribution.cumulative_function(0.69865437)).to eq 0.520534254262422
expect(standard_inverse_distribution.cumulative_function(0.9)).to eq 1.281551564140072
expect(standard_inverse_distribution.cumulative_function(0.98)).to eq 2.0537489090030308
expect(standard_inverse_distribution.cumulative_function(1)).to eq Float::INFINITY
expect(standard_inverse_distribution.cumulative_function(1.0000001)).to be_nil
end
end
describe '#density_function' do
let(:value) { 0.25 }
subject { described_class.new.density_function(value) }
it 'is not implemented' do
expect { subject }.to raise_error NotImplementedError
end
end
describe '#random' do
let(:value) { 0.25 }
subject { described_class.new.random(elements: value, seed: Random.new_seed) }
it 'is not implemented' do
expect { subject }.to raise_error NotImplementedError
end
end
end
| ruby | MIT | 0ac388ab734120bd708164a10261b25b53faf29d | 2026-01-04T17:46:01.529291Z | false |
estebanz01/ruby-statistics | https://github.com/estebanz01/ruby-statistics/blob/0ac388ab734120bd708164a10261b25b53faf29d/lib/ruby-statistics.rb | lib/ruby-statistics.rb | require File.dirname(__FILE__) + '/enumerable'
require File.dirname(__FILE__) + '/math'
Dir[ File.dirname(__FILE__) + '/ruby-statistics/**/*.rb'].each {|file| require file }
module RubyStatistics
# Your code goes here...
end
| ruby | MIT | 0ac388ab734120bd708164a10261b25b53faf29d | 2026-01-04T17:46:01.529291Z | false |
estebanz01/ruby-statistics | https://github.com/estebanz01/ruby-statistics/blob/0ac388ab734120bd708164a10261b25b53faf29d/lib/math.rb | lib/math.rb | module Math
def self.factorial(n)
return if n < 0
n = n.to_i # Only integers.
return 1 if n == 0 || n == 1
Math.gamma(n + 1) # Math.gamma(x) == (n - 1)! for integer values
end
def self.combination(n, r)
self.factorial(n)/(self.factorial(r) * self.factorial(n - r)).to_r # n!/(r! * [n - r]!)
end
def self.permutation(n, k)
self.factorial(n)/self.factorial(n - k).to_r
end
# Function adapted from the python implementation that exists in https://en.wikipedia.org/wiki/Simpson%27s_rule#Sample_implementation
# Finite integral in the interval [a, b] split up in n-intervals
def self.simpson_rule(a, b, n, &block)
unless n.even?
puts "The composite simpson's rule needs even intervals!"
return
end
h = (b - a)/n.to_r
resA = yield(a)
resB = yield(b)
sum = resA + resB
(1..n).step(2).each do |number|
res = yield(a + number * h)
sum += 4 * res
end
(1..(n-1)).step(2).each do |number|
res = yield(a + number * h)
sum += 2 * res
end
return sum * h / 3.0
end
def self.lower_incomplete_gamma_function(s, x)
base_iterator = x.round(1)
base_iterator += 1 if x < 1.0 && !x.zero?
# The greater the iterations, the better. That's why we are iterating 10_000 * x times
iterator = (10_000 * base_iterator).round
iterator = 100_000 if iterator.zero?
self.simpson_rule(0, x.to_r, iterator) do |t|
(t ** (s - 1)) * Math.exp(-t)
end
end
# Algorithm implementation translated from the ASA147 C++ version https://people.sc.fsu.edu/~jburkardt/cpp_src/asa147/asa147.html
# translated from FORTRAN by John Burkardt. Original algorithm written by Chi Leung Lau.
# It contains a modification on the error and underflow parameters to use maximum available float number
# and it performs the series using `Rational` objects to avoid memory exhaustion and reducing precision errors.
#
# This algorithm is licensed with MIT license.
#
# Reference:
#
# Chi Leung Lau,
# Algorithm AS 147:
# A Simple Series for the Incomplete Gamma Integral,
# Applied Statistics,
# Volume 29, Number 1, 1980, pages 113-114.
def self.normalised_lower_incomplete_gamma_function(s, x)
return 0.0 if s.negative? || x.zero? || x.negative?
# e = 1.0e-308
# uflo = 1.0e-47
e = Float::MIN
uflo = Float::MIN
lgamma, sign = Math.lgamma(s + 1.0)
arg = s * Math.log(x) - (sign * lgamma) - x
return 0.0 if arg < Math.log(uflo)
f = Math.exp(arg).to_r
return 0.0 if f.zero?
c = 1r
value = 1r
a = s.to_r
rational_x = x.to_r
loop do
a += 1r
c = c * (rational_x / a)
value += c
break if c <= (e * value)
end
(value * f).to_f
end
def self.beta_function(x, y)
return 1 if x == 1 && y == 1
(Math.gamma(x) * Math.gamma(y))/Math.gamma(x + y)
end
### This implementation is an adaptation of the incomplete beta function made in C by
### Lewis Van Winkle, which released the code under the zlib license.
### The whole math behind this code is described in the following post: https://codeplea.com/incomplete-beta-function-c
def self.incomplete_beta_function(x, alp, bet)
return if x < 0.0
return 1.0 if x > 1.0
tiny = 1.0E-50
if x > ((alp + 1.0)/(alp + bet + 2.0))
return 1.0 - self.incomplete_beta_function(1.0 - x, bet, alp)
end
# To avoid overflow problems, the implementation applies the logarithm properties
# to calculate in a faster and safer way the values.
lbet_ab = (Math.lgamma(alp)[0] + Math.lgamma(bet)[0] - Math.lgamma(alp + bet)[0]).freeze
front = (Math.exp(Math.log(x) * alp + Math.log(1.0 - x) * bet - lbet_ab) / alp.to_r).freeze
# This is the non-log version of the left part of the formula (before the continuous fraction)
# down_left = alp * self.beta_function(alp, bet)
# upper_left = (x ** alp) * ((1.0 - x) ** bet)
# front = upper_left/down_left
f, c, d = 1.0, 1.0, 0.0
returned_value = nil
# Let's do more iterations than the proposed implementation (200 iters)
(0..500).each do |number|
m = number/2
numerator = if number == 0
1.0
elsif number % 2 == 0
(m * (bet - m) * x)/((alp + 2.0 * m - 1.0)* (alp + 2.0 * m))
else
top = -((alp + m) * (alp + bet + m) * x)
down = ((alp + 2.0 * m) * (alp + 2.0 * m + 1.0))
top/down
end
d = 1.0 + numerator * d
d = tiny if d.abs < tiny
d = 1.0 / d.to_r
c = 1.0 + numerator / c.to_r
c = tiny if c.abs < tiny
cd = (c*d).freeze
f = f * cd
if (1.0 - cd).abs < 1.0E-10
returned_value = front * (f - 1.0)
break
end
end
returned_value
end
end
| ruby | MIT | 0ac388ab734120bd708164a10261b25b53faf29d | 2026-01-04T17:46:01.529291Z | false |
estebanz01/ruby-statistics | https://github.com/estebanz01/ruby-statistics/blob/0ac388ab734120bd708164a10261b25b53faf29d/lib/enumerable.rb | lib/enumerable.rb | # TODO: Avoid monkey-patching.
module Enumerable
def mean
self.reduce(:+) / self.length.to_f
end
def variance
mean = self.mean
self.reduce(0) { |memo, value| memo + ((value - mean) ** 2) } / (self.length - 1).to_f
end
def standard_deviation
Math.sqrt(self.variance)
end
end
| ruby | MIT | 0ac388ab734120bd708164a10261b25b53faf29d | 2026-01-04T17:46:01.529291Z | false |
estebanz01/ruby-statistics | https://github.com/estebanz01/ruby-statistics/blob/0ac388ab734120bd708164a10261b25b53faf29d/lib/ruby-statistics/version.rb | lib/ruby-statistics/version.rb | module RubyStatistics
VERSION = "4.1.0"
end
| ruby | MIT | 0ac388ab734120bd708164a10261b25b53faf29d | 2026-01-04T17:46:01.529291Z | false |
estebanz01/ruby-statistics | https://github.com/estebanz01/ruby-statistics/blob/0ac388ab734120bd708164a10261b25b53faf29d/lib/ruby-statistics/distribution.rb | lib/ruby-statistics/distribution.rb | Dir[File.dirname(__FILE__) + '/distribution/**/*.rb'].each {|file| require file }
module RubyStatistics
module Distribution
end
end
| ruby | MIT | 0ac388ab734120bd708164a10261b25b53faf29d | 2026-01-04T17:46:01.529291Z | false |
estebanz01/ruby-statistics | https://github.com/estebanz01/ruby-statistics/blob/0ac388ab734120bd708164a10261b25b53faf29d/lib/ruby-statistics/statistical_test.rb | lib/ruby-statistics/statistical_test.rb | Dir[File.dirname(__FILE__) + '/statistical_test/**/*.rb'].each {|file| require file }
module RubyStatistics
module StatisticalTest
end
end
# If StatisticalTest is not defined, setup alias.
if defined?(RubyStatistics) && !(defined?(StatisticalTest))
StatisticalTest = RubyStatistics::StatisticalTest
end
| ruby | MIT | 0ac388ab734120bd708164a10261b25b53faf29d | 2026-01-04T17:46:01.529291Z | false |
estebanz01/ruby-statistics | https://github.com/estebanz01/ruby-statistics/blob/0ac388ab734120bd708164a10261b25b53faf29d/lib/ruby-statistics/spearman_rank_coefficient.rb | lib/ruby-statistics/spearman_rank_coefficient.rb | module RubyStatistics
class SpearmanRankCoefficient
def self.rank(data:, return_ranks_only: true)
descending_order_data = data.sort { |a, b| b <=> a }
rankings = {}
data.each do |value|
# If we have ties, the find_index method will only retrieve the index of the
# first element in the list (i.e, the most close to the left of the array),
# so when a tie is detected, we increase the temporal ranking by the number of
# counted elements at that particular time and then we increase the counter.
temporal_ranking = descending_order_data.find_index(value) + 1 # 0-index
if rankings.fetch(value, false)
rankings[value][:rank] += (temporal_ranking + rankings[value][:counter])
rankings[value][:counter] += 1
rankings[value][:tie_rank] = rankings[value][:rank] / rankings[value][:counter].to_r
else
rankings[value] = { counter: 1, rank: temporal_ranking, tie_rank: temporal_ranking }
end
end
if return_ranks_only
data.map do |value|
rankings[value][:tie_rank]
end
else
rankings
end
end
# Formulas extracted from: https://statistics.laerd.com/statistical-guides/spearmans-rank-order-correlation-statistical-guide.php
def self.coefficient(set_one, set_two)
raise 'Both group sets must have the same number of cases.' if set_one.size != set_two.size
return if set_one.size == 0 && set_two.size == 0
set_one_mean, set_two_mean = set_one.mean, set_two.mean
have_tie_ranks = (set_one + set_two).any? { |rank| rank.is_a?(Float) || rank.is_a?(Rational) }
if have_tie_ranks
numerator = 0
squared_differences_set_one = 0
squared_differences_set_two = 0
set_one.size.times do |idx|
local_diff_one = (set_one[idx] - set_one_mean)
local_diff_two = (set_two[idx] - set_two_mean)
squared_differences_set_one += local_diff_one ** 2
squared_differences_set_two += local_diff_two ** 2
numerator += local_diff_one * local_diff_two
end
denominator = Math.sqrt(squared_differences_set_one * squared_differences_set_two)
numerator / denominator.to_r # This is rho or spearman's coefficient.
else
sum_squared_differences = set_one.each_with_index.reduce(0) do |memo, (rank_one, index)|
memo += ((rank_one - set_two[index]) ** 2)
memo
end
numerator = 6 * sum_squared_differences
denominator = ((set_one.size ** 3) - set_one.size)
1.0 - (numerator / denominator.to_r) # This is rho or spearman's coefficient.
end
end
end
end
| ruby | MIT | 0ac388ab734120bd708164a10261b25b53faf29d | 2026-01-04T17:46:01.529291Z | false |
estebanz01/ruby-statistics | https://github.com/estebanz01/ruby-statistics/blob/0ac388ab734120bd708164a10261b25b53faf29d/lib/ruby-statistics/statistical_test/chi_squared_test.rb | lib/ruby-statistics/statistical_test/chi_squared_test.rb | module RubyStatistics
module StatisticalTest
class ChiSquaredTest
def self.chi_statistic(expected, observed)
# If the expected is a number, we asumme that all expected observations
# has the same probability to occur, hence we expect to see the same number
# of expected observations per each observed value
statistic = if expected.is_a? Numeric
observed.reduce(0) do |memo, observed_value|
up = (observed_value - expected) ** 2
memo += (up/expected.to_r)
end
else
expected.each_with_index.reduce(0) do |memo, (expected_value, index)|
up = (observed[index] - expected_value) ** 2
memo += (up/expected_value.to_r)
end
end
[statistic, observed.size - 1]
end
def self.goodness_of_fit(alpha, expected, observed)
chi_score, df = *self.chi_statistic(expected, observed) # Splat array result
return if chi_score.nil? || df.nil?
probability = Distribution::ChiSquared.new(df).cumulative_function(chi_score)
p_value = 1 - probability
# According to https://stats.stackexchange.com/questions/29158/do-you-reject-the-null-hypothesis-when-p-alpha-or-p-leq-alpha
# We can assume that if p_value <= alpha, we can safely reject the null hypothesis, ie. accept the alternative hypothesis.
{ probability: probability,
p_value: p_value,
alpha: alpha,
null: alpha < p_value,
alternative: p_value <= alpha,
confidence_level: 1 - alpha }
end
end
end
end
| ruby | MIT | 0ac388ab734120bd708164a10261b25b53faf29d | 2026-01-04T17:46:01.529291Z | false |
estebanz01/ruby-statistics | https://github.com/estebanz01/ruby-statistics/blob/0ac388ab734120bd708164a10261b25b53faf29d/lib/ruby-statistics/statistical_test/t_test.rb | lib/ruby-statistics/statistical_test/t_test.rb | module RubyStatistics
module StatisticalTest
class TTest
# Errors for Zero std
class ZeroStdError < StandardError
STD_ERROR_MSG = 'Standard deviation for the difference or group is zero. Please, reconsider sample contents'.freeze
end
# Perform a T-Test for one or two samples.
# For the tails param, we need a symbol: :one_tail or :two_tail
def self.perform(alpha, tails, *args)
return if args.size < 2
degrees_of_freedom = 0
# If the comparison mean has been specified
t_score = if args[0].is_a? Numeric
data_mean = args[1].mean
data_std = args[1].standard_deviation
raise ZeroStdError, ZeroStdError::STD_ERROR_MSG if data_std == 0
comparison_mean = args[0]
degrees_of_freedom = args[1].size - 1
(data_mean - comparison_mean)/(data_std / Math.sqrt(args[1].size).to_r).to_r
else
sample_left_mean = args[0].mean
sample_left_variance = args[0].variance
sample_right_variance = args[1].variance
sample_right_mean = args[1].mean
degrees_of_freedom = args.flatten.size - 2
left_root = sample_left_variance/args[0].size.to_r
right_root = sample_right_variance/args[1].size.to_r
standard_error = Math.sqrt(left_root + right_root)
(sample_left_mean - sample_right_mean).abs/standard_error.to_r
end
t_distribution = Distribution::TStudent.new(degrees_of_freedom)
probability = t_distribution.cumulative_function(t_score)
# Steps grabbed from https://support.minitab.com/en-us/minitab/18/help-and-how-to/statistics/basic-statistics/supporting-topics/basics/manually-calculate-a-p-value/
# See https://github.com/estebanz01/ruby-statistics/issues/23
p_value = if tails == :two_tail
2 * (1 - t_distribution.cumulative_function(t_score.abs))
else
1 - probability
end
{ t_score: t_score,
probability: probability,
p_value: p_value,
alpha: alpha,
null: alpha < p_value,
alternative: p_value <= alpha,
confidence_level: 1 - alpha }
end
def self.paired_test(alpha, tails, left_group, right_group)
raise StandardError, 'both samples are the same' if left_group == right_group
# Handy snippet grabbed from https://stackoverflow.com/questions/2682411/ruby-sum-corresponding-members-of-two-or-more-arrays
differences = [left_group, right_group].transpose.map { |value| value.reduce(:-) }
degrees_of_freedom = differences.size - 1
difference_std = differences.standard_deviation
raise ZeroStdError, ZeroStdError::STD_ERROR_MSG if difference_std == 0
down = difference_std/Math.sqrt(differences.size)
t_score = (differences.mean - 0)/down.to_r
t_distribution = Distribution::TStudent.new(degrees_of_freedom)
probability = t_distribution.cumulative_function(t_score)
p_value = if tails == :two_tail
2 * (1 - t_distribution.cumulative_function(t_score.abs))
else
1 - probability
end
{ t_score: t_score,
probability: probability,
p_value: p_value,
alpha: alpha,
null: alpha < p_value,
alternative: p_value <= alpha,
confidence_level: 1 - alpha }
end
end
end
end
| ruby | MIT | 0ac388ab734120bd708164a10261b25b53faf29d | 2026-01-04T17:46:01.529291Z | false |
estebanz01/ruby-statistics | https://github.com/estebanz01/ruby-statistics/blob/0ac388ab734120bd708164a10261b25b53faf29d/lib/ruby-statistics/statistical_test/kolmogorov_smirnov_test.rb | lib/ruby-statistics/statistical_test/kolmogorov_smirnov_test.rb | module RubyStatistics
module StatisticalTest
class KolmogorovSmirnovTest
# Common alpha, and critical D are calculated following formulas from: https://en.wikipedia.org/wiki/Kolmogorov%E2%80%93Smirnov_test#Two-sample_Kolmogorov%E2%80%93Smirnov_test
def self.two_samples(group_one:, group_two:, alpha: 0.05)
samples = group_one + group_two # We can use unbalaced group samples
ecdf_one = Distribution::Empirical.new(samples: group_one)
ecdf_two = Distribution::Empirical.new(samples: group_two)
d_max = samples.sort.map do |sample|
d1 = ecdf_one.cumulative_function(x: sample)
d2 = ecdf_two.cumulative_function(x: sample)
(d1 - d2).abs
end.max
# TODO: Validate calculation of Common alpha.
common_alpha = Math.sqrt((-0.5 * Math.log(alpha)))
radicand = (group_one.size + group_two.size) / (group_one.size * group_two.size).to_r
critical_d = common_alpha * Math.sqrt(radicand)
# critical_d = self.critical_d(alpha: alpha, n: samples.size)
# We are unable to calculate the p_value, because we don't have the Kolmogorov distribution
# defined. We reject the null hypotesis if Dmax is > than Dcritical.
{ d_max: d_max,
d_critical: critical_d,
total_samples: samples.size,
alpha: alpha,
null: d_max <= critical_d,
alternative: d_max > critical_d,
confidence_level: 1.0 - alpha }
end
# This is an implementation of the formula presented by Paul Molin and Hervé Abdi in a paper,
# called "New Table and numerical approximations for Kolmogorov-Smirnov / Lilliefors / Van Soest
# normality test".
# In this paper, the authors defines a couple of 6th-degree polynomial functions that allow us
# to find an aproximation of the real critical value. This is based in the conclusions made by
# Dagnelie (1968), where indicates that critical values given by Lilliefors can be approximated
# numerically.
#
# In general, the formula found is:
# C(N, alpha) ^ -2 = A(alpha) * N + B(alpha).
#
# Where A(alpha), B(alpha) are two 6th degree polynomial functions computed using the principle
# of Monte Carlo simulations.
#
# paper can be found here: https://utdallas.edu/~herve/MolinAbdi1998-LillieforsTechReport.pdf
# def self.critical_d(alpha:, n:)
# confidence = 1.0 - alpha
# a_alpha = 6.32207539843126 -17.1398870006148 * confidence +
# 38.42812675101057 * (confidence ** 2) - 45.93241384693391 * (confidence ** 3) +
# 7.88697700041829 * (confidence ** 4) + 29.79317711037858 * (confidence ** 5) -
# 18.48090137098585 * (confidence ** 6)
# b_alpha = 12.940399038404 - 53.458334259532 * confidence +
# 186.923866119699 * (confidence ** 2) - 410.582178349305 * (confidence ** 3) +
# 517.377862566267 * (confidence ** 4) - 343.581476222384 * (confidence ** 5) +
# 92.123451358715 * (confidence ** 6)
# Math.sqrt(1.0 / (a_alpha * n + b_alpha))
# end
end
KSTest = KolmogorovSmirnovTest # Alias
end
end
| ruby | MIT | 0ac388ab734120bd708164a10261b25b53faf29d | 2026-01-04T17:46:01.529291Z | false |
estebanz01/ruby-statistics | https://github.com/estebanz01/ruby-statistics/blob/0ac388ab734120bd708164a10261b25b53faf29d/lib/ruby-statistics/statistical_test/f_test.rb | lib/ruby-statistics/statistical_test/f_test.rb | module RubyStatistics
module StatisticalTest
class FTest
# This method calculates the one-way ANOVA F-test statistic.
# We assume that all specified arguments are arrays.
# It returns an array with three elements:
# [F-statistic or F-score, degrees of freedom numerator, degrees of freedom denominator].
#
# Formulas extracted from:
# https://courses.lumenlearning.com/boundless-statistics/chapter/one-way-anova/
# http://sphweb.bumc.bu.edu/otlt/MPH-Modules/BS/BS704_HypothesisTesting-ANOVA/BS704_HypothesisTesting-Anova_print.html
def self.anova_f_score(*args)
# If only two groups have been specified as arguments, we follow the classic F-Test for
# equality of variances, which is the ratio between the variances.
f_score = nil
df1 = nil
df2 = nil
if args.size == 2
variances = [args[0].variance, args[1].variance]
f_score = variances.max/variances.min.to_r
df1 = 1 # k-1 (k = 2)
df2 = args.flatten.size - 2 # N-k (k = 2)
elsif args.size > 2
total_groups = args.size
total_elements = args.flatten.size
overall_mean = args.flatten.mean
sample_sizes = args.map(&:size)
sample_means = args.map(&:mean)
# Variance between groups
iterator = sample_sizes.each_with_index
variance_between_groups = iterator.reduce(0) do |summation, (size, index)|
inner_calculation = size * ((sample_means[index] - overall_mean) ** 2)
summation += (inner_calculation / (total_groups - 1).to_r)
end
# Variance within groups
variance_within_groups = (0...total_groups).reduce(0) do |outer_summation, group_index|
outer_summation += args[group_index].reduce(0) do |inner_sumation, observation|
inner_calculation = ((observation - sample_means[group_index]) ** 2)
inner_sumation += (inner_calculation / (total_elements - total_groups).to_r)
end
end
f_score = variance_between_groups/variance_within_groups.to_r
df1 = total_groups - 1
df2 = total_elements - total_groups
end
[f_score, df1, df2]
end
# This method expects the alpha value and the groups to calculate the one-way ANOVA test.
# It returns a hash with multiple information and the test result (if reject the null hypotesis or not).
# Keep in mind that the values for the alternative key (true/false) does not imply that the alternative hypothesis
# is TRUE or FALSE. It's a minor notation advantage to decide if reject the null hypothesis or not.
def self.one_way_anova(alpha, *args)
f_score, df1, df2 = *self.anova_f_score(*args) # Splat array result
return if f_score.nil? || df1.nil? || df2.nil?
probability = Distribution::F.new(df1, df2).cumulative_function(f_score)
p_value = 1 - probability
# According to https://stats.stackexchange.com/questions/29158/do-you-reject-the-null-hypothesis-when-p-alpha-or-p-leq-alpha
# We can assume that if p_value <= alpha, we can safely reject the null hypothesis, ie. accept the alternative hypothesis.
{ probability: probability,
p_value: p_value,
alpha: alpha,
null: alpha < p_value,
alternative: p_value <= alpha,
confidence_level: 1 - alpha }
end
end
end
end
| ruby | MIT | 0ac388ab734120bd708164a10261b25b53faf29d | 2026-01-04T17:46:01.529291Z | false |
estebanz01/ruby-statistics | https://github.com/estebanz01/ruby-statistics/blob/0ac388ab734120bd708164a10261b25b53faf29d/lib/ruby-statistics/statistical_test/wilcoxon_rank_sum_test.rb | lib/ruby-statistics/statistical_test/wilcoxon_rank_sum_test.rb | module RubyStatistics
module StatisticalTest
class WilcoxonRankSumTest
def rank(elements)
ranked_elements = {}
elements.sort.each_with_index do |element, index|
if ranked_elements.fetch(element, false)
# This allow us to solve the ties easily when performing the rank summation per group
ranked_elements[element][:counter] += 1
ranked_elements[element][:rank] += (index + 1)
else
ranked_elements[element] = { counter: 1, rank: (index + 1) }
end
end
# ranked_elements = [{ x => { counter: 1, rank: y } ]
ranked_elements
end
# Steps to perform the calculation are based on http://www.mit.edu/~6.s085/notes/lecture5.pdf
def perform(alpha, tails, group_one, group_two)
# Size for each group
n1, n2 = group_one.size, group_two.size
# Rank all data
total_ranks = rank(group_one + group_two)
# sum rankings per group
r1 = ranked_sum_for(total_ranks, group_one)
r2 = ranked_sum_for(total_ranks, group_two)
# calculate U statistic
u1 = (n1 * (n1 + 1)/2.0) - r1
u2 = (n2 * (n2 + 1)/2.0 ) - r2
u_statistic = [u1.abs, u2.abs].min
median_u = (n1 * n2)/2.0
ties = total_ranks.values.select { |element| element[:counter] > 1 }
std_u = if ties.size > 0
corrected_sigma(ties, n1, n2)
else
Math.sqrt((n1 * n2 * (n1 + n2 + 1))/12.0)
end
z = (u_statistic - median_u)/std_u
# Most literature are not very specific about the normal distribution to be used.
# We ran multiple tests with a Normal(median_u, std_u) and Normal(0, 1) and we found
# the latter to be more aligned with the results.
probability = Distribution::StandardNormal.new.cumulative_function(z.abs)
p_value = 1 - probability
p_value *= 2 if tails == :two_tail
{ probability: probability,
u: u_statistic,
z: z,
p_value: p_value,
alpha: alpha,
null: alpha < p_value,
alternative: p_value <= alpha,
confidence_level: 1 - alpha }
end
# Formula extracted from http://www.statstutor.ac.uk/resources/uploaded/mannwhitney.pdf
private def corrected_sigma(ties, total_group_one, total_group_two)
n = total_group_one + total_group_two
rank_sum = ties.reduce(0) do |memo, t|
memo += ((t[:counter] ** 3) - t[:counter])/12.0
end
left = (total_group_one * total_group_two)/(n * (n - 1)).to_r
right = (((n ** 3) - n)/12.0) - rank_sum
Math.sqrt(left * right)
end
private def ranked_sum_for(total, group)
# sum rankings per group
group.reduce(0) do |memo, element|
rank_of_element = total[element][:rank] / total[element][:counter].to_r
memo += rank_of_element
end
end
end
# Both test are the same. To keep the selected name, we just alias the class
# with the implementation.
MannWhitneyU = WilcoxonRankSumTest
end
end
| ruby | MIT | 0ac388ab734120bd708164a10261b25b53faf29d | 2026-01-04T17:46:01.529291Z | false |
estebanz01/ruby-statistics | https://github.com/estebanz01/ruby-statistics/blob/0ac388ab734120bd708164a10261b25b53faf29d/lib/ruby-statistics/distribution/gamma.rb | lib/ruby-statistics/distribution/gamma.rb | # frozen_string_literal: true
module RubyStatistics
module Distribution
class Gamma
attr_reader :shape, :scale, :rate
def initialize(shape:, scale: nil)
@shape = shape
@scale = scale
# If the scale is nil, it means we want the distribution to behave with a rate parameter
# instead of a scale parameter
@rate = if scale.nil?
1.0 / shape
else
nil
end
end
def as_rate?
scale.nil?
end
def mean
if as_rate?
self.shape / self.rate
else
self.shape * self.scale
end
end
def mode
return 0.0 if self.shape < 1.0
if as_rate?
(self.shape - 1.0) / self.rate
else
(self.shape - 1.0) * self.scale
end
end
def variance
if as_rate?
self.shape / (self.rate ** 2.0)
else
self.shape * (self.scale ** 2.0)
end
end
def skewness
2.0 / Math.sqrt(self.shape)
end
def density_function(x)
euler = if as_rate?
Math.exp(- self.rate * x)
else
Math.exp(-x / self.scale.to_r)
end
left = if as_rate?
(self.rate ** self.shape).to_r / Math.gamma(self.shape).to_r
else
1r / (Math.gamma(self.shape).to_r * (self.scale ** self.shape).to_r)
end
left * (x ** (self.shape - 1)) * euler
end
def cumulative_function(x)
upper = if as_rate?
self.rate * x.to_r
else
x / self.scale.to_r
end
# left = 1.0 / Math.gamma(self.shape)
# right = Math.lower_incomplete_gamma_function(self.shape, upper)
# left * right
Math.normalised_lower_incomplete_gamma_function(self.shape, upper)
end
end
end
end
| ruby | MIT | 0ac388ab734120bd708164a10261b25b53faf29d | 2026-01-04T17:46:01.529291Z | false |
estebanz01/ruby-statistics | https://github.com/estebanz01/ruby-statistics/blob/0ac388ab734120bd708164a10261b25b53faf29d/lib/ruby-statistics/distribution/beta.rb | lib/ruby-statistics/distribution/beta.rb | module RubyStatistics
module Distribution
class Beta
attr_accessor :alpha, :beta
def initialize(alp, bet)
self.alpha = alp.to_r
self.beta = bet.to_r
end
def cumulative_function(value)
Math.incomplete_beta_function(value, alpha, beta)
end
def density_function(value)
return 0 if value < 0 || value > 1 # Density function defined in the [0,1] interval
num = (value**(alpha - 1)) * ((1 - value)**(beta - 1))
den = Math.beta_function(alpha, beta)
num/den
end
def mode
return unless alpha > 1 && beta > 1
(alpha - 1)/(alpha + beta - 2)
end
def mean
return if alpha + beta == 0
alpha / (alpha + beta)
end
end
end
end
| ruby | MIT | 0ac388ab734120bd708164a10261b25b53faf29d | 2026-01-04T17:46:01.529291Z | false |
estebanz01/ruby-statistics | https://github.com/estebanz01/ruby-statistics/blob/0ac388ab734120bd708164a10261b25b53faf29d/lib/ruby-statistics/distribution/empirical.rb | lib/ruby-statistics/distribution/empirical.rb | module RubyStatistics
module Distribution
class Empirical
attr_accessor :samples
def initialize(samples:)
self.samples = samples
end
# Formula grabbed from here: https://statlect.com/asymptotic-theory/empirical-distribution
def cumulative_function(x:)
cumulative_sum = samples.reduce(0) do |summation, sample|
summation += if sample <= x
1
else
0
end
summation
end
cumulative_sum / samples.size.to_r
end
end
end
end
| ruby | MIT | 0ac388ab734120bd708164a10261b25b53faf29d | 2026-01-04T17:46:01.529291Z | false |
estebanz01/ruby-statistics | https://github.com/estebanz01/ruby-statistics/blob/0ac388ab734120bd708164a10261b25b53faf29d/lib/ruby-statistics/distribution/geometric.rb | lib/ruby-statistics/distribution/geometric.rb | module RubyStatistics
module Distribution
class Geometric
attr_accessor :probability_of_success, :always_success_allowed
def initialize(p, always_success: false)
self.probability_of_success = p.to_r
self.always_success_allowed = always_success
end
def density_function(k)
k = k.to_i
if always_success_allowed
return if k < 0
((1.0 - probability_of_success) ** k) * probability_of_success
else
return if k <= 0
((1.0 - probability_of_success) ** (k - 1.0)) * probability_of_success
end
end
def cumulative_function(k)
k = k.to_i
if always_success_allowed
return if k < 0
1.0 - ((1.0 - probability_of_success) ** (k + 1.0))
else
return if k <= 0
1.0 - ((1.0 - probability_of_success) ** k)
end
end
def mean
if always_success_allowed
(1.0 - probability_of_success) / probability_of_success
else
1.0 / probability_of_success
end
end
def median
if always_success_allowed
(-1.0 / Math.log2(1.0 - probability_of_success)).ceil - 1.0
else
(-1.0 / Math.log2(1.0 - probability_of_success)).ceil
end
end
def mode
if always_success_allowed
0.0
else
1.0
end
end
def variance
(1.0 - probability_of_success) / (probability_of_success ** 2)
end
def skewness
(2.0 - probability_of_success) / Math.sqrt(1.0 - probability_of_success)
end
def kurtosis
6.0 + ((probability_of_success ** 2) / (1.0 - probability_of_success))
end
end
end
end
| ruby | MIT | 0ac388ab734120bd708164a10261b25b53faf29d | 2026-01-04T17:46:01.529291Z | false |
estebanz01/ruby-statistics | https://github.com/estebanz01/ruby-statistics/blob/0ac388ab734120bd708164a10261b25b53faf29d/lib/ruby-statistics/distribution/weibull.rb | lib/ruby-statistics/distribution/weibull.rb | module RubyStatistics
module Distribution
class Weibull
attr_accessor :shape, :scale # k and lambda
def initialize(k, lamb)
self.shape = k.to_r
self.scale = lamb.to_r
end
def cumulative_function(random_value)
return 0 if random_value < 0
1 - Math.exp(-((random_value/scale) ** shape))
end
def density_function(value)
return if shape <= 0 || scale <= 0
return 0 if value < 0
left = shape/scale
center = (value/scale)**(shape - 1)
right = Math.exp(-((value/scale)**shape))
left * center * right
end
def mean
scale * Math.gamma(1 + (1/shape))
end
def mode
return 0 if shape <= 1
scale * (((shape - 1)/shape) ** (1/shape))
end
def variance
left = Math.gamma(1 + (2/shape))
right = Math.gamma(1 + (1/shape)) ** 2
(scale ** 2) * (left - right)
end
# Using the inverse CDF function, also called quantile, we can calculate
# a random sample that follows a weibull distribution.
#
# Formula extracted from https://www.taygeta.com/random/weibull.html
def random(elements: 1, seed: Random.new_seed)
results = []
srand(seed)
elements.times do
results << ((-1/scale) * Math.log(1 - rand)) ** (1/shape)
end
if elements == 1
results.first
else
results
end
end
end
end
end
| ruby | MIT | 0ac388ab734120bd708164a10261b25b53faf29d | 2026-01-04T17:46:01.529291Z | false |
estebanz01/ruby-statistics | https://github.com/estebanz01/ruby-statistics/blob/0ac388ab734120bd708164a10261b25b53faf29d/lib/ruby-statistics/distribution/negative_binomial.rb | lib/ruby-statistics/distribution/negative_binomial.rb | module RubyStatistics
module Distribution
class NegativeBinomial
attr_accessor :number_of_failures, :probability_per_trial
def initialize(r, p)
self.number_of_failures = r.to_i
self.probability_per_trial = p
end
def probability_mass_function(k)
return if number_of_failures < 0 || k < 0 || k > number_of_failures
left = Math.combination(k + number_of_failures - 1, k)
right = ((1 - probability_per_trial) ** number_of_failures) * (probability_per_trial ** k)
left * right
end
def cumulative_function(k)
return if k < 0 || k > number_of_failures
k = k.to_i
1.0 - Math.incomplete_beta_function(probability_per_trial, k + 1, number_of_failures)
end
def mean
(probability_per_trial * number_of_failures)/(1 - probability_per_trial).to_r
end
def variance
(probability_per_trial * number_of_failures)/((1 - probability_per_trial) ** 2).to_r
end
def skewness
(1 + probability_per_trial).to_r / Math.sqrt(probability_per_trial * number_of_failures)
end
def mode
if number_of_failures > 1
up = probability_per_trial * (number_of_failures - 1)
down = (1 - probability_per_trial).to_r
(up/down).floor
elsif number_of_failures <= 1
0.0
end
end
end
end
end
| ruby | MIT | 0ac388ab734120bd708164a10261b25b53faf29d | 2026-01-04T17:46:01.529291Z | false |
estebanz01/ruby-statistics | https://github.com/estebanz01/ruby-statistics/blob/0ac388ab734120bd708164a10261b25b53faf29d/lib/ruby-statistics/distribution/poisson.rb | lib/ruby-statistics/distribution/poisson.rb | module RubyStatistics
module Distribution
class Poisson
attr_accessor :expected_number_of_occurrences
alias_method :mean, :expected_number_of_occurrences
alias_method :variance, :expected_number_of_occurrences
def initialize(l)
self.expected_number_of_occurrences = l
end
def probability_mass_function(k)
return if k < 0 || expected_number_of_occurrences < 0
k = k.to_i
upper = (expected_number_of_occurrences ** k) * Math.exp(-expected_number_of_occurrences)
lower = Math.factorial(k)
upper/lower.to_r
end
def cumulative_function(k)
return if k < 0 || expected_number_of_occurrences < 0
k = k.to_i
upper = Math.lower_incomplete_gamma_function((k + 1).floor, expected_number_of_occurrences)
lower = Math.factorial(k.floor)
# We need the right tail, i.e.: The upper incomplete gamma function. This can be
# achieved by doing a substraction between 1 and the lower incomplete gamma function.
1 - (upper/lower.to_r)
end
end
end
end
| ruby | MIT | 0ac388ab734120bd708164a10261b25b53faf29d | 2026-01-04T17:46:01.529291Z | false |
estebanz01/ruby-statistics | https://github.com/estebanz01/ruby-statistics/blob/0ac388ab734120bd708164a10261b25b53faf29d/lib/ruby-statistics/distribution/t_student.rb | lib/ruby-statistics/distribution/t_student.rb | module RubyStatistics
module Distribution
class TStudent
attr_accessor :degrees_of_freedom
attr_reader :mode
def initialize(v)
self.degrees_of_freedom = v
@mode = 0
end
### Extracted from https://codeplea.com/incomplete-beta-function-c
### This function is shared under zlib license and the author is Lewis Van Winkle
def cumulative_function(value)
upper = (value + Math.sqrt(value * value + degrees_of_freedom))
lower = (2.0 * Math.sqrt(value * value + degrees_of_freedom))
x = upper/lower
alpha = degrees_of_freedom/2.0
beta = degrees_of_freedom/2.0
Math.incomplete_beta_function(x, alpha, beta)
end
def density_function(value)
return if degrees_of_freedom <= 0
upper = Math.gamma((degrees_of_freedom + 1)/2.0)
lower = Math.sqrt(degrees_of_freedom * Math::PI) * Math.gamma(degrees_of_freedom/2.0)
left = upper/lower
right = (1 + ((value ** 2)/degrees_of_freedom.to_r)) ** -((degrees_of_freedom + 1)/2.0)
left * right
end
def mean
0 if degrees_of_freedom > 1
end
def variance
if degrees_of_freedom > 1 && degrees_of_freedom <= 2
Float::INFINITY
elsif degrees_of_freedom > 2
degrees_of_freedom/(degrees_of_freedom - 2.0)
end
end
# Quantile function extracted from http://www.jennessent.com/arcview/idf.htm
# TODO: Make it truly Student's T sample.
def random(elements: 1, seed: Random.new_seed)
warn 'This is an alpha version code. The generated sample is similar to an uniform distribution'
srand(seed)
v = degrees_of_freedom
results = []
# Because the Quantile function of a student-t distribution is between (-Infinity, y)
# we setup an small threshold in order to properly compute the integral
threshold = 10_000.0e-12
elements.times do
y = rand
results << Math.simpson_rule(threshold, y, 10_000) do |t|
up = Math.gamma((v+1)/2.0)
down = Math.sqrt(Math::PI * v) * Math.gamma(v/2.0)
right = (1 + ((y ** 2)/v.to_r)) ** ((v+1)/2.0)
left = up/down.to_r
left * right
end
end
if elements == 1
results.first
else
results
end
end
end
end
end
| ruby | MIT | 0ac388ab734120bd708164a10261b25b53faf29d | 2026-01-04T17:46:01.529291Z | false |
estebanz01/ruby-statistics | https://github.com/estebanz01/ruby-statistics/blob/0ac388ab734120bd708164a10261b25b53faf29d/lib/ruby-statistics/distribution/binomial.rb | lib/ruby-statistics/distribution/binomial.rb | module RubyStatistics
module Distribution
class Binomial
attr_accessor :number_of_trials, :probability_per_trial
def initialize(n, p)
self.number_of_trials = n.to_i
self.probability_per_trial = p
end
def probability_mass_function(k)
return if k < 0 || k > number_of_trials
k = k.to_i
Math.combination(number_of_trials, k) *
(probability_per_trial ** k) * ((1 - probability_per_trial) ** (number_of_trials - k))
end
def cumulative_function(k)
return if k < 0 || k > number_of_trials
k = k.to_i
p = 1 - probability_per_trial
Math.incomplete_beta_function(p, number_of_trials - k, 1 + k)
end
def mean
number_of_trials * probability_per_trial
end
def variance
mean * (1 - probability_per_trial)
end
def mode
test = (number_of_trials + 1) * probability_per_trial
returned = if test == 0 || (test % 1 != 0)
test.floor
elsif (test % 1 == 0) && (test >= 1 && test <= number_of_trials)
[test, test - 1]
elsif test == number_of_trials + 1
number_of_trials
end
returned
end
end
end
end
| ruby | MIT | 0ac388ab734120bd708164a10261b25b53faf29d | 2026-01-04T17:46:01.529291Z | false |
estebanz01/ruby-statistics | https://github.com/estebanz01/ruby-statistics/blob/0ac388ab734120bd708164a10261b25b53faf29d/lib/ruby-statistics/distribution/logseries.rb | lib/ruby-statistics/distribution/logseries.rb | module RubyStatistics
module Distribution
class LogSeries
def self.density_function(k, p)
return if k <= 0
k = k.to_i
left = (-1.0 / Math.log(1.0 - p))
right = (p ** k).to_r
left * right / k
end
def self.cumulative_function(k, p)
return if k <= 0
# Sadly, the incomplete beta function is converging
# too fast to zero and breaking the calculation on logs.
# So, we default to the basic definition of the CDF which is
# the integral (-Inf, K) of the PDF, with P(X <= x) which can
# be solved as a summation of all PDFs from 1 to K. Note that the summation approach
# only applies to discrete distributions.
#
# right = Math.incomplete_beta_function(p, (k + 1).floor, 0) / Math.log(1.0 - p)
# 1.0 + right
result = 0.0
1.upto(k) do |number|
result += self.density_function(number, p)
end
result
end
def self.mode
1.0
end
def self.mean(p)
(-1.0 / Math.log(1.0 - p)) * (p / (1.0 - p))
end
def self.variance(p)
up = p + Math.log(1.0 - p)
down = ((1.0 - p) ** 2) * (Math.log(1.0 - p) ** 2)
(-1.0 * p) * (up / down.to_r)
end
end
end
end
| ruby | MIT | 0ac388ab734120bd708164a10261b25b53faf29d | 2026-01-04T17:46:01.529291Z | false |
estebanz01/ruby-statistics | https://github.com/estebanz01/ruby-statistics/blob/0ac388ab734120bd708164a10261b25b53faf29d/lib/ruby-statistics/distribution/normal.rb | lib/ruby-statistics/distribution/normal.rb | module RubyStatistics
module Distribution
class Normal
attr_accessor :mean, :standard_deviation, :variance
alias_method :mode, :mean
def initialize(avg, std)
self.mean = avg.to_r
self.standard_deviation = std.to_r
self.variance = std.to_r**2
end
def cumulative_function(value)
(1/2.0) * (1.0 + Math.erf((value - mean)/(standard_deviation * Math.sqrt(2.0))))
end
def density_function(value)
return 0 if standard_deviation <= 0
up_right = (value - mean)**2.0
down_right = 2.0 * variance
right = Math.exp(-(up_right/down_right))
left_down = Math.sqrt(2.0 * Math::PI * variance)
left_up = 1.0
(left_up/(left_down) * right)
end
## Marsaglia polar method implementation for random gaussian (normal) number generation.
# References:
# https://en.wikipedia.org/wiki/Marsaglia_polar_method
# https://math.stackexchange.com/questions/69245/transform-uniform-distribution-to-normal-distribution-using-lindeberg-l%C3%A9vy-clt
# https://www.projectrhea.org/rhea/index.php/The_principles_for_how_to_generate_random_samples_from_a_Gaussian_distribution
def random(elements: 1, seed: Random.new_seed)
results = []
# Setup seed
srand(seed)
# Number of random numbers to be generated.
elements.times do
x, y, r = 0.0, 0.0, 0.0
# Find an (x, y) point in the x^2 + y^2 < 1 circumference.
loop do
x = 2.0 * rand - 1.0
y = 2.0 * rand - 1.0
r = (x ** 2) + (y ** 2)
break unless r >= 1.0 || r == 0
end
# Project the random point to the required random distance
r = Math.sqrt(-2.0 * Math.log(r) / r)
# Transform the random distance to a gaussian value and append it to the results array
results << mean + x * r * standard_deviation
end
if elements == 1
results.first
else
results
end
end
end
class StandardNormal < Normal
def initialize
super(0, 1) # Mean = 0, Std = 1
end
def density_function(value)
pow = (value**2)/2.0
euler = Math.exp(-pow)
euler/Math.sqrt(2 * Math::PI)
end
end
# Inverse Standard Normal distribution:
# References:
# https://en.wikipedia.org/wiki/Inverse_distribution
# http://www.source-code.biz/snippets/vbasic/9.htm
class InverseStandardNormal < StandardNormal
A1 = -39.6968302866538
A2 = 220.946098424521
A3 = -275.928510446969
A4 = 138.357751867269
A5 = -30.6647980661472
A6 = 2.50662827745924
B1 = -54.4760987982241
B2 = 161.585836858041
B3 = -155.698979859887
B4 = 66.8013118877197
B5 = -13.2806815528857
C1 = -7.78489400243029E-03
C2 = -0.322396458041136
C3 = -2.40075827716184
C4 = -2.54973253934373
C5 = 4.37466414146497
C6 = 2.93816398269878
D1 = 7.78469570904146E-03
D2 = 0.32246712907004
D3 = 2.445134137143
D4 = 3.75440866190742
P_LOW = 0.02425
P_HIGH = 1 - P_LOW
def density_function(_)
raise NotImplementedError
end
def random(elements: 1, seed: Random.new_seed)
raise NotImplementedError
end
def cumulative_function(value)
return if value < 0.0 || value > 1.0
return -1.0 * Float::INFINITY if value.zero?
return Float::INFINITY if value == 1.0
if value < P_LOW
q = Math.sqrt((Math.log(value) * -2.0))
(((((C1 * q + C2) * q + C3) * q + C4) * q + C5) * q + C6) / ((((D1 * q + D2) * q + D3) * q + D4) * q + 1.0)
elsif value <= P_HIGH
q = value - 0.5
r = q ** 2
(((((A1 * r + A2) * r + A3) * r + A4) * r + A5) * r + A6) * q / (((((B1 * r + B2) * r + B3) * r + B4) * r + B5) * r + 1.0)
else
q = Math.sqrt((Math.log(1 - value) * -2.0))
- (((((C1 * q + C2) * q + C3) * q + C4) * q + C5) * q + C6) / ((((D1 * q + D2) * q + D3) * q + D4) * q + 1)
end
end
end
end
end
| ruby | MIT | 0ac388ab734120bd708164a10261b25b53faf29d | 2026-01-04T17:46:01.529291Z | false |
estebanz01/ruby-statistics | https://github.com/estebanz01/ruby-statistics/blob/0ac388ab734120bd708164a10261b25b53faf29d/lib/ruby-statistics/distribution/f.rb | lib/ruby-statistics/distribution/f.rb | module RubyStatistics
module Distribution
class F
attr_accessor :d1, :d2 # Degrees of freedom #1 and #2
def initialize(k, j)
self.d1 = k
self.d2 = j
end
# Formula extracted from http://www.itl.nist.gov/div898/handbook/eda/section3/eda3665.htm#CDF
def cumulative_function(value)
k = d2/(d2 + d1 * value.to_r)
1 - Math.incomplete_beta_function(k, d2/2.0, d1/2.0)
end
def density_function(value)
return if d1 < 0 || d2 < 0 # F-pdf is well defined for the [0, +infinity) interval.
val = value.to_r
upper = ((d1 * val) ** d1) * (d2**d2)
lower = (d1 * val + d2) ** (d1 + d2)
up = Math.sqrt(upper/lower.to_r)
down = val * Math.beta_function(d1/2.0, d2/2.0)
up/down.to_r
end
def mean
return if d2 <= 2
d2/(d2 - 2).to_r
end
def mode
return if d1 <= 2
left = (d1 - 2)/d1.to_r
right = d2/(d2 + 2).to_r
(left * right).to_f
end
end
end
end
| ruby | MIT | 0ac388ab734120bd708164a10261b25b53faf29d | 2026-01-04T17:46:01.529291Z | false |
estebanz01/ruby-statistics | https://github.com/estebanz01/ruby-statistics/blob/0ac388ab734120bd708164a10261b25b53faf29d/lib/ruby-statistics/distribution/chi_squared.rb | lib/ruby-statistics/distribution/chi_squared.rb | module RubyStatistics
module Distribution
class ChiSquared
attr_accessor :degrees_of_freedom
alias_method :mean, :degrees_of_freedom
def initialize(k)
self.degrees_of_freedom = k
end
def cumulative_function(value)
if degrees_of_freedom == 2
# Special case where DF = 2 https://en.wikipedia.org/wiki/Chi-squared_distribution#Cumulative_distribution_function
1.0 - Math.exp((-1.0 * value / 2.0))
else
k = degrees_of_freedom/2.0
# Math.lower_incomplete_gamma_function(k, value/2.0)/Math.gamma(k)
Math.normalised_lower_incomplete_gamma_function(k, value / 2.0)
end
end
def density_function(value)
return 0 if value < 0
common = degrees_of_freedom/2.0
left_down = (2 ** common) * Math.gamma(common)
right = (value ** (common - 1)) * Math.exp(-(value/2.0))
right / left_down
end
def mode
[degrees_of_freedom - 2, 0].max
end
def variance
degrees_of_freedom * 2
end
end
end
end
| ruby | MIT | 0ac388ab734120bd708164a10261b25b53faf29d | 2026-01-04T17:46:01.529291Z | false |
estebanz01/ruby-statistics | https://github.com/estebanz01/ruby-statistics/blob/0ac388ab734120bd708164a10261b25b53faf29d/lib/ruby-statistics/distribution/uniform.rb | lib/ruby-statistics/distribution/uniform.rb | module RubyStatistics
module Distribution
class Uniform
attr_accessor :left, :right
def initialize(a, b)
self.left = a.to_r
self.right = b.to_r
end
def density_function(value)
if value >= left && value <= right
1/(right - left)
else
0
end
end
def cumulative_function(value)
if value < left
0
elsif value >= left && value <= right
(value - left)/(right - left)
else
1
end
end
def mean
(1/2.0) * ( left + right )
end
alias_method :median, :mean
def variance
(1/12.0) * ( right - left ) ** 2
end
end
end
end
| ruby | MIT | 0ac388ab734120bd708164a10261b25b53faf29d | 2026-01-04T17:46:01.529291Z | false |
estebanz01/ruby-statistics | https://github.com/estebanz01/ruby-statistics/blob/0ac388ab734120bd708164a10261b25b53faf29d/lib/ruby-statistics/distribution/bernoulli.rb | lib/ruby-statistics/distribution/bernoulli.rb | module RubyStatistics
module Distribution
class Bernoulli
def self.density_function(n, p)
return if n != 0 && n != 1 # The support of the distribution is n = {0, 1}.
case n
when 0 then 1.0 - p
when 1 then p
end
end
def self.cumulative_function(n, p)
return if n != 0 && n != 1 # The support of the distribution is n = {0, 1}.
case n
when 0 then 1.0 - p
when 1 then 1.0
end
end
def self.variance(p)
p * (1.0 - p)
end
def self.skewness(p)
(1.0 - 2.0*p).to_r / Math.sqrt(p * (1.0 - p))
end
def self.kurtosis(p)
(6.0 * (p ** 2) - (6 * p) + 1) / (p * (1.0 - p))
end
end
end
end
| ruby | MIT | 0ac388ab734120bd708164a10261b25b53faf29d | 2026-01-04T17:46:01.529291Z | false |
estebanz01/ruby-statistics | https://github.com/estebanz01/ruby-statistics/blob/0ac388ab734120bd708164a10261b25b53faf29d/lib/ruby-statistics/distribution/tables/chi_squared.rb | lib/ruby-statistics/distribution/tables/chi_squared.rb | module RubyStatistics
module Distribution
module Tables
class ChiSquared
# Values retrieved from the following table provided by the University of Arizona.
# https://math.arizona.edu/~jwatkins/chi-square-table.pdf
TABLE = [
[0.000, 0.000, 0.001, 0.004, 0.016, 2.706, 3.841, 5.024, 6.635, 7.879],
[0.010, 0.020, 0.051, 0.103, 0.211, 4.605, 5.991, 7.378, 9.210, 10.597],
[0.072, 0.115, 0.216, 0.352, 0.584, 6.251, 7.815, 9.348, 11.345, 12.838],
[0.207, 0.297, 0.484, 0.711, 1.064, 7.779, 9.488, 11.143, 13.277, 14.860],
[0.412, 0.554, 0.831, 1.145, 1.610, 9.236, 11.070, 12.833, 15.086, 16.750],
[0.676, 0.872, 1.237, 1.635, 2.204, 10.645, 12.592, 14.449, 16.812, 18.548],
[0.989, 1.239, 1.690, 2.167, 2.833, 12.017, 14.067, 16.013, 18.475, 20.278],
[1.344, 1.646, 2.180, 2.733, 3.490, 13.362, 15.507, 17.535, 20.090, 21.955],
[1.735, 2.088, 2.700, 3.325, 4.168, 14.684, 16.919, 19.023, 21.666, 23.589],
[2.156, 2.558, 3.247, 3.940, 4.865, 15.987, 18.307, 20.483, 23.209, 25.188],
[2.603, 3.053, 3.816, 4.575, 5.578, 17.275, 19.675, 21.920, 24.725, 26.757],
[3.074, 3.571, 4.404, 5.226, 6.304, 18.549, 21.026, 23.337, 26.217, 28.300],
[3.565, 4.107, 5.009, 5.892, 7.042, 19.812, 22.362, 24.736, 27.688, 29.819],
[4.075, 4.660, 5.629, 6.571, 7.790, 21.064, 23.685, 26.119, 29.141, 31.319],
[4.601, 5.229, 6.262, 7.261, 8.547, 22.307, 24.996, 27.488, 30.578, 32.801],
[5.142, 5.812, 6.908, 7.962, 9.312, 23.542, 26.296, 28.845, 32.000, 34.267],
[5.697, 6.408, 7.564, 8.672, 10.085, 24.769, 27.587, 30.191, 33.409, 35.718],
[6.265, 7.015, 8.231, 9.390, 10.865, 25.989, 28.869, 31.526, 34.805, 37.156],
[6.844, 7.633, 8.907, 10.117, 11.651, 27.204, 30.144, 32.852, 36.191, 38.582],
[7.434, 8.260, 9.591, 10.851, 12.443, 28.412, 31.410, 34.170, 37.566, 39.997],
[8.034, 8.897, 10.283, 11.591, 13.240, 29.615, 32.671, 35.479, 38.932, 41.401],
[8.643, 9.542, 10.982, 12.338, 14.041, 30.813, 33.924, 36.781, 40.289, 42.796],
[9.260, 10.196, 11.689, 13.091, 14.848, 32.007, 35.172, 38.076, 41.638, 44.181],
[9.886, 10.856, 12.401, 13.848, 15.659, 33.196, 36.415, 39.364, 42.980, 45.559],
[10.520, 11.524, 13.120, 14.611, 16.473, 34.382, 37.652, 40.646, 44.314, 46.928],
[11.160, 12.198, 13.844, 15.379, 17.292, 35.563, 38.885, 41.923, 45.642, 48.290],
[11.808, 12.879, 14.573, 16.151, 18.114, 36.741, 40.113, 43.195, 46.963, 49.645],
[12.461, 13.565, 15.308, 16.928, 18.939, 37.916, 41.337, 44.461, 48.278, 50.993],
[13.121, 14.256, 16.047, 17.708, 19.768, 39.087, 42.557, 45.722, 49.588, 52.336],
[13.787, 14.953, 16.791, 18.493, 20.599, 40.256, 43.773, 46.979, 50.892, 53.672],
[20.707, 22.164, 24.433, 26.509, 29.051, 51.805, 55.758, 59.342, 63.691, 66.766],
[27.991, 29.707, 32.357, 34.764, 37.689, 63.167, 67.505, 71.420, 76.154, 79.490],
[35.534, 37.485, 40.482, 43.188, 46.459, 74.397, 79.082, 83.298, 88.379, 91.952],
[43.275, 45.442, 48.758, 51.739, 55.329, 85.527, 90.531, 95.023, 100.425, 104.215],
[51.172, 53.540, 57.153, 60.391, 64.278, 96.578, 101.879, 106.629, 112.329, 116.321],
[59.196, 61.754, 65.647, 69.126, 73.291, 107.565, 113.145, 118.136, 124.116, 128.299],
[67.328, 70.065, 74.222, 77.929, 82.358, 118.498, 124.342, 129.561, 135.807, 140.169]
].freeze
ALPHA_HEADER =
{
0.995 => 0,
0.990 => 1,
0.975 => 2,
0.95 => 3,
0.9 => 4,
0.1 => 5,
0.05 => 6,
0.025 => 7,
0.01 => 8,
0.005 => 9
}.freeze
DEGREES_OF_FREEDOM = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 40, 50, 60, 70, 80, 90, 100].freeze
# return an array of the alpha values in correct order
# i.e. 0.995 -> 0, 0.990 -> 1 etc
def self.alpha_values
ALPHA_HEADER.keys
end
# Checks if a valid alpha value is passed to look up values
def self.valid_alpha?(alpha)
self.alpha_values.include?(alpha)
end
# Return a whole column of the distribution table for a certain alpha value
def self.alpha_column(alpha)
raise "Undefined alpha value." unless self.valid_alpha?(alpha)
# return an array of hashes for an alpha value
# including the degree of freedom for each critical value
# i.e. [{df: 1, critival_value: x},...]
TABLE.map.with_index do |row, index|
{ df: DEGREES_OF_FREEDOM[index], critical_value: row[ALPHA_HEADER[alpha]] }
end
end
end
end
end
end
| ruby | MIT | 0ac388ab734120bd708164a10261b25b53faf29d | 2026-01-04T17:46:01.529291Z | false |
forestryio/jekyll-menus | https://github.com/forestryio/jekyll-menus/blob/288acfacfaa14a94fbfd6738b10f9311da3a436c/spec/rspec/helper.rb | spec/rspec/helper.rb | ruby | MIT | 288acfacfaa14a94fbfd6738b10f9311da3a436c | 2026-01-04T17:46:07.109073Z | false | |
forestryio/jekyll-menus | https://github.com/forestryio/jekyll-menus/blob/288acfacfaa14a94fbfd6738b10f9311da3a436c/spec/lib/jekyll/menus.rb | spec/lib/jekyll/menus.rb | ruby | MIT | 288acfacfaa14a94fbfd6738b10f9311da3a436c | 2026-01-04T17:46:07.109073Z | false | |
forestryio/jekyll-menus | https://github.com/forestryio/jekyll-menus/blob/288acfacfaa14a94fbfd6738b10f9311da3a436c/lib/jekyll-menus.rb | lib/jekyll-menus.rb | # Frozen-string-literal: true
# Copyright: 2015 Forestry.io - MIT License
# Encoding: utf-8
require "jekyll/menus"
| ruby | MIT | 288acfacfaa14a94fbfd6738b10f9311da3a436c | 2026-01-04T17:46:07.109073Z | false |
forestryio/jekyll-menus | https://github.com/forestryio/jekyll-menus/blob/288acfacfaa14a94fbfd6738b10f9311da3a436c/lib/jekyll/menus.rb | lib/jekyll/menus.rb | # Frozen-string-literal: true
# Copyright: 2015 Forestry.io - MIT License
# Encoding: utf-8
module Jekyll
class Menus
autoload :Utils, "jekyll/menus/utils"
autoload :Drops, "jekyll/menus/drops"
def initialize(site)
@site = site
end
#
def menus
Utils.deep_merge(_data_menus, Utils.deep_merge(
_page_menus, _collection_menus
))
end
#
def to_liquid_drop
Drops::All.new(
menus
)
end
#
def _data_menus
out = {}
if @site.data["menus"] && @site.data["menus"].is_a?(Hash)
then @site.data["menus"].each do |key, menu|
if menu.is_a?(Hash) || menu.is_a?(Array)
(menu = [menu].flatten).each do |item|
_validate_config_menu_item(
item
)
item["_frontmatter"] = false
end
else
_throw_invalid_menu_entry(
menu
)
end
merge = { key => menu }
out = Utils.deep_merge(
out, merge
)
end
end
out
end
#
def _page_menus
out = {}
@site.pages.select { |p| p.data.keys.grep(/menus?/).size > 0 }.each_with_object({}) do |page|
[page.data["menus"], page.data["menu"]].flatten.compact.map do |menu|
out = _front_matter_menu(menu, page, out)
end
end
out
end
#
def _collection_menus
out = {}
@site.collections.each do |collection, pages|
pages.docs.select { |p| p.data.keys.grep(/menus?/).size > 0 }.each_with_object({}) do |page|
[page.data["menus"], page.data["menu"]].flatten.compact.map do |menu|
out = _front_matter_menu(menu, page, out)
end
end
end
out
end
#
def _front_matter_menu(menu, page, out={})
# --
# menu: key
# menu:
# - key1
# - key2
# --
if menu.is_a?(Array) || menu.is_a?(String)
_simple_front_matter_menu(menu, **{
:mergeable => out, :page => page
})
#
elsif menu.is_a?(Hash)
menu.each do |key, item|
out[key] ||= []
# --
# menu:
# key: identifier
# --
if item.is_a?(String)
out[key] << _fill_front_matter_menu({ "identifier" => item }, **{
:page => page
})
# --
# menu:
# key:
# url: /url
# --
elsif item.is_a?(Hash)
out[key] << _fill_front_matter_menu(item, **{
:page => page
})
# --
# menu:
# key:
# - url: /url
# --
else
_throw_invalid_menu_entry(
item
)
end
end
# --
# menu:
# key: 3
# --
else
_throw_invalid_menu_entry(
menu
)
end
out
end
#
private
def _simple_front_matter_menu(menu, mergeable: nil, page: nil)
if menu.is_a?(Array)
then menu.each do |item|
if !item.is_a?(String)
_throw_invalid_menu_entry(
item
)
else
_simple_front_matter_menu(item, {
:mergeable => mergeable, :page => page
})
end
end
else
mergeable[menu] ||= []
mergeable[menu] << _fill_front_matter_menu(nil, **{
:page => page
})
end
end
#
private
def _fill_front_matter_menu(val, page: nil)
raise ArgumentError, "Kwd 'page' is required." unless page
val ||= {}
val["url"] ||= page.url
val["identifier"] ||= slug(page)
val["_frontmatter"] = page.relative_path # `page.url` can be changed with permalink frontmatter
val["title"] ||= page.data["title"]
val["weight"] ||= -1
val
end
#
private
def slug(page)
ext = page.data["ext"] || page.ext
out = File.join(File.dirname(page.path), File.basename(page.path, ext))
out.tr("^a-z0-9-_\\/", "").gsub(/\/|\-+/, "_").gsub(
/^_+/, ""
)
end
#
private
def _validate_config_menu_item(item)
if !item.is_a?(Hash) || !item.values_at("url", "title", "identifier").compact.size == 3
_throw_invalid_menu_entry(
item
)
else
item["weight"] ||= -1
end
end
#
private
def _throw_invalid_menu_entry(data)
raise RuntimeError, "Invalid menu item given: #{
data.inspect
}"
end
end
end
require "jekyll/menus/hook"
| ruby | MIT | 288acfacfaa14a94fbfd6738b10f9311da3a436c | 2026-01-04T17:46:07.109073Z | false |
forestryio/jekyll-menus | https://github.com/forestryio/jekyll-menus/blob/288acfacfaa14a94fbfd6738b10f9311da3a436c/lib/jekyll/menus/drops.rb | lib/jekyll/menus/drops.rb | # Frozen-string-literal: true
# Copyright: 2015 Forestry.io - MIT License
# Encoding: utf-8
module Jekyll
class Menus
module Drops
autoload :Menu, "jekyll/menus/drops/menu"
autoload :All, "jekyll/menus/drops/all"
autoload :Item, "jekyll/menus/drops/item"
end
end
end
| ruby | MIT | 288acfacfaa14a94fbfd6738b10f9311da3a436c | 2026-01-04T17:46:07.109073Z | false |
forestryio/jekyll-menus | https://github.com/forestryio/jekyll-menus/blob/288acfacfaa14a94fbfd6738b10f9311da3a436c/lib/jekyll/menus/version.rb | lib/jekyll/menus/version.rb | # Frozen-string-literal: true
# Copyright: 2015 Forestry.io - MIT License
# Encoding: utf-8
module Jekyll
class Menus
VERSION = "0.6.1"
end
end
| ruby | MIT | 288acfacfaa14a94fbfd6738b10f9311da3a436c | 2026-01-04T17:46:07.109073Z | false |
forestryio/jekyll-menus | https://github.com/forestryio/jekyll-menus/blob/288acfacfaa14a94fbfd6738b10f9311da3a436c/lib/jekyll/menus/utils.rb | lib/jekyll/menus/utils.rb | # Frozen-string-literal: true
# Copyright: 2015 Forestry.io - MIT License
# Encoding: utf-8
module Jekyll
class Menus
module Utils module_function
def deep_merge(old, _new)
return old | _new if old.is_a?(Array)
old.merge(_new) do |_, o, n|
(o.is_a?(Hash) && n.is_a?(Hash)) || (o.is_a?(Array) &&
n.is_a?(Array)) ? deep_merge(o, n) : n
end
end
def deep_merge!(old, _new)
old.replace(deep_merge(
old, _new
))
end
end
end
end
| ruby | MIT | 288acfacfaa14a94fbfd6738b10f9311da3a436c | 2026-01-04T17:46:07.109073Z | false |
forestryio/jekyll-menus | https://github.com/forestryio/jekyll-menus/blob/288acfacfaa14a94fbfd6738b10f9311da3a436c/lib/jekyll/menus/hook.rb | lib/jekyll/menus/hook.rb | # Frozen-string-literal: true
# Copyright: 2015 Forestry.io - MIT License
# Encoding: utf-8
module Jekyll
module Drops
class SiteDrop
attr_accessor :menus
end
end
end
Jekyll::Hooks.register :site, :pre_render do |site, payload|
payload.site.menus = Jekyll::Menus.new(site).to_liquid_drop
end
| ruby | MIT | 288acfacfaa14a94fbfd6738b10f9311da3a436c | 2026-01-04T17:46:07.109073Z | false |
forestryio/jekyll-menus | https://github.com/forestryio/jekyll-menus/blob/288acfacfaa14a94fbfd6738b10f9311da3a436c/lib/jekyll/menus/drops/menu.rb | lib/jekyll/menus/drops/menu.rb | # Frozen-string-literal: true
# Copyright: 2015 Forestry.io - MIT License
# Encoding: utf-8
module Jekyll
class Menus
module Drops
class Menu < Liquid::Drop
attr_reader :parent, :identifier, :menu
def initialize(menu, identifier, parent)
@parent = parent
@identifier = identifier
@menu = menu
end
#
def find
to_a.find do |item|
yield item
end
end
#
def select
to_a.select do |item|
yield item
end
end
#
def to_a
@menu.map { |item| Item.new(item, parent) }.sort_by(
&:weight
)
end
#
def each
to_a.each do |drop|
yield drop
end
end
end
end
end
end
| ruby | MIT | 288acfacfaa14a94fbfd6738b10f9311da3a436c | 2026-01-04T17:46:07.109073Z | false |
forestryio/jekyll-menus | https://github.com/forestryio/jekyll-menus/blob/288acfacfaa14a94fbfd6738b10f9311da3a436c/lib/jekyll/menus/drops/item.rb | lib/jekyll/menus/drops/item.rb | # Frozen-string-literal: true
# Copyright: 2015 Forestry.io - MIT License
# Encoding: utf-8
module Jekyll
class Menus
module Drops
class Item < Liquid::Drop
def initialize(item, parent)
@parent = parent
@item =
item
end
#
def children
out = @parent.find { |menu| menu.identifier == @item["identifier"] }
if out
return out.to_a
end
end
#
def url
@item[
"url"
]
end
#
def title
@item[
"title"
]
end
#
def identifier
@item[
"identifier"
]
end
#
def weight
@item[
"weight"
]
end
#
def before_method(method)
if @item.has_key?(method.to_s)
return @item[
method.to_s
]
end
end
alias_method :liquid_method_missing, :before_method
end
end
end
end
| ruby | MIT | 288acfacfaa14a94fbfd6738b10f9311da3a436c | 2026-01-04T17:46:07.109073Z | false |
forestryio/jekyll-menus | https://github.com/forestryio/jekyll-menus/blob/288acfacfaa14a94fbfd6738b10f9311da3a436c/lib/jekyll/menus/drops/all.rb | lib/jekyll/menus/drops/all.rb | # Frozen-string-literal: true
# Copyright: 2015 Forestry.io - MIT License
# Encoding: utf-8
module Jekyll
class Menus
module Drops
class All < Liquid::Drop
def initialize(menus)
@menus = menus
end
#
def find
to_a.find do |menu|
yield menu
end
end
#
def to_a
@menus.keys.map do |identifier|
self[
identifier
]
end
end
#
def each
to_a.each do |drop|
yield drop
end
end
#
def [](key)
if @menus.key?(key)
then Menu.new(@menus[key],
key, self
)
end
end
end
end
end
end
| ruby | MIT | 288acfacfaa14a94fbfd6738b10f9311da3a436c | 2026-01-04T17:46:07.109073Z | false |
chefspec/fauxhai | https://github.com/chefspec/fauxhai/blob/86a0ac4d5ab91f249801ffa290ae39a58d99b6b4/spec/spec_helper.rb | spec/spec_helper.rb | require "rspec"
require "rspec/its"
require "fauxhai"
RSpec.configure do |config|
# Basic configuraiton
config.run_all_when_everything_filtered = true
config.filter_run(:focus)
config.add_formatter("documentation")
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = "random"
config.seed = ENV["SEED"].to_i if ENV["SEED"]
# Enable full backtrace if $DEBUG is set.
config.full_backtrace = true if ENV["DEBUG"]
end
| ruby | MIT | 86a0ac4d5ab91f249801ffa290ae39a58d99b6b4 | 2026-01-04T17:45:47.766557Z | false |
chefspec/fauxhai | https://github.com/chefspec/fauxhai/blob/86a0ac4d5ab91f249801ffa290ae39a58d99b6b4/spec/mocker_spec.rb | spec/mocker_spec.rb | require "spec_helper"
describe Fauxhai::Mocker do
describe "#data" do
let(:options) { {} }
subject { described_class.new({ github_fetching: false }.merge(options)).data }
context "with a platform and version" do
let(:options) { { platform: "chefspec", version: "0.6.1" } }
its(["hostname"]) { is_expected.to eq "chefspec" }
end
context "with a Windows platform and version" do
let(:options) { { platform: "windows", version: "10" } }
its(["hostname"]) { is_expected.to eq "Fauxhai" }
end
end
describe "#version" do
let(:options) { {} }
subject { described_class.new({ github_fetching: false }.merge(options)).send(:version) }
context "with a platform and version" do
let(:options) { { platform: "chefspec", version: "0.6.1" } }
it { is_expected.to eq "0.6.1" }
end
context "with a platform and no version" do
let(:options) { { platform: "chefspec" } }
it { is_expected.to eq "0.6.1" }
end
context "with a platform and a blank version" do
let(:options) { { platform: "chefspec", version: "" } }
it { is_expected.to eq "0.6.1" }
end
context "with a platform and a partial version" do
let(:options) { { platform: "chefspec", version: "0.6" } }
it { is_expected.to eq "0.6.1" }
end
context "with a platform and a non-matching partial version" do
let(:options) { { platform: "chefspec", version: "0.7" } }
it { is_expected.to eq "0.7" }
end
context "with a Windows platform and no version" do
let(:options) { { platform: "windows" } }
it { is_expected.to eq "2019" }
end
context "with a Windows platform and an exact partial version" do
let(:options) { { platform: "windows", version: "2012" } }
it { is_expected.to eq "2012" }
end
context "with a CentOS platform and a partial version" do
let(:options) { { platform: "centos", version: "6" } }
it { is_expected.to eq "6.10" }
end
context "with a platform and an invalid version" do
let(:options) { { platform: "chefspec", version: "99" } }
it { is_expected.to eq "99" }
end
context "with an invalid platform and an invalid version" do
let(:options) { { platform: "notthere", version: "99" } }
it { is_expected.to eq "99" }
end
end
end
| ruby | MIT | 86a0ac4d5ab91f249801ffa290ae39a58d99b6b4 | 2026-01-04T17:45:47.766557Z | false |
chefspec/fauxhai | https://github.com/chefspec/fauxhai/blob/86a0ac4d5ab91f249801ffa290ae39a58d99b6b4/lib/fauxhai.rb | lib/fauxhai.rb | module Fauxhai
autoload :Exception, "fauxhai/exception"
autoload :Fetcher, "fauxhai/fetcher"
autoload :Mocker, "fauxhai/mocker"
autoload :VERSION, "fauxhai/version"
def self.root
@@root ||= File.expand_path("../../", __FILE__)
end
def self.mock(*args, &block)
Fauxhai::Mocker.new(*args, &block)
end
def self.fetch(*args, &block)
Fauxhai::Fetcher.new(*args, &block)
end
end
| ruby | MIT | 86a0ac4d5ab91f249801ffa290ae39a58d99b6b4 | 2026-01-04T17:45:47.766557Z | false |
chefspec/fauxhai | https://github.com/chefspec/fauxhai/blob/86a0ac4d5ab91f249801ffa290ae39a58d99b6b4/lib/fauxhai/version.rb | lib/fauxhai/version.rb | module Fauxhai
VERSION = "9.3.0".freeze
end
| ruby | MIT | 86a0ac4d5ab91f249801ffa290ae39a58d99b6b4 | 2026-01-04T17:45:47.766557Z | false |
chefspec/fauxhai | https://github.com/chefspec/fauxhai/blob/86a0ac4d5ab91f249801ffa290ae39a58d99b6b4/lib/fauxhai/fetcher.rb | lib/fauxhai/fetcher.rb | require "digest/sha1"
require "json" unless defined?(JSON)
module Fauxhai
class Fetcher
def initialize(options = {}, &override_attributes)
@options = options
if !force_cache_miss? && cached?
@data = cache
else
require "net/ssh" unless defined?(Net::SSH)
Net::SSH.start(host, user, @options) do |ssh|
@data = JSON.parse(ssh.exec!("ohai"))
end
# cache this data so we do not have to SSH again
File.open(cache_file, "w+") { |f| f.write(@data.to_json) }
end
yield(@data) if block_given?
if defined?(ChefSpec)
data = @data
::ChefSpec::Runner.send :define_method, :fake_ohai do |ohai|
data.each_pair do |attribute, value|
ohai[attribute] = value
end
end
end
@data
end
def cache
@cache ||= JSON.parse(File.read(cache_file))
end
def cached?
File.exist?(cache_file)
end
def cache_key
Digest::SHA2.hexdigest("#{user}@#{host}")
end
def cache_file
File.expand_path(File.join(Fauxhai.root, "tmp", cache_key))
end
def force_cache_miss?
@force_cache_miss ||= @options.delete(:force_cache_miss) || false
end
# Return the given `@data` attribute as a Ruby hash instead of a JSON object
#
# @return [Hash] the `@data` represented as a Ruby hash
def to_hash(*args)
@data.to_hash(*args)
end
def to_s
"#<Fauxhai::Fetcher @host=#{host}, @options=#{@options}>"
end
private
def host
@host ||= begin
raise ArgumentError, ":host is a required option for Fauxhai.fetch" unless @options[:host]
@options.delete(:host)
end
end
def user
@user ||= (@options.delete(:user) || ENV["USER"] || ENV["USERNAME"]).chomp
end
end
end
| ruby | MIT | 86a0ac4d5ab91f249801ffa290ae39a58d99b6b4 | 2026-01-04T17:45:47.766557Z | false |
chefspec/fauxhai | https://github.com/chefspec/fauxhai/blob/86a0ac4d5ab91f249801ffa290ae39a58d99b6b4/lib/fauxhai/exception.rb | lib/fauxhai/exception.rb | module Fauxhai
module Exception
class InvalidPlatform < ArgumentError; end
class InvalidVersion < ArgumentError; end
end
end
| ruby | MIT | 86a0ac4d5ab91f249801ffa290ae39a58d99b6b4 | 2026-01-04T17:45:47.766557Z | false |
chefspec/fauxhai | https://github.com/chefspec/fauxhai/blob/86a0ac4d5ab91f249801ffa290ae39a58d99b6b4/lib/fauxhai/runner.rb | lib/fauxhai/runner.rb | require "ohai" unless defined?(Ohai::System)
require "ohai/plugins/chef"
module Fauxhai
class Runner
def initialize(args)
@system = Ohai::System.new
@system.all_plugins
case @system.data["platform"]
when "windows", :windows
require_relative "runner/windows"
singleton_class.send :include, ::Fauxhai::Runner::Windows
else
require_relative "runner/default"
singleton_class.send :include, ::Fauxhai::Runner::Default
end
result = @system.data.dup.delete_if { |k, v| !whitelist_attributes.include?(k) }.merge(
"languages" => languages,
"counters" => counters,
"current_user" => current_user,
"domain" => domain,
"hostname" => hostname,
"machinename" => hostname,
"fqdn" => fqdn,
"ipaddress" => ipaddress,
"keys" => keys,
"macaddress" => macaddress,
"network" => network,
"uptime" => uptime,
"uptime_seconds" => uptime_seconds,
"idle" => uptime,
"idletime_seconds" => uptime_seconds,
"cpu" => cpu,
"memory" => memory,
"virtualization" => virtualization,
"time" => time
)
require "json" unless defined?(JSON)
puts JSON.pretty_generate(result.sort.to_h)
end
end
end
| ruby | MIT | 86a0ac4d5ab91f249801ffa290ae39a58d99b6b4 | 2026-01-04T17:45:47.766557Z | false |
chefspec/fauxhai | https://github.com/chefspec/fauxhai/blob/86a0ac4d5ab91f249801ffa290ae39a58d99b6b4/lib/fauxhai/mocker.rb | lib/fauxhai/mocker.rb | require "json" unless defined?(JSON)
require "pathname" unless defined?(Pathname)
module Fauxhai
class Mocker
# The base URL for the GitHub project (raw)
RAW_BASE = "https://raw.githubusercontent.com/chefspec/fauxhai/master".freeze
# A message about where to find a list of platforms
PLATFORM_LIST_MESSAGE = "A list of available platforms is available at https://github.com/chefspec/fauxhai/blob/master/PLATFORMS.md".freeze
# Create a new Ohai Mock with fauxhai.
#
# @param [Hash] options
# the options for the mocker
# @option options [String] :platform
# the platform to mock
# @option options [String] :version
# the version of the platform to mock
# @option options [String] :path
# the path to a local JSON file
# @option options [Bool] :github_fetching
# whether to try loading from Github
def initialize(options = {}, &override_attributes)
@options = { github_fetching: true }.merge(options)
yield(data) if block_given?
end
def data
@fauxhai_data ||= lambda do
# If a path option was specified, use it
if @options[:path]
filepath = File.expand_path(@options[:path])
unless File.exist?(filepath)
raise Fauxhai::Exception::InvalidPlatform.new("You specified a path to a JSON file on the local system that does not exist: '#{filepath}'")
end
else
filepath = File.join(platform_path, "#{version}.json")
end
if File.exist?(filepath)
parse_and_validate(File.read(filepath))
elsif @options[:github_fetching]
# Try loading from github (in case someone submitted a PR with a new file, but we haven't
# yet updated the gem version). Cache the response locally so it's faster next time.
require "open-uri" unless defined?(OpenURI)
begin
response = URI.open("#{RAW_BASE}/lib/fauxhai/platforms/#{platform}/#{version}.json")
rescue OpenURI::HTTPError
raise Fauxhai::Exception::InvalidPlatform.new("Could not find platform '#{platform}/#{version}' on the local disk and an HTTP error was encountered when fetching from Github. #{PLATFORM_LIST_MESSAGE}")
end
if response.status.first.to_i == 200
response_body = response.read
path = Pathname.new(filepath)
FileUtils.mkdir_p(path.dirname)
begin
File.open(filepath, "w") { |f| f.write(response_body) }
rescue Errno::EACCES # a pretty common problem in CI systems
puts "Fetched '#{platform}/#{version}' from GitHub, but could not write to the local path: #{filepath}. Fix the local file permissions to avoid downloading this file every run."
end
return parse_and_validate(response_body)
else
raise Fauxhai::Exception::InvalidPlatform.new("Could not find platform '#{platform}/#{version}' on the local disk and an Github fetching returned http error code #{response.status.first.to_i}! #{PLATFORM_LIST_MESSAGE}")
end
else
raise Fauxhai::Exception::InvalidPlatform.new("Could not find platform '#{platform}/#{version}' on the local disk and Github fetching is disabled! #{PLATFORM_LIST_MESSAGE}")
end
end.call
end
private
# As major releases of Ohai ship it's difficult and sometimes impossible
# to regenerate all fauxhai data. This allows us to deprecate old releases
# and eventually remove them while giving end users ample warning.
def parse_and_validate(unparsed_data)
parsed_data = JSON.parse(unparsed_data)
if parsed_data["deprecated"]
STDERR.puts "WARNING: Fauxhai platform data for #{parsed_data["platform"]} #{parsed_data["platform_version"]} is deprecated and will be removed in the 10.0 release 3/2022. #{PLATFORM_LIST_MESSAGE}"
end
parsed_data
end
def platform
@options[:platform] ||= begin
STDERR.puts "WARNING: you must specify a 'platform' and optionally a 'version' for your ChefSpec Runner and/or Fauxhai constructor, in the future omitting the platform will become a hard error. #{PLATFORM_LIST_MESSAGE}"
"chefspec"
end
end
def platform_path
File.join(Fauxhai.root, "lib", "fauxhai", "platforms", platform)
end
def version
@version ||= begin
if File.exist?("#{platform_path}/#{@options[:version]}.json")
# Whole version, use it as-is.
@options[:version]
else
# Check if it's a prefix of an existing version.
versions = Dir["#{platform_path}/*.json"].map { |path| File.basename(path, ".json") }
unless @options[:version].to_s == ""
# If the provided version is nil or '', that means take anything,
# otherwise run the prefix match with an extra \D to avoid the
# case where "7.1" matches "7.10.0".
prefix_re = /^#{Regexp.escape(@options[:version])}\D/
versions.select! { |ver| ver =~ prefix_re }
end
if versions.empty?
# No versions available, either an unknown platform or nothing matched
# the prefix check. Pass through the option as given so we can try
# github fetching.
@options[:version]
else
# Take the highest version available, trying to use rules that should
# probably mostly work on all OSes. Famous last words. The idea of
# the regex is to split on any punctuation (the common case) and
# also any single letter with digit on either side (2012r2). This
# leaves any long runs of letters intact (4.2-RELEASE). Then convert
# any run of digits to an integer to get version-ish comparison.
# This is basically a more flexible version of Gem::Version.
versions.max_by do |ver|
ver.split(/[^a-z0-9]|(?<=\d)[a-z](?=\d)/i).map do |part|
if part =~ /^\d+$/
part.to_i
else
part
end
end
end
end
end
end
end
end
end
| ruby | MIT | 86a0ac4d5ab91f249801ffa290ae39a58d99b6b4 | 2026-01-04T17:45:47.766557Z | false |
chefspec/fauxhai | https://github.com/chefspec/fauxhai/blob/86a0ac4d5ab91f249801ffa290ae39a58d99b6b4/lib/fauxhai/runner/default.rb | lib/fauxhai/runner/default.rb | module Fauxhai
class Runner
module Default
def bin_dir
"/usr/local/bin"
end
def counters
{
"network" => {
"interfaces" => {
"lo" => {
"tx" => {
"queuelen" => "1",
"bytes" => 0,
"packets" => 0,
"errors" => 0,
"drop" => 0,
"carrier" => 0,
"collisions" => 0,
},
"rx" => {
"bytes" => 0,
"packets" => 0,
"errors" => 0,
"drop" => 0,
"overrun" => 0,
},
},
default_interface.to_s => {
"rx" => {
"bytes" => 0,
"packets" => 0,
"errors" => 0,
"drop" => 0,
"overrun" => 0,
"frame" => 0,
"compressed" => 0,
"multicast" => 0,
},
"tx" => {
"bytes" => 0,
"packets" => 0,
"errors" => 0,
"drop" => 0,
"overrun" => 0,
"collisions" => 0,
"carrier" => 0,
"compressed" => 0,
},
},
},
},
}
end
def current_user
"fauxhai"
end
def default_gateway
"10.0.0.1"
end
def default_interface
case @system.data["platform_family"]
when "mac_os_x"
"en0"
when /bsd/
"em0"
when "arch", "fedora"
"enp0s3"
else
"eth0"
end
end
def domain
"local"
end
def fqdn
"fauxhai.local"
end
def gem_bin
"/usr/local/bin/gem"
end
def gems_dir
"/usr/local/gems"
end
def hostname
"Fauxhai"
end
def ipaddress
"10.0.0.2"
end
def ip6address
"fe80:0:0:0:0:0:a00:2"
end
def keys
{
"ssh" => ssh,
}
end
def languages
{
"ruby" => @system.data["languages"]["ruby"].merge("bin_dir" => bin_dir,
"gem_bin" => gem_bin,
"gems_dir" => gems_dir,
"ruby_bin" => ruby_bin),
"powershell" => @system.data["languages"]["powershell"],
}
end
def macaddress
"11:11:11:11:11:11"
end
def network
{
"interfaces" => {
"lo" => {
"mtu" => "65536",
"flags" => %w{LOOPBACK UP LOWER_UP},
"encapsulation" => "Loopback",
"addresses" => {
"127.0.0.1" => {
"family" => "inet",
"prefixlen" => "8",
"netmask" => "255.0.0.0",
"scope" => "Node",
"ip_scope" => "LOOPBACK",
},
"::1" => {
"family" => "inet6",
"prefixlen" => "128",
"scope" => "Node",
"tags" => [],
"ip_scope" => "LINK LOCAL LOOPBACK",
},
},
"state" => "unknown",
},
default_interface.to_s => {
"type" => default_interface.chop,
"number" => "0",
"mtu" => "1500",
"flags" => %w{BROADCAST MULTICAST UP LOWER_UP},
"encapsulation" => "Ethernet",
"addresses" => {
macaddress.to_s => {
"family" => "lladdr",
},
ipaddress.to_s => {
"family" => "inet",
"prefixlen" => "24",
"netmask" => "255.255.255.0",
"broadcast" => "10.0.0.255",
"scope" => "Global",
"ip_scope" => "RFC1918 PRIVATE",
},
"fe80::11:1111:1111:1111" => {
"family" => "inet6",
"prefixlen" => "64",
"scope" => "Link",
"tags" => [],
"ip_scope" => "LINK LOCAL UNICAST",
},
},
"state" => "up",
"arp" => {
"10.0.0.1" => "fe:ff:ff:ff:ff:ff",
},
"routes" => [
{
"destination" => "default",
"family" => "inet",
"via" => default_gateway,
},
{
"destination" => "10.0.0.0/24",
"family" => "inet",
"scope" => "link",
"proto" => "kernel",
"src" => ipaddress,
},
{
"destination" => "fe80::/64",
"family" => "inet6",
"metric" => "256",
"proto" => "kernel",
},
],
"ring_params" => {},
},
},
"default_interface" => default_interface,
"default_gateway" => default_gateway,
}
end
def ruby_bin
"/usr/local/bin/ruby"
end
def ssh
{
"host_dsa_public" => File.read(File.join(Fauxhai.root, "lib", "fauxhai", "keys", "id_dsa.pub")).strip,
"host_rsa_public" => File.read(File.join(Fauxhai.root, "lib", "fauxhai", "keys", "id_rsa.pub")).strip,
}
end
def uptime
"30 days 15 hours 07 minutes 30 seconds"
end
def uptime_seconds
2646450
end
def cpu
{
"real" => 1,
"total" => 1,
"cores" => 1,
}
end
def memory
{
"total" => "1048576kB",
}
end
def virtualization
{
"systems" => {},
}
end
def time
{
"timezone" => "GMT",
}
end
# Whitelist attributes are attributes that we *actually* want from the node. Other attributes are
# either ignored or overridden, but we ensure these are returned with the command.
#
# @return [Array] - the key of whitelisted attributes
def whitelist_attributes
%w{
block_device
chef_packages
command
dmi
filesystem
fips
init_package
kernel
lsb
ohai_time
os
os_version
packages
platform
platform_version
platform_build
platform_family
root_group
shard_seed
shells
}
end
end
end
end
| ruby | MIT | 86a0ac4d5ab91f249801ffa290ae39a58d99b6b4 | 2026-01-04T17:45:47.766557Z | false |
chefspec/fauxhai | https://github.com/chefspec/fauxhai/blob/86a0ac4d5ab91f249801ffa290ae39a58d99b6b4/lib/fauxhai/runner/windows.rb | lib/fauxhai/runner/windows.rb | module Fauxhai
class Runner
module Windows
require_relative "default"
include ::Fauxhai::Runner::Default
def default_interface
"0xe"
end
def network
{
"interfaces" => {
"#{default_interface}" => {
"configuration" => {
"caption" => "[00000012] Ethernet Adapter",
"database_path" => '%SystemRoot%\\System32\\drivers\\etc',
"default_ip_gateway" => %w{default_gateway},
"description" => "Ethernet Adapter",
"dhcp_enabled" => false,
"dns_domain_suffix_search_order" => [],
"dns_enabled_for_wins_resolution" => false,
"dns_host_name" => hostname,
"domain_dns_registration_enabled" => false,
"full_dns_registration_enabled" => true,
"gateway_cost_metric" => [0],
"index" => 12,
"interface_index" => 14,
"ip_address" => [ipaddress],
"ip_connection_metric" => 5,
"ip_enabled" => true,
"ip_filter_security_enabled" => false,
"ip_sec_permit_ip_protocols" => [],
"ip_sec_permit_tcp_ports" => [],
"ip_sec_permit_udp_ports" => [],
"ip_subnet" => %w{255.255.255.0 64},
"mac_address" => macaddress,
"service_name" => "netkvm",
"setting_id" => "{00000000-0000-0000-0000-000000000000}",
"tcpip_netbios_options" => 0,
"tcp_window_size" => 64240,
"wins_enable_lm_hosts_lookup" => true,
"wins_scope_id" => "",
},
"instance" => {
"adapter_type" => "Ethernet 802.3",
"adapter_type_id" => 0,
"availability" => 3,
"caption" => "[00000012] Ethernet Adapter",
"config_manager_error_code" => 0,
"config_manager_user_config" => false,
"creation_class_name" => "Win32_NetworkAdapter",
"description" => "Ethernet Adapter",
"device_id" => "12",
"guid" => "{00000000-0000-0000-0000-000000000000}",
"index" => 12,
"installed" => true,
"interface_index" => 14,
"mac_address" => macaddress,
"manufacturer" => "",
"max_number_controlled" => 0,
"name" => "Ethernet Adapter",
"net_connection_id" => "Ethernet",
"net_connection_status" => 2,
"net_enabled" => true,
"physical_adapter" => true,
"pnp_device_id" => 'PCI\\VEN_0000&DEV_0000&SUBSYS_000000000&REV_00\\0&0000000000&00',
"power_management_supported" => false,
"product_name" => "Ethernet Adapter",
"service_name" => "netkvm",
"speed" => "10000000000",
"system_creation_class_name" => "Win32_ComputerSystem",
"system_name" => hostname,
"time_of_last_reset" => "20000101000001.000000+000",
},
"counters" => {},
"addresses" => {
"#{ipaddress}" => {
"prefixlen" => "24",
"netmask" => "255.255.255.0",
"broadcast" => "10.0.0.255",
"family" => "inet",
},
"#{macaddress}" => {
"family" => "lladdr",
},
},
"type" => "Ethernet 802.3",
"arp" => {
"10.0.0.1" => "fe:ff:ff:ff:ff:ff",
},
"encapsulation" => "Ethernet",
},
},
"default_gateway" => default_gateway,
"default_interface" => default_interface,
}
end
end
end
end
| ruby | MIT | 86a0ac4d5ab91f249801ffa290ae39a58d99b6b4 | 2026-01-04T17:45:47.766557Z | false |
n8/tracer_bullets | https://github.com/n8/tracer_bullets/blob/e1a304940910b51f5029a7e83aee4e1dd29b7034/lib/tracer_bullets.rb | lib/tracer_bullets.rb | require "tracer_bullets/version"
module TracerBullets
module Methods
def tracer_bullet
if Rails.env.development?
_tracer_bullets_log( "Elapsed: #{((Time.now - @tracer_bullet_start_time)*1000).to_i}ms #{caller(0)[1]}" )
@tracer_bullet_start_time = Time.now
end
end
alias_method :tb, :tracer_bullet
private
def _tracer_bullets_log(msg)
log = Rails.logger
if defined?(ActiveSupport::TaggedLogging)
log.tagged("TracerBullets") { |l| l.debug(msg) }
else
log.debug(msg)
end
end
end
module Controller
extend ActiveSupport::Concern
include Methods
included do
before_filter :setup_tracer_bullet_start_time
end
def setup_tracer_bullet_start_time
@tracer_bullet_start_time = Time.now
end
end
module View
extend ActiveSupport::Concern
include Methods
end
class Railtie < Rails::Railtie
initializer "tracer_bullet.action_controller" do
ActiveSupport.on_load(:action_controller) do
include TracerBullets::Controller
end
end
initializer "tracer_bullet.action_view" do
ActiveSupport.on_load(:action_view) do
include TracerBullets::View
end
end
end
end
| ruby | MIT | e1a304940910b51f5029a7e83aee4e1dd29b7034 | 2026-01-04T17:46:14.711660Z | false |
n8/tracer_bullets | https://github.com/n8/tracer_bullets/blob/e1a304940910b51f5029a7e83aee4e1dd29b7034/lib/tracer_bullets/version.rb | lib/tracer_bullets/version.rb | module TracerBullets
VERSION = "0.0.5"
end
| ruby | MIT | e1a304940910b51f5029a7e83aee4e1dd29b7034 | 2026-01-04T17:46:14.711660Z | false |
hyperoslo/capistrano-foreman | https://github.com/hyperoslo/capistrano-foreman/blob/4c08afc005de4f04000e7678b781671cb4360c56/lib/capistrano-foreman.rb | lib/capistrano-foreman.rb | ruby | MIT | 4c08afc005de4f04000e7678b781671cb4360c56 | 2026-01-04T17:46:13.153110Z | false | |
hyperoslo/capistrano-foreman | https://github.com/hyperoslo/capistrano-foreman/blob/4c08afc005de4f04000e7678b781671cb4360c56/lib/capistrano/foreman.rb | lib/capistrano/foreman.rb | load File.expand_path('../tasks/foreman.rb', __FILE__)
| ruby | MIT | 4c08afc005de4f04000e7678b781671cb4360c56 | 2026-01-04T17:46:13.153110Z | false |
hyperoslo/capistrano-foreman | https://github.com/hyperoslo/capistrano-foreman/blob/4c08afc005de4f04000e7678b781671cb4360c56/lib/capistrano/tasks/foreman.rb | lib/capistrano/tasks/foreman.rb | namespace :foreman do
task :setup do
invoke :'foreman:export'
invoke :'foreman:start'
end
desc 'Export the Procfile'
task :export do
on roles fetch(:foreman_roles) do
opts = {
app: fetch(:application),
log: File.join(shared_path, 'log'),
}.merge fetch(:foreman_options, {})
opts.merge!(host.properties.fetch(:foreman_options) || {})
execute(:mkdir, "-p", opts[:log])
within release_path do
foreman_exec :foreman, 'export',
fetch(:foreman_init_system),
fetch(:foreman_export_path),
opts.map { |opt, value| "--#{opt}=\"#{value}\"" }.join(' ')
end
if fetch(:foreman_init_system) == 'systemd'
foreman_exec :systemctl, :'daemon-reload'
end
end
end
desc 'Start the application services'
task :start do
on roles fetch(:foreman_roles) do
case fetch(:foreman_init_system)
when 'systemd'
foreman_exec :systemctl, :enable, fetch(:foreman_app_name_systemd)
foreman_exec :systemctl, :start, fetch(:foreman_app_name_systemd)
else
foreman_exec :start, fetch(:foreman_app)
end
end
end
desc 'Stop the application services'
task :stop do
on roles fetch(:foreman_roles) do
case fetch(:foreman_init_system)
when 'systemd'
foreman_exec :systemctl, :stop, fetch(:foreman_app_name_systemd)
foreman_exec :systemctl, :disable, fetch(:foreman_app_name_systemd)
else
foreman_exec :stop, fetch(:foreman_app)
end
end
end
desc 'Restart the application services'
task :restart do
on roles fetch(:foreman_roles) do
case fetch(:foreman_init_system)
when 'systemd'
foreman_exec :systemctl, :restart, fetch(:foreman_app_name_systemd)
else
foreman_exec :restart, fetch(:foreman_app)
end
end
end
def foreman_exec(*args)
sudo_type = fetch(:foreman_use_sudo)
case sudo_type.to_s
when 'rbenv'
# this is required because 'rbenv sudo'
# is not recognized by bundle_bins
args.unshift(:bundle, :exec) if args[0].to_s == "foreman"
execute(:rbenv, :sudo, *args)
when 'rvm'
execute(:rvmsudo, *args)
when 'chruby'
execute(:sudo, 'chruby-exec', fetch(:chruby_ruby), '--', *args)
else
sudo_type ? sudo(*args) : execute(*args)
end
end
end
namespace :load do
task :defaults do
set :bundle_bins, fetch(:bundle_bins, []).push(:foreman)
set :foreman_use_sudo, false
set :foreman_init_system, 'upstart'
set :foreman_export_path, '/etc/init/sites'
set :foreman_roles, :all
set :foreman_app, -> { fetch(:application) }
set :foreman_app_name_systemd, -> { "#{ fetch(:foreman_app) }.target" }
if !fetch(:rvm_map_bins).nil?
set :rvm_map_bins, fetch(:rvm_map_bins).push('foreman')
end
end
end
| ruby | MIT | 4c08afc005de4f04000e7678b781671cb4360c56 | 2026-01-04T17:46:13.153110Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/spec/coverage_helper.rb | spec/coverage_helper.rb | # frozen_string_literal: true
require "simplecov"
require "simplecov-rcov"
# return non-zero if not met
SimpleCov.at_exit do
SimpleCov.minimum_coverage 100
SimpleCov.result.format!
end
SimpleCov.start do
add_filter "lib/simple_scheduler/railtie"
add_filter "/spec/"
end
# Format the reports in a way I like
SimpleCov.formatter = SimpleCov::Formatter::RcovFormatter
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/spec/rails_helper.rb | spec/rails_helper.rb | # frozen_string_literal: true
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= "test"
require "coverage_helper"
require File.expand_path("../spec/dummy/config/environment.rb", __dir__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require "spec_helper"
require "rspec/rails"
require "sidekiq/testing"
RSpec.configure do |config|
config.include ActiveJob::TestHelper
config.include ActiveSupport::Testing::Assertions
config.include ActiveSupport::Testing::TimeHelpers
config.filter_rails_from_backtrace!
ActiveJob::Base.logger = Rails.logger
end
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/spec/spec_helper.rb | spec/spec_helper.rb | # frozen_string_literal: true
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
# This option will default to `:apply_to_host_groups` in RSpec 4 (and will
# have no way to turn it off -- the option exists only for backwards
# compatibility in RSpec 3). It causes shared context metadata to be
# inherited by the metadata hash of host groups and examples, rather than
# triggering implicit auto-inclusion in groups with matching metadata.
config.shared_context_metadata_behavior = :apply_to_host_groups
end
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/spec/simple_scheduler/scheduler_job_spec.rb | spec/simple_scheduler/scheduler_job_spec.rb | # frozen_string_literal: true
require "rails_helper"
describe SimpleScheduler::SchedulerJob, type: :job do
let(:now) { Time.parse("2017-01-27 00:00:00 CST") }
# Set the environment variable for a custom YAML configuration file.
# @param path [String]
def config_path(path)
stub_const("ENV", ENV.to_hash.merge("SIMPLE_SCHEDULER_CONFIG" => path))
end
describe "successfully queues" do
subject(:job) { described_class.perform_later }
it "queues the job" do
expect { job }.to change(enqueued_jobs, :size).by(1)
end
it "is in default queue" do
expect(described_class.new.queue_name).to eq("default")
end
end
describe "scheduling tasks without specifying a config path" do
it "queues the jobs loaded from config/simple_scheduler.yml" do
travel_to(now) do
expect do
described_class.perform_now
end.to change(enqueued_jobs, :size).by(4)
end
end
end
describe "Sidekiq queue name" do
it "uses 'default' as the queue name if `queue_name` isn't set in the config" do
travel_to(now) do
described_class.perform_now
expect(enqueued_jobs.first[:queue]).to eq("default")
end
end
it "uses the custom queue name from the config file when adding FutureJob" do
config_path("spec/simple_scheduler/config/custom_queue_name.yml")
travel_to(now) do
described_class.perform_now
expect(enqueued_jobs.first[:queue]).to eq("custom")
end
end
end
describe "loading a YML file with ERB tags" do
it "parses the file and queues the jobs" do
config_path("spec/simple_scheduler/config/erb_test.yml")
travel_to(now) do
expect do
described_class.perform_now
end.to change(enqueued_jobs, :size).by(2)
end
end
end
describe "scheduling an hourly task" do
it "queues jobs for at least six hours into the future by default" do
config_path("spec/simple_scheduler/config/hourly_task.yml")
travel_to(now) do
expect do
described_class.perform_now
end.to change(enqueued_jobs, :size).by(7)
end
end
it "respects the queue_ahead global option" do
config_path("spec/simple_scheduler/config/queue_ahead_global.yml")
travel_to(now) do
expect do
described_class.perform_now
end.to change(enqueued_jobs, :size).by(3)
end
end
it "respects the queue_ahead option per task" do
config_path("spec/simple_scheduler/config/queue_ahead_per_task.yml")
travel_to(now) do
expect do
described_class.perform_now
end.to change(enqueued_jobs, :size).by(4)
end
end
end
describe "scheduling a weekly task" do
it "always queues two future jobs" do
config_path("spec/simple_scheduler/config/active_job.yml")
travel_to(now) do
expect do
described_class.perform_now
end.to change(enqueued_jobs, :size).by(2)
end
end
end
end
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/spec/simple_scheduler/task_spec.rb | spec/simple_scheduler/task_spec.rb | # frozen_string_literal: true
require "rails_helper"
describe SimpleScheduler::Task, type: :model do
describe "initialize" do
it "requires the `class` param" do
expect do
described_class.new(every: "10.minutes")
end.to raise_error(ArgumentError, "Missing param `class` specifying the class of the job to run.")
end
it "requires the `every` param" do
expect do
described_class.new(class: "TestJob")
end.to raise_error(ArgumentError, "Missing param `every` specifying how often the job should run.")
end
end
describe "existing_jobs" do
let(:task) do
described_class.new(
class: "TestJob",
every: "1.hour",
name: "test_task"
)
end
let(:sidekiq_entry_matching_class_and_name) do
Sidekiq::SortedEntry.new(
nil,
1,
"wrapped" => "SimpleScheduler::FutureJob",
"class" => "ActiveJob::QueueAdapters::SidekiqAdapter::JobWrapper",
"args" => [{ "arguments" => [{ "class" => "TestJob", "name" => "test_task" }] }]
)
end
let(:sidekiq_entry_matching_class_wrong_task_name) do
Sidekiq::SortedEntry.new(
nil,
1,
"wrapped" => "SimpleScheduler::FutureJob",
"class" => "ActiveJob::QueueAdapters::SidekiqAdapter::JobWrapper",
"args" => [{ "arguments" => [{ "class" => "TestJob", "name" => "wrong_task" }] }]
)
end
let(:sidekiq_entry_wrong_class) do
Sidekiq::SortedEntry.new(
nil,
1,
"wrapped" => "SimpleScheduler::FutureJob",
"class" => "ActiveJob::QueueAdapters::SidekiqAdapter::JobWrapper",
"args" => [{ "arguments" => [{ "class" => "SomeOtherJob", "name" => "test_task" }] }]
)
end
it "returns an array of Sidekiq entries for existing jobs" do
expect(described_class).to receive(:scheduled_set).and_return([
sidekiq_entry_matching_class_and_name,
sidekiq_entry_matching_class_and_name
])
expect(task.existing_jobs.length).to eq(2)
end
it "only returns Sidekiq entries for the task's job class" do
expect(described_class).to receive(:scheduled_set).and_return([
sidekiq_entry_matching_class_and_name,
sidekiq_entry_wrong_class
])
expect(task.existing_jobs.length).to eq(1)
end
it "only returns Sidekiq entries for the task's name (key used for the YAML block)" do
expect(described_class).to receive(:scheduled_set).and_return([
sidekiq_entry_matching_class_and_name,
sidekiq_entry_matching_class_wrong_task_name
])
expect(task.existing_jobs.length).to eq(1)
end
it "returns an empty array if there are no existing jobs" do
expect(described_class).to receive(:scheduled_set).and_return([
sidekiq_entry_wrong_class,
sidekiq_entry_wrong_class
])
expect(task.existing_jobs.length).to eq(0)
end
end
describe "existing_run_times" do
let(:task) do
described_class.new(
class: "TestJob",
every: "1.hour",
name: "test_task"
)
end
let(:future_time1) { (Time.now + 1.hour).beginning_of_minute }
let(:future_time2) { (Time.now + 2.hours).beginning_of_minute }
it "returns an array of existing future run times for the task's job" do
expect(described_class).to receive(:scheduled_set).and_return([
Sidekiq::SortedEntry.new(
nil,
future_time1.to_i,
"wrapped" => "SimpleScheduler::FutureJob",
"class" => "ActiveJob::QueueAdapters::SidekiqAdapter::JobWrapper",
"args" => [{ "arguments" => [{ "class" => "TestJob", "name" => "test_task" }] }]
),
Sidekiq::SortedEntry.new(
nil,
future_time2.to_i,
"wrapped" => "SimpleScheduler::FutureJob",
"class" => "ActiveJob::QueueAdapters::SidekiqAdapter::JobWrapper",
"args" => [{ "arguments" => [{ "class" => "TestJob", "name" => "test_task" }] }]
)
])
expect(task.existing_run_times).to eq([future_time1, future_time2])
end
it "only returns times for the task's job class" do
expect(described_class).to receive(:scheduled_set).and_return([
Sidekiq::SortedEntry.new(
nil,
future_time1.to_i,
"wrapped" => "SimpleScheduler::FutureJob",
"class" => "ActiveJob::QueueAdapters::SidekiqAdapter::JobWrapper",
"args" => [{ "arguments" => [{ "class" => "TestJob", "name" => "test_task" }] }]
),
Sidekiq::SortedEntry.new(
nil,
future_time2.to_i,
"wrapped" => "SimpleScheduler::FutureJob",
"class" => "ActiveJob::QueueAdapters::SidekiqAdapter::JobWrapper",
"args" => [{ "arguments" => [{ "class" => "SomeOtherJob", "name" => "test_task" }] }]
)
])
expect(task.existing_run_times).to eq([future_time1])
end
it "only returns times for the task's job class and task name" do
expect(described_class).to receive(:scheduled_set).and_return([
Sidekiq::SortedEntry.new(
nil,
future_time1.to_i,
"wrapped" => "SimpleScheduler::FutureJob",
"class" => "ActiveJob::QueueAdapters::SidekiqAdapter::JobWrapper",
"args" => [{ "arguments" => [{ "class" => "TestJob", "name" => "test_task" }] }]
),
Sidekiq::SortedEntry.new(
nil,
future_time2.to_i,
"wrapped" => "SimpleScheduler::FutureJob",
"class" => "ActiveJob::QueueAdapters::SidekiqAdapter::JobWrapper",
"args" => [{ "arguments" => [{ "class" => "TestJob", "name" => "wrong_task" }] }]
)
])
expect(task.existing_run_times).to eq([future_time1])
end
it "returns an empty array if there are no times" do
expect(described_class).to receive(:scheduled_set).and_return([
Sidekiq::SortedEntry.new(
nil,
future_time1.to_i,
"wrapped" => "SimpleScheduler::FutureJob",
"class" => "ActiveJob::QueueAdapters::SidekiqAdapter::JobWrapper",
"args" => [{ "arguments" => [{ "class" => "SomeOtherJob", "name" => "test_task" }] }]
),
Sidekiq::SortedEntry.new(
nil,
future_time2.to_i,
"wrapped" => "SimpleScheduler::FutureJob",
"class" => "ActiveJob::QueueAdapters::SidekiqAdapter::JobWrapper",
"args" => [{ "arguments" => [{ "class" => "SomeOtherJob", "name" => "test_task" }] }]
)
])
expect(task.existing_run_times).to eq([])
end
end
describe "future_run_times" do
context "when creating a weekly task" do
let(:task) do
described_class.new(
class: "TestJob",
every: "1.week",
at: "0:00",
queue_ahead: 10,
tz: "America/Chicago"
)
end
it "returns at least the next two future times the job should be run" do
travel_to Time.parse("2016-12-01 1:00:00 CST") do
expect(task.future_run_times).to eq([
Time.parse("2016-12-02 0:00:00 CST"),
Time.parse("2016-12-09 0:00:00 CST")
])
end
end
it "uses queue_ahead to ensure jobs are queued into the future" do
travel_to Time.parse("2016-12-01 20:00:00 CST") do
task.instance_variable_set(:@queue_ahead, 50_400) # 5 weeks
expect(task.future_run_times).to eq([
Time.parse("2016-12-02 0:00:00 CST"),
Time.parse("2016-12-09 0:00:00 CST"),
Time.parse("2016-12-16 0:00:00 CST"),
Time.parse("2016-12-23 0:00:00 CST"),
Time.parse("2016-12-30 0:00:00 CST"),
Time.parse("2017-01-06 0:00:00 CST")
])
end
end
end
context "when creating a daily task" do
let(:task) do
described_class.new(
class: "TestJob",
every: "1.day",
at: "00:30",
queue_ahead: 10,
tz: "America/Chicago"
)
end
it "returns at least the next two future times the job should be run" do
travel_to Time.parse("2016-12-01 1:00:00 CST") do
expect(task.future_run_times).to eq([
Time.parse("2016-12-02 0:30:00 CST"),
Time.parse("2016-12-03 0:30:00 CST")
])
end
end
it "uses queue_ahead to ensure jobs are queued into the future" do
travel_to Time.parse("2016-12-01 20:00:00 CST") do
task.instance_variable_set(:@queue_ahead, 10_080) # 1 week
expect(task.future_run_times).to eq([
Time.parse("2016-12-02 0:30:00 CST"),
Time.parse("2016-12-03 0:30:00 CST"),
Time.parse("2016-12-04 0:30:00 CST"),
Time.parse("2016-12-05 0:30:00 CST"),
Time.parse("2016-12-06 0:30:00 CST"),
Time.parse("2016-12-07 0:30:00 CST"),
Time.parse("2016-12-08 0:30:00 CST"),
Time.parse("2016-12-09 0:30:00 CST")
])
end
end
end
context "when creating an hourly task" do
let(:task) do
described_class.new(
class: "TestJob",
every: "1.hour",
at: "*:00",
queue_ahead: 10,
tz: "America/Chicago"
)
end
it "returns at least the next two future times the job should be run" do
travel_to Time.parse("2016-12-01 1:00:00 CST") do
expect(task.future_run_times).to eq([
Time.parse("2016-12-01 1:00:00 CST"),
Time.parse("2016-12-01 2:00:00 CST")
])
end
end
it "uses queue_ahead to ensure jobs are queued into the future" do
travel_to Time.parse("2016-12-01 20:00:00 CST") do
task.instance_variable_set(:@queue_ahead, 360) # 6 hours
expect(task.future_run_times).to eq([
Time.parse("2016-12-01 20:00:00 CST"),
Time.parse("2016-12-01 21:00:00 CST"),
Time.parse("2016-12-01 22:00:00 CST"),
Time.parse("2016-12-01 23:00:00 CST"),
Time.parse("2016-12-02 0:00:00 CST"),
Time.parse("2016-12-02 1:00:00 CST"),
Time.parse("2016-12-02 2:00:00 CST")
])
end
end
end
context "when creating a frequent task" do
let(:task) do
described_class.new(
class: "TestJob",
every: "15.minutes",
at: "*:00",
queue_ahead: 5,
tz: "America/Chicago"
)
end
it "returns at least the next two future times the job should be run" do
travel_to Time.parse("2016-12-01 1:00:00 CST") do
expect(task.future_run_times).to eq([
Time.parse("2016-12-01 1:00:00 CST"),
Time.parse("2016-12-01 1:15:00 CST")
])
end
end
it "uses queue_ahead to ensure jobs are queued into the future" do
travel_to Time.parse("2016-12-01 20:00:00 CST") do
task.instance_variable_set(:@queue_ahead, 60) # minutes
expect(task.future_run_times).to eq([
Time.parse("2016-12-01 20:00:00 CST"),
Time.parse("2016-12-01 20:15:00 CST"),
Time.parse("2016-12-01 20:30:00 CST"),
Time.parse("2016-12-01 20:45:00 CST"),
Time.parse("2016-12-01 21:00:00 CST")
])
end
end
end
context "when daylight saving time falls back" do
context "if the :at hour is given" do
let(:task) do
described_class.new(
class: "TestJob",
every: "1.day",
at: "01:30",
tz: "America/Chicago"
)
end
it "will be scheduled to run at the given time" do
travel_to Time.parse("2016-11-06 00:00:00 CDT") do
expect(task.future_run_times).to include(Time.parse("2016-11-06 01:30:00 CDT"))
end
end
it "won't be rescheduled when the time falls back if the job was previously executed" do
travel_to Time.parse("2016-11-06 01:00:00 CST") do
tomorrows_run_time = Time.parse("2016-11-07 01:30:00 CST")
expect(task).to receive(:existing_jobs).and_return([
Sidekiq::SortedEntry.new(nil, tomorrows_run_time.to_i, "wrapped" => "TestJob", "class" => "ActiveJob::QueueAdapters::SidekiqAdapter::JobWrapper")
])
expect(task.future_run_times).to eq([
Time.parse("2016-11-07 01:30:00 CST"),
Time.parse("2016-11-08 01:30:00 CST")
])
end
end
end
context "if the :at hour isn't given" do
let(:task) do
described_class.new(
class: "TestJob",
every: "1.hour",
at: "*:30",
queue_ahead: 360,
tz: "America/Chicago"
)
end
it "will be scheduled to run every time based on the given frequency, including running twice at the 'same' hour" do
travel_to Time.parse("2016-11-06 00:00:00 CDT") do
expect(task.future_run_times).to eq([
Time.parse("2016-11-06 00:30:00 CDT"),
Time.parse("2016-11-06 01:30:00 CDT"),
Time.parse("2016-11-06 01:30:00 CST"),
Time.parse("2016-11-06 02:30:00 CST"),
Time.parse("2016-11-06 03:30:00 CST"),
Time.parse("2016-11-06 04:30:00 CST"),
Time.parse("2016-11-06 05:30:00 CST")
])
end
end
end
end
context "when daylight saving time springs forward" do
context "if the :at hour is given" do
let(:task) do
described_class.new(
class: "TestJob",
every: "1.day",
at: "02:30",
tz: "America/Chicago"
)
end
it "will always run, even if the time doesn't exist on the day" do
travel_to Time.parse("2016-03-13 01:00:00 CST") do
expect(task.future_run_times).to include(Time.parse("2016-03-13 02:30:00 CST"))
end
end
it "won't throw off the hour it is run next time after running late" do
travel_to Time.parse("2016-03-13 01:00:00 CST") do
expect(task.future_run_times).to eq([
Time.parse("2016-03-13 03:30:00 CDT"),
Time.parse("2016-03-14 02:30:00 CDT")
])
end
end
end
context "if the :at hour isn't given" do
let(:task) do
described_class.new(
class: "TestJob",
every: "1.hour",
at: "*:30",
queue_ahead: 360,
tz: "America/Chicago"
)
end
it "will always run, even if the time doesn't exist on the day" do
travel_to Time.parse("2016-03-13 01:50:00 CST") do
expect(task.future_run_times).to include(Time.parse("2016-03-13 02:30:00 CST"))
end
end
it "won't run twice or throw off the hour it is run next time" do
travel_to Time.parse("2016-03-13 00:50:00 CST") do
expect(task.future_run_times).to eq([
Time.parse("2016-03-13 01:30:00 CST"),
Time.parse("2016-03-13 03:30:00 CDT"),
Time.parse("2016-03-13 04:30:00 CDT"),
Time.parse("2016-03-13 05:30:00 CDT"),
Time.parse("2016-03-13 06:30:00 CDT"),
Time.parse("2016-03-13 07:30:00 CDT"),
Time.parse("2016-03-13 08:30:00 CDT")
])
end
end
end
end
end
end
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/spec/simple_scheduler/at_spec.rb | spec/simple_scheduler/at_spec.rb | # frozen_string_literal: true
require "rails_helper"
describe SimpleScheduler::At, type: :model do
describe "AT_PATTERN" do
let(:pattern) { SimpleScheduler::At::AT_PATTERN }
it "matches valid times" do
match = pattern.match("0:00")
expect(match[2]).to eq("0")
expect(match[3]).to eq("00")
match = pattern.match("9:30")
expect(match[2]).to eq("9")
expect(match[3]).to eq("30")
match = pattern.match("Sat 23:59")
expect(match[2]).to eq("23")
expect(match[3]).to eq("59")
match = pattern.match("Sun 00:00")
expect(match[2]).to eq("00")
expect(match[3]).to eq("00")
end
it "doesn't match invalid times" do
expect(pattern.match("99:99")).to eq(nil)
expect(pattern.match("0:60")).to eq(nil)
expect(pattern.match("12:0")).to eq(nil)
expect(pattern.match("24:00")).to eq(nil)
expect(pattern.match("*:60")).to eq(nil)
expect(pattern.match("Sun 00:60")).to eq(nil)
expect(pattern.match("[Mon|Tue|Wed|Thu|Fri] 00:00")).to eq(nil)
end
end
describe "when the run :at time includes a specific hour" do
let(:at) { described_class.new("2:30", ActiveSupport::TimeZone.new("America/Chicago")) }
context "when the :at hour is after the current time's hour" do
it "returns the :at hour:minutes on the current day" do
travel_to Time.parse("2016-12-02 1:23:45 CST") do
expect(at).to eq(Time.parse("2016-12-02 2:30:00 CST"))
end
end
end
context "when the :at hour is before the current time's hour" do
it "returns the :at hour:minutes on the next day" do
travel_to Time.parse("2016-12-02 3:45:12 CST") do
expect(at).to eq(Time.parse("2016-12-03 2:30:00 CST"))
end
end
end
context "when the :at hour is the same as the current time's hour" do
it "returns the :at hour:minutes on the next day if the :at minute < current time's min" do
travel_to Time.parse("2016-12-02 2:34:56 CST") do
expect(at).to eq(Time.parse("2016-12-03 2:30:00 CST"))
end
end
it "returns the :at hour:minutes on the current day if the :at minute > current time's min" do
travel_to Time.parse("2016-12-02 2:20:00 CST") do
expect(at).to eq(Time.parse("2016-12-02 2:30:00 CST"))
end
end
it "returns the :at hour:minutes without seconds on the current day if the :at minute == current time's min" do
travel_to Time.parse("2016-12-02 2:30:30 CST") do
expect(at).to eq(Time.parse("2016-12-02 2:30:00 CST"))
end
end
end
end
describe "when a specific day of the week is given" do
let(:at) { described_class.new("Fri 23:45", ActiveSupport::TimeZone.new("America/Chicago")) }
context "if the current day is earlier in the week than the :at day" do
it "returns the next day the :at day occurs" do
travel_to Time.parse("2016-12-01 1:23:45 CST") do # Dec 1 is Thursday
expect(at).to eq(Time.parse("2016-12-02 23:45:00 CST"))
end
end
end
context "if the current day is later in the week than the :at day" do
it "returns the next day the :at day occurs, which will be next week" do
travel_to Time.parse("2016-12-03 1:23:45 CST") do # Dec 3 is Saturday
expect(at).to eq(Time.parse("2016-12-09 23:45:00 CST"))
end
end
end
context "if the current day is the same as the :at day" do
it "returns the current day if :at time is later than the current time" do
travel_to Time.parse("2016-12-02 23:20:00 CST") do # Dec 2 is Friday
expect(at).to eq(Time.parse("2016-12-02 23:45:00 CST"))
end
end
it "returns next week's day if :at time is earlier than the current time" do
travel_to Time.parse("2016-12-02 23:50:00 CST") do # Dec 2 is Friday
expect(at).to eq(Time.parse("2016-12-09 23:45:00 CST"))
end
end
it "returns the current time without seconds if :at time matches the current time" do
travel_to Time.parse("2016-12-02 23:45:45 CST") do # Dec 2 is Friday
expect(at).to eq(Time.parse("2016-12-02 23:45:00 CST"))
end
end
end
end
describe "when the run :at time allows any hour" do
let(:at) { described_class.new("*:30", ActiveSupport::TimeZone.new("America/New_York")) }
context "when the :at minute < current time's min" do
it "returns the next hour with the :at minutes on the current day" do
travel_to Time.parse("2016-12-02 2:45:00 EST") do
expect(at).to eq(Time.parse("2016-12-02 3:30:00 EST"))
end
end
it "returns the first hour of the next day with the :at minutes if it's the last hour of the day" do
travel_to Time.parse("2016-12-02 23:45:00 EST") do
expect(at).to eq(Time.parse("2016-12-03 0:30:00 EST"))
end
end
end
context "when the :at minute > current time's min" do
it "returns the current hour with the :at minutes on the current day" do
travel_to Time.parse("2016-12-02 2:25:25 EST") do
expect(at).to eq(Time.parse("2016-12-02 2:30:00 EST"))
end
end
end
context "when the :at minute == current time's min" do
it "returns the current time without seconds" do
travel_to Time.parse("2016-12-02 2:30:25 EST") do
expect(at).to eq(Time.parse("2016-12-02 2:30:00 EST"))
end
end
end
end
describe "when the run :at time isn't given" do
it "raises an InvalidAtTime error" do
expect do
described_class.new(nil, ActiveSupport::TimeZone.new("America/New_York"))
end.to raise_error(SimpleScheduler::At::InvalidTime, "The `at` option is required.")
end
end
describe "when the run :at time is invalid" do
it "raises an InvalidAtTime error" do
expect do
described_class.new("24:00", ActiveSupport::TimeZone.new("America/New_York"))
end.to raise_error(SimpleScheduler::At::InvalidTime, "The `at` option '24:00' is invalid.")
end
end
end
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/spec/simple_scheduler/future_job_spec.rb | spec/simple_scheduler/future_job_spec.rb | # frozen_string_literal: true
require "rails_helper"
describe SimpleScheduler::FutureJob, type: :job do
describe "successfully queues" do
subject(:job) { described_class.perform_later }
it "queues the job" do
expect { job }.to change(enqueued_jobs, :size).by(1)
end
it "is in default queue" do
expect(described_class.new.queue_name).to eq("default")
end
end
describe "when an Active Job is scheduled" do
let(:task_params) do
{
class: "TestJob",
every: "1.hour",
name: "job_task"
}
end
it "queues the Active Job" do
expect do
described_class.perform_now(task_params, Time.now.to_i)
end.to change(enqueued_jobs, :size).by(1)
end
end
describe "when a Sidekiq Worker is scheduled" do
let(:task_params) do
{
class: "TestWorker",
every: "1.hour",
name: "worker_task"
}
end
it "adds the job to the queue" do
expect do
described_class.perform_now(task_params, Time.now.to_i)
end.to change(TestWorker.jobs, :size).by(1)
end
end
describe "when a job or worker accepts the scheduled time as an argument" do
it "executes an Active Job without exception" do
expect do
task_params = { class: "TestJob", every: "1.hour" }
perform_enqueued_jobs do
described_class.perform_now(task_params, Time.now.to_i)
end
end.not_to raise_error
end
it "executes an Sidekiq Worker without exception" do
expect do
task_params = { class: "TestWorker", every: "1.hour" }
perform_enqueued_jobs do
Sidekiq::Testing.inline! do
described_class.perform_now(task_params, Time.now.to_i)
end
end
end.not_to raise_error
end
end
describe "when a job or worker accepts no arguments" do
it "executes an Active Job without exception" do
expect do
task_params = { class: "TestNoArgsJob", every: "1.hour" }
perform_enqueued_jobs do
described_class.perform_now(task_params, Time.now.to_i)
end
end.not_to raise_error
end
it "executes an Sidekiq Worker without exception" do
expect do
task_params = { class: "TestNoArgsWorker", every: "1.hour" }
perform_enqueued_jobs do
Sidekiq::Testing.inline! do
described_class.perform_now(task_params, Time.now.to_i)
end
end
end.not_to raise_error
end
end
describe "when a job or worker accepts optional arguments" do
it "executes an Active Job without exception" do
expect do
task_params = { class: "TestOptionalArgsJob", every: "1.hour" }
perform_enqueued_jobs do
described_class.perform_now(task_params, Time.now.to_i)
end
end.not_to raise_error
end
it "executes an Sidekiq Worker without exception" do
expect do
task_params = { class: "TestOptionalArgsWorker", every: "1.hour" }
perform_enqueued_jobs do
Sidekiq::Testing.inline! do
described_class.perform_now(task_params, Time.now.to_i)
end
end
end.not_to raise_error
end
end
describe "when the job is run within the allowed expiration time" do
let(:task_params) do
{
class: "TestJob",
every: "1.hour",
name: "job_task",
expires_after: "30.minutes"
}
end
it "adds the job to the queue" do
expect do
described_class.perform_now(task_params, (Time.now - 29.minutes).to_i)
end.to change(enqueued_jobs, :size).by(1)
end
end
describe "when the job is run past the allowed expiration time" do
let(:task_params) do
{
class: "TestJob",
every: "1.hour",
name: "job_task",
expires_after: "30.minutes"
}
end
it "doesn't add the job to the queue" do
expect do
described_class.perform_now(task_params, (Time.now - 31.minutes).to_i)
end.to change(enqueued_jobs, :size).by(0)
end
it "calls all blocks defined to handle the expired task exception" do
travel_to Time.parse("2016-12-01 1:00:00 CST") do
run_time = Time.now
scheduled_time = run_time - 31.minutes
yielded_exception = nil
SimpleScheduler.expired_task do |exception|
yielded_exception = exception
end
described_class.perform_now(task_params, scheduled_time.to_i)
expect(yielded_exception).to be_a(SimpleScheduler::FutureJob::Expired)
expect(yielded_exception.run_time).to eq(run_time)
expect(yielded_exception.scheduled_time).to eq(scheduled_time)
expect(yielded_exception.task).to be_a(SimpleScheduler::Task)
end
end
end
describe ".delete_all" do
let(:application_job) do
Sidekiq::SortedEntry.new(
nil,
1,
"wrapped" => "SomeApplicationJob",
"class" => "ActiveJob::QueueAdapters::SidekiqAdapter::JobWrapper"
)
end
let(:simple_scheduler_job1) do
Sidekiq::SortedEntry.new(
nil,
1,
"wrapped" => "SimpleScheduler::FutureJob",
"class" => "ActiveJob::QueueAdapters::SidekiqAdapter::JobWrapper",
"args" => [{ "arguments" => [{ "class" => "TestJob", "name" => "test_task" }] }]
)
end
let(:simple_scheduler_job2) do
Sidekiq::SortedEntry.new(
nil,
1,
"wrapped" => "SimpleScheduler::FutureJob",
"class" => "ActiveJob::QueueAdapters::SidekiqAdapter::JobWrapper",
"args" => [{ "arguments" => [{ "class" => "AnotherJob", "name" => "another_task" }] }]
)
end
before do
expect(SimpleScheduler::Task).to receive(:scheduled_set).and_return([
application_job,
simple_scheduler_job1,
simple_scheduler_job2
])
end
it "deletes future jobs scheduled by Simple Scheduler from the Sidekiq::ScheduledSet" do
expect(simple_scheduler_job1).to receive(:delete).once
expect(simple_scheduler_job2).to receive(:delete).once
expect(application_job).not_to receive(:delete)
SimpleScheduler::FutureJob.delete_all
end
end
end
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/spec/dummy/app/jobs/test_no_args_worker.rb | spec/dummy/app/jobs/test_no_args_worker.rb | # Sidekiq Worker for testing a worker with no args
class TestNoArgsWorker
include Sidekiq::Worker
def perform; end
end
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/spec/dummy/app/jobs/test_worker.rb | spec/dummy/app/jobs/test_worker.rb | # Sidekiq Worker for testing
class TestWorker
include Sidekiq::Worker
def perform(scheduled_time); end
end
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/spec/dummy/app/jobs/test_job.rb | spec/dummy/app/jobs/test_job.rb | # Active Job for testing
class TestJob < ApplicationJob
def perform(scheduled_time); end
end
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/spec/dummy/app/jobs/test_optional_args_worker.rb | spec/dummy/app/jobs/test_optional_args_worker.rb | # Sidekiq Worker for testing a worker with optional args
class TestOptionalArgsWorker
include Sidekiq::Worker
def perform(scheduled_time, options = nil); end
end
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/spec/dummy/app/jobs/application_job.rb | spec/dummy/app/jobs/application_job.rb | class ApplicationJob < ActiveJob::Base
end
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/spec/dummy/app/jobs/test_no_args_job.rb | spec/dummy/app/jobs/test_no_args_job.rb | # Active Job for testing a job with no args
class TestNoArgsJob < ApplicationJob
def perform; end
end
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/spec/dummy/app/jobs/test_optional_args_job.rb | spec/dummy/app/jobs/test_optional_args_job.rb | # Active Job for testing a job with optional args
class TestOptionalArgsJob < ApplicationJob
def perform(scheduled_time, options = nil); end
end
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/spec/dummy/app/helpers/application_helper.rb | spec/dummy/app/helpers/application_helper.rb | module ApplicationHelper
end
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/spec/dummy/app/controllers/application_controller.rb | spec/dummy/app/controllers/application_controller.rb | class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
end
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/spec/dummy/app/models/application_record.rb | spec/dummy/app/models/application_record.rb | class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/spec/dummy/app/channels/application_cable/channel.rb | spec/dummy/app/channels/application_cable/channel.rb | module ApplicationCable
class Channel < ActionCable::Channel::Base
end
end
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/spec/dummy/app/channels/application_cable/connection.rb | spec/dummy/app/channels/application_cable/connection.rb | module ApplicationCable
class Connection < ActionCable::Connection::Base
end
end
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/spec/dummy/config/application.rb | spec/dummy/config/application.rb | require_relative "boot"
require "action_controller/railtie"
require "rails/test_unit/railtie"
Bundler.require(*Rails.groups)
require "simple_scheduler"
module Dummy
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
end
end
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/spec/dummy/config/environment.rb | spec/dummy/config/environment.rb | # Load the Rails application.
require_relative "application"
# Initialize the Rails application.
Rails.application.initialize!
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/spec/dummy/config/puma.rb | spec/dummy/config/puma.rb | # Puma can serve each request in a thread from an internal thread pool.
# The `threads` method setting takes two numbers a minimum and maximum.
# Any libraries that use thread pools should be configured to match
# the maximum value specified for Puma. Default is set to 5 threads for minimum
# and maximum, this matches the default thread size of Active Record.
#
threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }.to_i
threads threads_count, threads_count
# Specifies the `port` that Puma will listen on to receive requests, default is 3000.
#
port ENV.fetch("PORT") { 3000 }
# Specifies the `environment` that Puma will run in.
#
environment ENV.fetch("RAILS_ENV") { "development" }
# Specifies the number of `workers` to boot in clustered mode.
# Workers are forked webserver processes. If using threads and workers together
# the concurrency of the application would be max `threads` * `workers`.
# Workers do not work on JRuby or Windows (both of which do not support
# processes).
#
# workers ENV.fetch("WEB_CONCURRENCY") { 2 }
# Use the `preload_app!` method when specifying a `workers` number.
# This directive tells Puma to first boot the application and load code
# before forking the application. This takes advantage of Copy On Write
# process behavior so workers use less memory. If you use this option
# you need to make sure to reconnect any threads in the `on_worker_boot`
# block.
#
# preload_app!
# The code in the `on_worker_boot` will be called if you are using
# clustered mode by specifying a number of `workers`. After each worker
# process is booted this block will be run, if you are using `preload_app!`
# option you will want to use this block to reconnect to any threads
# or connections that may have been created at application boot, Ruby
# cannot share connections between processes.
#
# on_worker_boot do
# ActiveRecord::Base.establish_connection if defined?(ActiveRecord)
# end
# Allow puma to be restarted by `rails restart` command.
plugin :tmp_restart
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/spec/dummy/config/routes.rb | spec/dummy/config/routes.rb | Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/spec/dummy/config/spring.rb | spec/dummy/config/spring.rb | %w(
.ruby-version
.rbenv-vars
tmp/restart.txt
tmp/caching-dev.txt
).each { |path| Spring.watch(path) }
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/spec/dummy/config/boot.rb | spec/dummy/config/boot.rb | # Set up gems listed in the Gemfile.
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../Gemfile', __dir__)
require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE'])
$LOAD_PATH.unshift File.expand_path('../../../lib', __dir__)
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/spec/dummy/config/initializers/filter_parameter_logging.rb | spec/dummy/config/initializers/filter_parameter_logging.rb | # Be sure to restart your server when you modify this file.
# Configure sensitive parameters which will be filtered from the log file.
Rails.application.config.filter_parameters += [:password]
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/spec/dummy/config/initializers/application_controller_renderer.rb | spec/dummy/config/initializers/application_controller_renderer.rb | # Be sure to restart your server when you modify this file.
# ApplicationController.renderer.defaults.merge!(
# http_host: 'example.org',
# https: false
# )
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/spec/dummy/config/initializers/session_store.rb | spec/dummy/config/initializers/session_store.rb | # Be sure to restart your server when you modify this file.
Rails.application.config.session_store :cookie_store, key: '_dummy_session'
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/spec/dummy/config/initializers/wrap_parameters.rb | spec/dummy/config/initializers/wrap_parameters.rb | # Be sure to restart your server when you modify this file.
# This file contains settings for ActionController::ParamsWrapper which
# is enabled by default.
# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
ActiveSupport.on_load(:action_controller) do
wrap_parameters format: [:json]
end
# To enable root element in JSON for ActiveRecord objects.
# ActiveSupport.on_load(:active_record) do
# self.include_root_in_json = true
# end
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/spec/dummy/config/initializers/inflections.rb | spec/dummy/config/initializers/inflections.rb | # Be sure to restart your server when you modify this file.
# Add new inflection rules using the following format. Inflections
# are locale specific, and you may define rules for as many different
# locales as you wish. All of these examples are active by default:
# ActiveSupport::Inflector.inflections(:en) do |inflect|
# inflect.plural /^(ox)$/i, '\1en'
# inflect.singular /^(ox)en/i, '\1'
# inflect.irregular 'person', 'people'
# inflect.uncountable %w( fish sheep )
# end
# These inflection rules are supported but not enabled by default:
# ActiveSupport::Inflector.inflections(:en) do |inflect|
# inflect.acronym 'RESTful'
# end
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/spec/dummy/config/initializers/cookies_serializer.rb | spec/dummy/config/initializers/cookies_serializer.rb | # Be sure to restart your server when you modify this file.
# Specify a serializer for the signed and encrypted cookie jars.
# Valid options are :json, :marshal, and :hybrid.
Rails.application.config.action_dispatch.cookies_serializer = :json
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/spec/dummy/config/initializers/backtrace_silencers.rb | spec/dummy/config/initializers/backtrace_silencers.rb | # Be sure to restart your server when you modify this file.
# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
# Rails.backtrace_cleaner.remove_silencers!
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/spec/dummy/config/initializers/mime_types.rb | spec/dummy/config/initializers/mime_types.rb | # Be sure to restart your server when you modify this file.
# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/spec/dummy/config/environments/test.rb | spec/dummy/config/environments/test.rb | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Do not eager load code on boot. This avoids loading your whole application
# just for the purpose of running a single test. If you are using a tool that
# preloads Rails for running tests, you may have to set it to true.
config.eager_load = false
# Configure public file server for tests with Cache-Control for performance.
# config.public_file_server.enabled = true
# config.public_file_server.headers = {
# 'Cache-Control' => 'public, max-age=3600'
# }
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates.
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment.
config.action_controller.allow_forgery_protection = false
# Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
end
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/spec/dummy/config/environments/development.rb | spec/dummy/config/environments/development.rb | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports.
config.consider_all_requests_local = true
# Enable/disable caching. By default caching is disabled.
if Rails.root.join('tmp/caching-dev.txt').exist?
config.action_controller.perform_caching = true
config.cache_store = :memory_store
config.public_file_server.headers = {
'Cache-Control' => 'public, max-age=172800'
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Suppress logger output for asset requests.
config.assets.quiet = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
# Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
# config.file_watcher = ActiveSupport::EventedFileUpdateChecker
end
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/spec/dummy/config/environments/production.rb | spec/dummy/config/environments/production.rb | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Mount Action Cable outside main process or domain
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/lib/simple_scheduler.rb | lib/simple_scheduler.rb | # frozen_string_literal: true
require "active_job"
require "sidekiq/api"
require_relative "simple_scheduler/at"
require_relative "simple_scheduler/future_job"
require_relative "simple_scheduler/railtie"
require_relative "simple_scheduler/scheduler_job"
require_relative "simple_scheduler/task"
require_relative "simple_scheduler/version"
# Module for scheduling jobs at specific times using Sidekiq.
module SimpleScheduler
# Used by a Rails initializer to handle expired tasks.
# SimpleScheduler.expired_task do |exception|
# ExceptionNotifier.notify_exception(
# exception,
# data: {
# task: exception.task.name,
# scheduled: exception.scheduled_time,
# actual: exception.run_time
# }
# )
# end
def self.expired_task(&block)
expired_task_blocks << block
end
# Blocks that should be called when a task doesn't run because it has expired.
# @return [Array]
def self.expired_task_blocks
@expired_task_blocks ||= []
end
end
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/lib/simple_scheduler/task.rb | lib/simple_scheduler/task.rb | # frozen_string_literal: true
module SimpleScheduler
# Class for parsing each task in the scheduler config YAML file and returning
# the values needed to schedule the task in the future.
#
# @!attribute [r] job_class
# @return [Class] The class of the job or worker.
# @!attribute [r] params
# @return [Hash] The params used to create the task
class Task
attr_reader :job_class, :params
DEFAULT_QUEUE_AHEAD_MINUTES = 360
# Initializes a task by parsing the params so the task can be queued in the future.
# @param params [Hash]
# @option params [String] :class The class of the Active Job or Sidekiq Worker
# @option params [String] :every How frequently the job will be performed
# @option params [String] :at The starting time for the interval
# @option params [String] :expires_after The interval used to determine how late the job is allowed to run
# @option params [Integer] :queue_ahead The number of minutes that jobs should be queued in the future
# @option params [String] :task_name The name of the task as defined in the YAML config
# @option params [String] :tz The time zone to use when parsing the `at` option
def initialize(params)
validate_params!(params)
@params = params
end
# The task's first run time as a Time-like object.
# @return [SimpleScheduler::At]
def at
@at ||= At.new(@params[:at], time_zone)
end
# The time between the scheduled and actual run time that should cause the job not to run.
# @return [String]
def expires_after
@params[:expires_after]
end
# Returns an array of existing jobs matching the job class of the task.
# @return [Array<Sidekiq::SortedEntry>]
def existing_jobs
@existing_jobs ||= SimpleScheduler::Task.scheduled_set.select do |job|
next unless job.display_class == "SimpleScheduler::FutureJob"
task_params = job.display_args[0].symbolize_keys
task_params[:class] == job_class_name && task_params[:name] == name
end.to_a
end
# Returns an array of existing future run times that have already been scheduled.
# @return [Array<Time>]
def existing_run_times
@existing_run_times ||= existing_jobs.map(&:at)
end
# How often the job will be run.
# @return [ActiveSupport::Duration]
def frequency
@frequency ||= parse_frequency(@params[:every])
end
# Returns an array Time objects for future run times based on
# the current time and the given minutes to look ahead.
# @return [Array<Time>]
# rubocop:disable Metrics/AbcSize
def future_run_times
future_run_times = existing_run_times.dup
last_run_time = future_run_times.last || (at - frequency)
last_run_time = last_run_time.in_time_zone(time_zone)
# Ensure there are at least two future jobs scheduled and that the queue ahead time is filled
while future_run_times.length < 2 || minutes_queued_ahead(last_run_time) < queue_ahead
last_run_time = frequency.from_now(last_run_time)
# The hour may not match because of a shift caused by DST in previous run times,
# so we need to ensure that the hour matches the specified hour if given.
last_run_time = last_run_time.change(hour: at.hour, min: at.min) if at.hour?
future_run_times << last_run_time
end
future_run_times
end
# rubocop:enable Metrics/AbcSize
# The class name of the job or worker.
# @return [String]
def job_class_name
@params[:class]
end
# The name of the task as defined in the YAML config.
# @return [String]
def name
@params[:name]
end
# The number of minutes that jobs should be queued in the future.
# @return [Integer]
def queue_ahead
@queue_ahead ||= @params[:queue_ahead] || DEFAULT_QUEUE_AHEAD_MINUTES
end
# The time zone to use when parsing the `at` option.
# @return [ActiveSupport::TimeZone]
def time_zone
@time_zone ||= params[:tz] ? ActiveSupport::TimeZone.new(params[:tz]) : Time.zone
end
# Loads the scheduled jobs from Sidekiq once to avoid loading from
# Redis for each task when looking up existing scheduled jobs.
# @return [Sidekiq::ScheduledSet]
def self.scheduled_set
@scheduled_set ||= Sidekiq::ScheduledSet.new
end
private
def minutes_queued_ahead(last_run_time)
(last_run_time - Time.now) / 60
end
def parse_frequency(every_string)
split_duration = every_string.split(".")
frequency = split_duration[0].to_i
frequency_units = split_duration[1]
frequency.send(frequency_units)
end
def validate_params!(params)
raise ArgumentError, "Missing param `class` specifying the class of the job to run." unless params.key?(:class)
raise ArgumentError, "Missing param `every` specifying how often the job should run." unless params.key?(:every)
@job_class = params[:class].constantize
params[:name] ||= params[:class]
end
end
end
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/lib/simple_scheduler/version.rb | lib/simple_scheduler/version.rb | # frozen_string_literal: true
module SimpleScheduler
VERSION = "2.0.0"
end
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
simplymadeapps/simple_scheduler | https://github.com/simplymadeapps/simple_scheduler/blob/fac50a8119736f1df3ddabb2aeef33efd000902e/lib/simple_scheduler/at.rb | lib/simple_scheduler/at.rb | # frozen_string_literal: true
require "delegate"
module SimpleScheduler
# A delegator that parses the :at option on a task into the first time it should run.
# Instead of inheriting from Time (which conflicts with ActiveSupport time helpers),
# this wraps a Time instance and selectively overrides hour/hour? semantics.
# Time.now
# # => 2016-12-09 08:24:11 -0600
# SimpleScheduler::At.new("*:30")
# # => 2016-12-09 08:30:00 -0600
# SimpleScheduler::At.new("1:00")
# # => 2016-12-10 01:00:00 -0600
# SimpleScheduler::At.new("Sun 0:00")
# # => 2016-12-11 00:00:00 -0600
class At < SimpleDelegator
AT_PATTERN = /\A(Sun|Mon|Tue|Wed|Thu|Fri|Sat)?\s?(?:\*{1,2}|((?:\b[0-1]?[0-9]|2[0-3]))):([0-5]\d)\z/
DAYS = %w[Sun Mon Tue Wed Thu Fri Sat].freeze
# Error class raised when an invalid string is given for the time.
class InvalidTime < StandardError; end
# Accepts a time string to determine when a task should be run for the first time.
# Valid formats:
# "18:00"
# "3:30"
# "**:00"
# "*:30"
# "Sun 2:00"
# "[Sun|Mon|Tue|Wed|Thu|Fri|Sat] 00:00"
# @param at [String] The formatted string for a task's run time
# @param time_zone [ActiveSupport::TimeZone] The time zone to parse the at time in
def initialize(at, time_zone = nil)
@at = at
@time_zone = time_zone || Time.zone
super(parsed_time) # Delegate all Time methods to parsed Time instance
end
# Returns the specified hour if present in the at string, else the delegated Time's hour.
# @return [Integer]
def hour
hour? ? at_hour : __getobj__.hour
end
# Returns whether or not the hour was specified in the :at string.
# @return [Boolean]
def hour?
at_match[2].present?
end
private
def at_match
@at_match ||= begin
raise InvalidTime, "The `at` option is required." if @at.nil?
match = AT_PATTERN.match(@at)
raise InvalidTime, "The `at` option '#{@at}' is invalid." if match.nil?
match
end
end
def at_hour
@at_hour ||= (at_match[2] || now.hour).to_i
end
def at_min
@at_min ||= (at_match[3] || now.min).to_i
end
def at_wday
@at_wday ||= DAYS.index(at_match[1])
end
def at_wday?
at_match[1].present?
end
def next_hour
@next_hour ||= begin
h = at_hour
# Add an additional hour if a specific hour wasn't given, if the minutes
# given are less than the current time's minutes.
h += 1 if next_hour?
h
end
end
def next_hour?
!hour? && at_min < now.min
end
def now
@now ||= @time_zone.now.beginning_of_minute
end
def parsed_day
day = now.beginning_of_day
# If no day of the week is given, return today
return day unless at_wday?
# Shift to the correct day of the week if given
add_days = at_wday - day.wday
add_days += 7 if day.wday > at_wday
day + add_days.days
end
# Returns the very first time a job should be run for the scheduled task.
# @return [Time]
def parsed_time
return @parsed_time if defined?(@parsed_time) && @parsed_time
time_object = parsed_day
change_hour = next_hour
# There is no hour 24, so we need to move to the next day
if change_hour == 24
time_object = 1.day.from_now(time_object)
change_hour = 0
end
time_object = time_object.change(hour: change_hour, min: at_min)
# If the parsed time is still before the current time, add an additional day if
# the week day wasn't specified or add an additional week to get the correct time.
time_object += at_wday? ? 1.week : 1.day if now > time_object
@parsed_time = time_object
end
end
end
| ruby | MIT | fac50a8119736f1df3ddabb2aeef33efd000902e | 2026-01-04T17:46:19.163745Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.