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 |
|---|---|---|---|---|---|---|---|---|
taylorthurlow/panda-motd | https://github.com/taylorthurlow/panda-motd/blob/d1cc6db9220243e83fbb1a2bbf91c6a143b9f559/spec/factories/motd_factory.rb | spec/factories/motd_factory.rb | # frozen_string_literal: true
FactoryBot.define do
factory :motd, class: MOTD do
skip_create
transient do
components { [] }
end
config { association(:config, components: components) }
initialize_with { new(config.file_path, false) }
end
end
| ruby | MIT | d1cc6db9220243e83fbb1a2bbf91c6a143b9f559 | 2026-01-04T17:46:36.398098Z | false |
taylorthurlow/panda-motd | https://github.com/taylorthurlow/panda-motd/blob/d1cc6db9220243e83fbb1a2bbf91c6a143b9f559/spec/factories/component_factories.rb | spec/factories/component_factories.rb | # frozen_string_literal: true
Dir["#{PandaMOTD.root}/lib/panda_motd/components/**/*.rb"].each do |c|
component_sym = File.basename(c, ".rb").to_sym
klass = Config.component_classes[component_sym]
FactoryBot.define do
factory component_sym, class: klass do
skip_create
transient do
settings { nil }
end
motd { association(:motd, components: [component_sym]) }
initialize_with { new(motd) }
after(:build) do |component|
allow(component).to receive(:`).and_return ""
end
after(:create) do |component, evaluator|
component.config.merge!(evaluator.settings) if evaluator.settings
end
end
end
end
| ruby | MIT | d1cc6db9220243e83fbb1a2bbf91c6a143b9f559 | 2026-01-04T17:46:36.398098Z | false |
taylorthurlow/panda-motd | https://github.com/taylorthurlow/panda-motd/blob/d1cc6db9220243e83fbb1a2bbf91c6a143b9f559/spec/components/ascii_text_art_spec.rb | spec/components/ascii_text_art_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "colorize"
describe ASCIITextArt do
context "with normal config" do
subject(:component) { create(:ascii_text_art) }
it "prints the properly colored art" do
stub_system_call(component, returns: "helloworld")
component.process
expect(component.results).to start_with "\e[0;31;49m" # code for red
expect(component.results).to end_with "\e[0m"
end
it "prints the art" do
stub_system_call(component, returns: "helloworld")
component.process
expect(component.to_s).not_to be_nil
end
end
context "with config containing an invalid font name" do
subject(:component) {
create(:ascii_text_art, settings: { "font" => "badfontname" })
}
it "adds an error to the component" do
stub_system_call(component, returns: "helloworld")
component.process
expect(component.errors.count).to eq 1
expect(component.errors.first.message).to eq "Invalid font name"
end
end
end
| ruby | MIT | d1cc6db9220243e83fbb1a2bbf91c6a143b9f559 | 2026-01-04T17:46:36.398098Z | false |
taylorthurlow/panda-motd | https://github.com/taylorthurlow/panda-motd/blob/d1cc6db9220243e83fbb1a2bbf91c6a143b9f559/spec/components/service_status_spec.rb | spec/components/service_status_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "colorize"
describe ServiceStatus do
context "with normal config" do
subject(:component) { create(:service_status) }
it "returns the list of statuses" do
stub_system_call(component, returns: "active")
component.process
expect(component.results).to eq(Plex: :active, Sonarr: :active)
end
it "prints the list of statuses" do
stub_system_call(component, returns: "active")
component.process
results = component.to_s.delete(" ") # handle variable whitespace
expect(results).to include "Plex" + "active".green
expect(results).to include "Sonarr" + "active".green
end
context "when printing different statuses" do
it "prints active in green" do
component.instance_variable_set(:@results, servicename: :active)
expect(component.to_s).to include "active".green
end
it "prints inactive in yellow" do
component.instance_variable_set(:@results, servicename: :inactive)
expect(component.to_s).to include "inactive".yellow
end
it "prints failed in red" do
component.instance_variable_set(:@results, servicename: :failed)
expect(component.to_s).to include "failed".red
end
it "prints unknown status in red" do
component.instance_variable_set(:@results, servicename: :asdf123)
expect(component.to_s).to include "asdf123".red
end
end
context "when system call output is empty" do
it "adds an error to the component" do
stub_system_call(component, returns: "")
component.process
errors = component.errors
expect(errors.count).to eq 2
expect(errors.first.message).to eq "systemctl output was blank."
end
end
end
end
| ruby | MIT | d1cc6db9220243e83fbb1a2bbf91c6a143b9f559 | 2026-01-04T17:46:36.398098Z | false |
taylorthurlow/panda-motd | https://github.com/taylorthurlow/panda-motd/blob/d1cc6db9220243e83fbb1a2bbf91c6a143b9f559/spec/components/fail_2_ban_spec.rb | spec/components/fail_2_ban_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Fail2Ban do
context "with normal config" do
subject(:component) { create(:fail_2_ban) }
it "gets statistics" do
stub_system_call(component)
component.process
expect(component.results[:jails]).to eq(
"sshd" => { total: 871, current: 0 },
)
end
it "prints the results" do
stub_system_call(component)
component.process
results = component.to_s
expect(results).to include "Fail2Ban:"
expect(results).to include "Total bans: 871"
expect(results).to include "Current bans: 0"
end
end
context "with config containing an invalid jail name" do
subject(:component) {
create(:fail_2_ban, settings: { "jails" => ["asdf"] })
}
it "adds an error to the component" do
stub_system_call(
component,
returns: "Sorry but the jail 'asdf' does not exist",
)
component.process
expect(component.errors.count).to eq 1
expect(component.errors.first.message).to eq "Invalid jail name 'asdf'."
end
end
end
| ruby | MIT | d1cc6db9220243e83fbb1a2bbf91c6a143b9f559 | 2026-01-04T17:46:36.398098Z | false |
taylorthurlow/panda-motd | https://github.com/taylorthurlow/panda-motd/blob/d1cc6db9220243e83fbb1a2bbf91c6a143b9f559/spec/components/uptime_spec.rb | spec/components/uptime_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe Uptime do
subject(:component) { create(:uptime) }
let(:sysinfo) { instance_double("sysinfo") }
context "when uptime is less than 1 day" do
it "formats the uptime" do
allow(SysInfo).to receive(:new).and_return(sysinfo)
allow(sysinfo).to receive(:uptime).and_return(15.12394)
component.process
expect(component.to_s).to eq "up 15 hours, 7 minutes"
end
it "gets the proper number of days" do
allow(SysInfo).to receive(:new).and_return(sysinfo)
allow(sysinfo).to receive(:uptime).and_return(15.12394)
component.process
expect(component.days).to eq 0
end
it "gets the proper number of hours" do
allow(SysInfo).to receive(:new).and_return(sysinfo)
allow(sysinfo).to receive(:uptime).and_return(15.12394)
component.process
expect(component.hours).to eq 15
end
it "gets the proper number of minutes" do
allow(SysInfo).to receive(:new).and_return(sysinfo)
allow(sysinfo).to receive(:uptime).and_return(15.12394)
component.process
expect(component.minutes).to eq 7
end
context "when hours is zero" do
it "does not show hours" do
allow(SysInfo).to receive(:new).and_return(sysinfo)
allow(sysinfo).to receive(:uptime).and_return(0.12394)
component.process
expect(component.to_s).to eq "up 7 minutes"
end
end
end
context "when uptime is greater than 1 day" do
it "formats the uptime" do
allow(SysInfo).to receive(:new).and_return(sysinfo)
allow(sysinfo).to receive(:uptime).and_return(51.59238)
component.process
expect(component.to_s).to eq "up 2 days, 3 hours, 35 minutes"
end
it "gets the proper number of days" do
allow(SysInfo).to receive(:new).and_return(sysinfo)
allow(sysinfo).to receive(:uptime).and_return(51.59238)
component.process
expect(component.days).to eq 2
end
it "gets the proper number of hours" do
allow(SysInfo).to receive(:new).and_return(sysinfo)
allow(sysinfo).to receive(:uptime).and_return(51.59238)
component.process
expect(component.hours).to eq 3
end
it "gets the proper number of minutes" do
allow(SysInfo).to receive(:new).and_return(sysinfo)
allow(sysinfo).to receive(:uptime).and_return(51.59238)
component.process
expect(component.minutes).to eq 35
end
context "when hours is zero" do
it "does not show hours" do
allow(SysInfo).to receive(:new).and_return(sysinfo)
allow(sysinfo).to receive(:uptime).and_return(48.12394)
component.process
expect(component.to_s).to eq "up 2 days, 7 minutes"
end
end
end
context "when days is 1" do
it "does not pluralize" do
allow(SysInfo).to receive(:new).and_return(sysinfo)
allow(sysinfo).to receive(:uptime).and_return(29.12394)
component.process
expect(component.to_s).to eq "up 1 day, 5 hours, 7 minutes"
end
end
context "when hours is 1" do
it "does not pluralize" do
allow(SysInfo).to receive(:new).and_return(sysinfo)
allow(sysinfo).to receive(:uptime).and_return(49.12394)
component.process
expect(component.to_s).to eq "up 2 days, 1 hour, 7 minutes"
end
end
context "when minutes is 1" do
it "does not pluralize" do
allow(SysInfo).to receive(:new).and_return(sysinfo)
allow(sysinfo).to receive(:uptime).and_return(59.017)
component.process
expect(component.to_s).to eq "up 2 days, 11 hours, 1 minute"
end
end
end
| ruby | MIT | d1cc6db9220243e83fbb1a2bbf91c6a143b9f559 | 2026-01-04T17:46:36.398098Z | false |
taylorthurlow/panda-motd | https://github.com/taylorthurlow/panda-motd/blob/d1cc6db9220243e83fbb1a2bbf91c6a143b9f559/spec/components/ssl_certificates_spec.rb | spec/components/ssl_certificates_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "colorize"
describe SSLCertificates do
context "with normal config" do
subject(:component) { create(:ssl_certificates) }
it "returns the list of certificates" do
stub_system_call(component)
allow(File).to receive(:exist?).and_return(true) # valid cert path
component.process
expect(component.results).to eq([[
"thurlow.io",
Time.parse("Jul 12 2018 08:17:27 GMT"),
]])
end
context "when printing different statuses" do
it "prints a valid certificate" do
component.instance_variable_set(:@results, [["mycert", Time.now + 31]])
expect(component.to_s.delete(" ")).to include "validuntil".green
end
it "prints an expiring certificate" do
component.instance_variable_set(:@results, [["mycert", Time.now + 1]])
expect(component.to_s.delete(" ")).to include "expiringat".yellow
end
it "prints an expired certificate" do
component.instance_variable_set(:@results, [["mycert", Time.now]])
expect(component.to_s.delete(" ")).to include "expiredat".red
end
end
context "when the certificate expiration date cannot be found" do
it "adds an error to the component" do
stub_system_call(component, returns: "")
allow(File).to receive(:exist?).and_return(true) # valid cert path
component.process
expect(component.errors.count).to eq 1
expect(component.errors.first.message).to eq(
"Unable to find certificate expiration date"
)
end
end
context "when the certificate expiration date cannot be parsed" do
it "adds an error to the component" do
stub_system_call(
component,
returns: "notAfter=Wtf 69 42:42:42 2077 LOL\n",
)
allow(File).to receive(:exist?).and_return(true) # valid cert path
component.process
expect(component.errors.count).to eq 1
expect(component.errors.first.message).to eq(
"Found expiration date, but unable to parse as date"
)
end
end
context "when config contains certificates that are not found" do
it "prints that the certificate was not found" do
allow(File).to receive(:exist?).and_call_original
allow(File).to receive(:exist?)
.with("/etc/letsencrypt/live/thurlow.io/cert.pem")
.and_return(false) # assume cert file path is invalid
stub_system_call(component)
component.process
expect(component.to_s).to include "Certificate thurlow.io not found"
end
end
end
context "when sorting is set to alphabetical" do
subject(:component) {
settings = { "sort_method" => "alphabetical",
"certs" => {
"def" => "/etc/letsencrypt/live/def.com/cert.pem",
"abc" => "/etc/letsencrypt/live/abc.com/cert.pem",
"xyz" => "/etc/letsencrypt/live/xyz.com/cert.pem",
} }
create(:ssl_certificates, settings: settings)
}
it "prints the certificates in alphabetical order" do
stub_system_call(component)
allow(File).to receive(:exist?).and_return(true) # valid cert path
component.process
name_list = component.to_s.split("\n")
.drop(1)
.map { |c| c.strip.match(/^(\S+)/)[1] }
expect(name_list).to eq ["abc", "def", "xyz"]
end
end
context "when sorting is set to expiration" do
subject(:component) {
settings = { "sort_method" => "expiration",
"certs" => {
"def" => "/etc/letsencrypt/live/def.com/cert.pem",
"abc" => "/etc/letsencrypt/live/abc.com/cert.pem",
"xyz" => "/etc/letsencrypt/live/xyz.com/cert.pem",
} }
create(:ssl_certificates, settings: settings)
}
def systemctl_call(path)
return "openssl x509 -in #{path} -dates"
end
def stubbed_return_expiry(time_shift)
time = (Time.now + time_shift).strftime("%b %d %H:%M:%S %Y %Z")
return "notAfter=#{time}\n"
end
it "prints the certificates in order of earliest expiration first" do
allow(File).to receive(:exist?).and_return(true) # valid cert path
allow(component).to receive(:`)
.with(systemctl_call("/etc/letsencrypt/live/def.com/cert.pem"))
.and_return(stubbed_return_expiry(3 * 60))
allow(component).to receive(:`)
.with(systemctl_call("/etc/letsencrypt/live/abc.com/cert.pem"))
.and_return(stubbed_return_expiry(1 * 60))
allow(component).to receive(:`)
.with(systemctl_call("/etc/letsencrypt/live/xyz.com/cert.pem"))
.and_return(stubbed_return_expiry(2 * 60))
component.process
name_list = component.to_s.split("\n")
.drop(1)
.map { |c| c.strip.match(/^(\S+)/)[1] }
expect(name_list).to eq ["abc", "xyz", "def"]
end
end
end
| ruby | MIT | d1cc6db9220243e83fbb1a2bbf91c6a143b9f559 | 2026-01-04T17:46:36.398098Z | false |
taylorthurlow/panda-motd | https://github.com/taylorthurlow/panda-motd/blob/d1cc6db9220243e83fbb1a2bbf91c6a143b9f559/spec/components/last_login_spec.rb | spec/components/last_login_spec.rb | # frozen_string_literal: true
require "spec_helper"
describe LastLogin do
context "with normal config" do
subject(:component) {
create(:last_login, settings: { "users" => { "taylor" => 4 } })
}
it "returns the list of logins" do
stub_system_call(component)
component.process
expect(component.results[:taylor][1]).to eq(
username: "taylor",
location: "192.168.1.101",
time_start: Time.parse("2018-05-12T13:32:28-0700"),
time_end: Time.parse("2018-05-12T13:35:39-0700"),
)
end
it "prints the list of logins" do
stub_system_call(component)
component.process
expect(component.to_s).to include "from 192.168.1.101 at 05/12/2018 " \
"01:35PM (#{"still logged in".green})"
expect(component.to_s).to include "from 192.168.1.101 at 05/11/2018 " \
"07:56PM (#{"gone - no logout".yellow})"
expect(component.to_s).to include "from 192.168.1.101 at 05/12/2018 " \
"01:32PM (3 minutes)"
end
context "when there are no logins found for a user" do
it "prints a message" do
component.config["users"] = { "stoyan" => 2 }
stub_system_call(component)
component.process
expect(component.to_s).to include "no logins found for user"
end
end
end
end
| ruby | MIT | d1cc6db9220243e83fbb1a2bbf91c6a143b9f559 | 2026-01-04T17:46:36.398098Z | false |
taylorthurlow/panda-motd | https://github.com/taylorthurlow/panda-motd/blob/d1cc6db9220243e83fbb1a2bbf91c6a143b9f559/spec/components/filesystems_spec.rb | spec/components/filesystems_spec.rb | # frozen_string_literal: true
require "spec_helper"
require "colorize"
describe Filesystems do
context "with normal config" do
subject(:component) {
create(:filesystems, settings: {
"filesystems" => { "/dev/sda1" => "Ubuntu" },
})
}
it "returns the hash of filesystem info" do
stub_system_call(component)
component.process
expect(component.results).to eq [{
pretty_name: "Ubuntu",
filesystem_name: "/dev/sda1",
size: 111_331_104 * 1024,
used: 70_005_864 * 1024,
avail: 35_646_904 * 1024,
}]
end
context "when printing different units" do
it "prints in terabytes" do
stub_system_call(component)
component.process
results_with_size(10 ** 9)
expect(component.to_s).to include "1.0T"
end
it "prints in gigabytes" do
stub_system_call(component)
component.process
results_with_size(10 ** 6)
expect(component.to_s).to include "1.0G"
end
it "prints in megabytes" do
stub_system_call(component)
component.process
results_with_size(10 ** 3)
expect(component.to_s).to include "1.0M"
end
it "prints in kilobytes" do
stub_system_call(component)
component.process
results_with_size(10 ** 0)
expect(component.to_s).to include "1.0K"
end
it "prints with 3 whole numbers" do
stub_system_call(component)
component.process
results_with_size(123 * 10 ** 6)
expect(component.to_s).to include "126G"
end
it "prints with 1 whole number and 1 decimal place" do
stub_system_call(component)
component.process
results_with_size(1_300_000_000)
expect(component.to_s).to include "1.3T"
end
def results_with_size(size)
component.instance_variable_set(:@results, [{
pretty_name: "Ubuntu",
filesystem_name: "/dev/sda1",
size: size * 1024,
used: (size * 0.5) * 1024,
avail: 35_646_904 * 1024,
}])
end
end
context "when printing usage colors" do
it "uses green from 0 to 75" do
stub_system_call(component)
component.process
results_with_ratio(0.0)
expect(component.to_s.delete(" ")).to include "0%".green
results_with_ratio(0.75)
expect(component.to_s.delete(" ")).to include "75%".green
end
it "uses yellow from 76 to 95" do
stub_system_call(component)
component.process
results_with_ratio(0.76)
expect(component.to_s.delete(" ")).to include "76%".yellow
results_with_ratio(0.95)
expect(component.to_s.delete(" ")).to include "95%".yellow
end
it "uses red from 96 to 100" do
stub_system_call(component)
component.process
results_with_ratio(0.96)
expect(component.to_s.delete(" ")).to include "96%".red
results_with_ratio(1.0)
expect(component.to_s.delete(" ")).to include "100%".red
end
def results_with_ratio(ratio)
component.instance_variable_set(:@results, [{
pretty_name: "Ubuntu",
filesystem_name: "/dev/sda1",
size: 100_000 * 1024,
used: (100_000 * ratio) * 1024,
avail: 35_646_904 * 1024,
}])
end
end
it "prints the filesystem info" do
stub_system_call(component)
component.process
expect(component.to_s).to include "Ubuntu 114G 72G 37G"
end
end
context "with config containing filesystems that are not found" do
subject(:component) {
create(:filesystems, settings: {
"filesystems" => { "/dev/notfound" => "Ubuntu" },
})
}
it "returns the hash of filesystem info" do
stub_system_call(component)
component.process
expect(component.results).to eq ["/dev/notfound was not found"]
end
it "prints the filesystem info" do
stub_system_call(component)
component.process
expect(component.to_s).to include "/dev/notfound was not found"
end
end
end
| ruby | MIT | d1cc6db9220243e83fbb1a2bbf91c6a143b9f559 | 2026-01-04T17:46:36.398098Z | false |
taylorthurlow/panda-motd | https://github.com/taylorthurlow/panda-motd/blob/d1cc6db9220243e83fbb1a2bbf91c6a143b9f559/spec/matchers/should_have_attr_reader.rb | spec/matchers/should_have_attr_reader.rb | # frozen_string_literal: true
# :nocov:
RSpec::Matchers.define :have_attr_reader do |field|
match do |object_instance|
object_instance.respond_to?(field)
end
failure_message do |object_instance|
"expected attr_reader for #{field} on #{object_instance}"
end
failure_message_when_negated do |object_instance|
"expected attr_reader for #{field} not to be defined on #{object_instance}"
end
description do
"assert there is an attr_reader of the given name on the supplied object"
end
end
# :nocov:
| ruby | MIT | d1cc6db9220243e83fbb1a2bbf91c6a143b9f559 | 2026-01-04T17:46:36.398098Z | false |
taylorthurlow/panda-motd | https://github.com/taylorthurlow/panda-motd/blob/d1cc6db9220243e83fbb1a2bbf91c6a143b9f559/lib/panda_motd.rb | lib/panda_motd.rb | # frozen_string_literal: true
require "require_all"
require_rel "panda_motd"
class PandaMOTD
# Creates a new MOTD instance, assuming a config file has been passed as an
# argument to the command.
def self.new_motd
if ARGV[0].nil?
puts "You must provide a config file path as an argument to panda-motd."
else
MOTD.new(ARGV[0])
end
end
# Gets the root path of the gem.
def self.root
File.expand_path("..", __dir__)
end
end
| ruby | MIT | d1cc6db9220243e83fbb1a2bbf91c6a143b9f559 | 2026-01-04T17:46:36.398098Z | false |
taylorthurlow/panda-motd | https://github.com/taylorthurlow/panda-motd/blob/d1cc6db9220243e83fbb1a2bbf91c6a143b9f559/lib/panda_motd/component_error.rb | lib/panda_motd/component_error.rb | # frozen_string_literal: true
require "colorize"
class ComponentError
attr_reader :component, :message
def initialize(component, message)
@component = component
@message = message
end
# Gets a printable error string in red.
def to_s
return "#{@component.name} error: ".red + @message.to_s
end
end
| ruby | MIT | d1cc6db9220243e83fbb1a2bbf91c6a143b9f559 | 2026-01-04T17:46:36.398098Z | false |
taylorthurlow/panda-motd | https://github.com/taylorthurlow/panda-motd/blob/d1cc6db9220243e83fbb1a2bbf91c6a143b9f559/lib/panda_motd/component.rb | lib/panda_motd/component.rb | # frozen_string_literal: true
class Component
attr_reader :name, :errors, :results, :config
def initialize(motd, name)
@name = name
@motd = motd
@config = motd.config.component_config(@name)
@errors = []
end
# Evaluates the component so that it has some meaningful output when it comes
# time to print the MOTD.
def process
raise NotImplementedError
end
# Gives the output of a component as a string.
def to_s
raise NotImplementedError
end
# The number of lines to print before the component in the context of the
# entire MOTD. 1 by default, if not configured.
def lines_before
@motd.config.component_config(@name)["lines_before"] || 1
end
# The number of lines to print after the component in the context of the
# entire MOTD. 1 by default, if not configured.
def lines_after
@motd.config.component_config(@name)["lines_after"] || 1
end
end
| ruby | MIT | d1cc6db9220243e83fbb1a2bbf91c6a143b9f559 | 2026-01-04T17:46:36.398098Z | false |
taylorthurlow/panda-motd | https://github.com/taylorthurlow/panda-motd/blob/d1cc6db9220243e83fbb1a2bbf91c6a143b9f559/lib/panda_motd/version.rb | lib/panda_motd/version.rb | # frozen_string_literal: true
class PandaMOTD
#:nodoc:
VERSION ||= "0.0.12"
end
| ruby | MIT | d1cc6db9220243e83fbb1a2bbf91c6a143b9f559 | 2026-01-04T17:46:36.398098Z | false |
taylorthurlow/panda-motd | https://github.com/taylorthurlow/panda-motd/blob/d1cc6db9220243e83fbb1a2bbf91c6a143b9f559/lib/panda_motd/motd.rb | lib/panda_motd/motd.rb | # frozen_string_literal: true
require "sysinfo"
class MOTD
attr_reader :config, :components
# Creates an MOTD by parsing the provided config file, and processing each
# component.
#
# @param config_path [String] The path to the configuration file. If not
# provided, the default config path will be used.
# @param process [Boolean] whether or not to actually process and evaluate
# the printable results of each component
def initialize(config_path = nil, process = true)
@config = Config.new(config_path)
@components = @config.components_enabled.map { |ce| ce.new(self) }
@components.each(&:process) if process
end
# Takes each component on the MOTD and joins them together in a printable
# format. It inserts two newlines in between each component, ensuring that
# there is one empty line between each. If a component has any errors, the
# error will be printed in a clean way.
def to_s
@components.map do |c|
if c.errors.any?
c.errors.map(&:to_s).join("\n")
else
c.to_s
end
end.join("\n\n")
end
end
| ruby | MIT | d1cc6db9220243e83fbb1a2bbf91c6a143b9f559 | 2026-01-04T17:46:36.398098Z | false |
taylorthurlow/panda-motd | https://github.com/taylorthurlow/panda-motd/blob/d1cc6db9220243e83fbb1a2bbf91c6a143b9f559/lib/panda_motd/config.rb | lib/panda_motd/config.rb | # frozen_string_literal: true
require "yaml"
require "fileutils"
class Config
attr_reader :file_path
# @param file_path [String] The file path to look for the configuration file.
# If not provided, the default file path will be used.
def initialize(file_path = nil)
@file_path = file_path || File.join(Dir.home, ".config", "panda-motd.yaml")
unless File.exist?(@file_path)
create_config(@file_path)
puts "panda-motd created a default config file at: #{@file_path}"
end
load_config(@file_path)
end
# A list of enabled components' class constants.
def components_enabled
# iterate config hash and grab names of enabled components
enabled = @config["components"].map { |c, s| c if s["enabled"] }.compact
# get the class constant
enabled.map { |e| Config.component_classes[e.to_sym] }
end
# Gets the configuration for a component.
#
# @param component_name [String] the name of the component to fetch the
# configuration for
def component_config(component_name)
@config["components"][component_name.to_s]
end
# The mapping of component string names to class constants.
def self.component_classes
{
ascii_text_art: ASCIITextArt,
service_status: ServiceStatus,
uptime: Uptime,
ssl_certificates: SSLCertificates,
filesystems: Filesystems,
last_login: LastLogin,
fail_2_ban: Fail2Ban,
}
end
private
# Creates a configuration file at a given file path, from the default
# configuration file.
#
# @param file_path [String] the file path at which to create the config
def create_config(file_path)
default_config_path = File.join(
File.dirname(__dir__), "panda_motd", "default_config.yaml"
)
FileUtils.cp(default_config_path, file_path)
end
# Loads a configuration file.
#
# @param file_path [String] the file path of the config to load
def load_config(file_path)
@config = YAML.safe_load(File.read(file_path))
@config["components"] = [] if @config["components"].nil?
end
end
| ruby | MIT | d1cc6db9220243e83fbb1a2bbf91c6a143b9f559 | 2026-01-04T17:46:36.398098Z | false |
taylorthurlow/panda-motd | https://github.com/taylorthurlow/panda-motd/blob/d1cc6db9220243e83fbb1a2bbf91c6a143b9f559/lib/panda_motd/components/ssl_certificates.rb | lib/panda_motd/components/ssl_certificates.rb | # frozen_string_literal: true
require "date"
class SSLCertificates < Component
def initialize(motd)
super(motd, "ssl_certificates")
end
# @see Component#process
def process
@certs = @config["certs"]
@results = cert_dates(@certs)
end
# Prints the list of SSL certificates with their statuses. If a certificate
# is not found at the configured location, a message will be printed which
# explains this.
def to_s
<<~HEREDOC
SSL Certificates:
#{sorted_results.map do |cert|
return " #{cert}" if cert.is_a? String # print the not found message
parse_cert(cert)
end.join("\n")}
HEREDOC
end
private
# Takes an entry from `@results` and formats it in a way that is conducive
# to being printed in the context of the MOTD.
#
# @param cert [Array] a two-element array in the same format as the return
# value of {#parse_result}
def parse_cert(cert)
name_portion = cert[0].ljust(longest_cert_name_length + 6, " ")
status_sym = cert_status(cert[1])
status = cert_status_strings[status_sym].to_s
colorized_status = status.colorize(cert_status_colors[status_sym])
date_portion = cert[1].strftime("%e %b %Y %H:%M:%S%p")
" #{name_portion} #{colorized_status} #{date_portion}"
end
# Determines the length of the longest SSL certificate name for use in
# formatting the output of the component.
#
# @return [Integer] the length of the longest certificate name
def longest_cert_name_length
@results.map { |r| r[0].length }.max
end
# Takes the results array and sorts it according to the configured sort
# method. If the option is not set or is set improperly, it will default to
# alphabetical.
def sorted_results
if @config["sort_method"] == "alphabetical"
@results.sort_by { |c| c[0] }
elsif @config["sort_method"] == "expiration"
@results.sort_by { |c| c[1] }
else # default to alphabetical
@results.sort_by { |c| c[0] }
end
end
# Takes a list of certificates and compiles a list of results for each
# certificate. If a certificate was not found, a notice will be returned
# instead.
#
# @return [Array] An array of parsed results. If there was an error, the
# element will be just a string. If it was successful, the element will be
# another two-element array in the same format as the return value of
# {#parse_result}.
def cert_dates(certs)
certs.map do |name, path|
if File.exist?(path)
parse_result(name, path)
else
"Certificate #{name} not found at path: #{path}"
end
end.compact # remove nil entries, will have nil if error ocurred
end
# Uses `openssl` to obtain and parse and expiration date for the certificate.
#
# @param name [String] the name of the SSL certificate
# @param path [String] the file path to the SSL certificate
#
# @return [Array] A pair where the first element is the configured name of
# the SSL certificate, and the second element is the expiration date of
# the certificate.
def parse_result(name, path)
cmd_result = `openssl x509 -in #{path} -dates`
# match indices: 1 - month, 2 - day, 3 - time, 4 - year, 5 - zone
exp = /notAfter=([A-Za-z]+) +(\d+) +([\d:]+) +(\d{4}) +([A-Za-z]+)\n/
parsed = cmd_result.match(exp)
if parsed.nil?
@errors << ComponentError.new(self, "Unable to find certificate " \
"expiration date")
nil
else
expiry_date = Time.parse([1, 2, 4, 3, 5].map { |n| parsed[n] }.join(" "))
[name, expiry_date]
end
rescue ArgumentError
@errors << ComponentError.new(self, "Found expiration date, but unable " \
"to parse as date")
[name, Time.now]
end
# Maps an expiration date to a symbol representing the expiration status of
# an SSL certificate.
#
# @param expiry_date [Time] the time at which the certificate expires
#
# @return [Symbol] A symbol representing the expiration status of the
# certificate. Valid values are `:expiring`, `:expired`, and `:valid`.
def cert_status(expiry_date)
if (Time.now...Time.now + 30).cover? expiry_date # ... range excludes last
:expiring
elsif Time.now >= expiry_date
:expired
else
:valid
end
end
# Maps a certificate expiration status to a color that represents it.
def cert_status_colors
{
valid: :green,
expiring: :yellow,
expired: :red,
}
end
# Maps a certificate expiration status to a string which can be prefixed to
# the expiration date, to aid in explaining when the certificate expires.
def cert_status_strings
{
valid: "valid until",
expiring: "expiring at",
expired: "expired at",
}
end
end
| ruby | MIT | d1cc6db9220243e83fbb1a2bbf91c6a143b9f559 | 2026-01-04T17:46:36.398098Z | false |
taylorthurlow/panda-motd | https://github.com/taylorthurlow/panda-motd/blob/d1cc6db9220243e83fbb1a2bbf91c6a143b9f559/lib/panda_motd/components/uptime.rb | lib/panda_motd/components/uptime.rb | # frozen_string_literal: true
require "sysinfo"
class Uptime < Component
attr_reader :days, :hours, :minutes
def initialize(motd)
super(motd, "uptime")
end
# Calculates the number of days, hours, and minutes based on the current
# uptime value.
#
# @see Component#process
def process
uptime = SysInfo.new.uptime
@days = (uptime / 24).floor
@hours = (uptime - @days * 24).floor
@minutes = ((uptime - @days * 24 - hours) * 60).floor
end
# Gets a printable uptime string with a prefix. The prefix can be configured,
# and defaults to "up".
def to_s
"#{@config["prefix"] || "up"} #{format_uptime}"
end
private
# Formats the uptime values in such a way that it is easier to read. If any
# of the measurements are zero, that part is omitted. Words are properly
# pluralized.
#
# Examples:
#
# `3d 20h 55m` becomes `3 days, 20 hours, 55 minutes`
#
# `3d 0h 55m` becomes `3 days, 55 minutes`
def format_uptime
[@days, @hours, @minutes].zip(%w[day hour minute])
.reject { |n, _word| n.zero? }
.map { |n, word| "#{n} #{word}#{"s" if n != 1}" }
.join(", ")
end
end
| ruby | MIT | d1cc6db9220243e83fbb1a2bbf91c6a143b9f559 | 2026-01-04T17:46:36.398098Z | false |
taylorthurlow/panda-motd | https://github.com/taylorthurlow/panda-motd/blob/d1cc6db9220243e83fbb1a2bbf91c6a143b9f559/lib/panda_motd/components/ascii_text_art.rb | lib/panda_motd/components/ascii_text_art.rb | # frozen_string_literal: true
require "artii"
require "colorize"
class ASCIITextArt < Component
def initialize(motd)
super(motd, "ascii_text_art")
end
def process
@text = `#{@config["command"]}`
@art = Artii::Base.new font: @config["font"]
@results = @art.asciify(@text)
@results = @results.colorize(@config["color"].to_sym) if @config["color"]
rescue Errno::EISDIR # Artii doesn't handle invalid font names very well
@errors << ComponentError.new(self, "Invalid font name")
end
def to_s
@results
end
end
| ruby | MIT | d1cc6db9220243e83fbb1a2bbf91c6a143b9f559 | 2026-01-04T17:46:36.398098Z | false |
taylorthurlow/panda-motd | https://github.com/taylorthurlow/panda-motd/blob/d1cc6db9220243e83fbb1a2bbf91c6a143b9f559/lib/panda_motd/components/filesystems.rb | lib/panda_motd/components/filesystems.rb | # frozen_string_literal: true
require "ruby-units"
require "colorize"
class Filesystems < Component
def initialize(motd)
super(motd, "filesystems")
end
def process
@results = parse_filesystem_usage(@config["filesystems"])
end
def to_s
name_col_size = @results.select { |r| r.is_a? Hash }
.map { |r| r[:pretty_name].length }
.max || 0
size_w_padding = (name_col_size + 6) > 13 ? (name_col_size + 6) : 13
result = +"Filesystems".ljust(size_w_padding, " ")
result << "Size Used Free Use%\n"
@results.each do |filesystem|
result << format_filesystem(filesystem, size_w_padding)
end
result
end
private
def format_filesystem(filesystem, size)
return " #{filesystem}\n" if filesystem.is_a? String # handle fs not found
# filesystem name
result = +""
result << " #{filesystem[:pretty_name]}".ljust(size, " ")
# statistics (size, used, free, use%)
[:size, :used, :avail].each do |metric|
result << format_metric(filesystem, metric)
end
percent_used = calc_percent_used(filesystem)
result << format_percent_used(percent_used)
result << "\n"
# visual bar representation of use%
result << generate_usage_bar(filesystem, size, percent_used)
result
end
def generate_usage_bar(filesystem, size, percent_used)
result = +""
total_ticks = size + 18
used_ticks = (total_ticks * (percent_used.to_f / 100)).round
result << " [#{("=" * used_ticks).send(pct_color(percent_used))}" \
"#{("=" * (total_ticks - used_ticks)).light_black}]"
result << "\n" unless filesystem == @results.last
result
end
def pct_color(percentage)
case percentage
when 0..75 then :green
when 76..95 then :yellow
when 96..100 then :red
else :white
end
end
def calc_percent_used(filesystem)
((filesystem[:used].to_f / filesystem[:size].to_f) * 100).round
end
def format_percent_used(percent_used)
(percent_used.to_s.rjust(3, " ") + "%").send(pct_color(percent_used))
end
def calc_metric(value)
Unit.new("#{value} bytes").convert_to(calc_units(value))
end
def format_metric(filesystem, metric)
# we have 4 characters of space to include the number, a potential
# decimal point, and the unit character at the end. if the whole number
# component is 3+ digits long then we omit the decimal point and just
# display the whole number component. if the whole number component is
# 2 digits long, we can't afford to use a decimal point, so we still
# only display the whole number component. if the whole number
# component is 1 digit long, we use the single whole number component
# digit, a decimal point, a single fractional digit, and the unit
# character.
value = calc_metric(filesystem[metric])
whole_number_length = value.scalar.floor.to_s.length
round_amount = whole_number_length > 1 ? 0 : 1
formatted = value.scalar.round(round_amount).to_s + value.units[0].upcase
formatted.rjust(4, " ") + " "
end
def calc_units(value)
if value > 10 ** 12
"terabytes"
elsif value > 10 ** 9
"gigabytes"
elsif value > 10 ** 6
"megabytes"
elsif value > 10 ** 3
"kilobytes"
else
"bytes"
end
end
def parse_filesystem_usage(filesystems)
entries = `BLOCKSIZE=1024 df --output=source,size,used,avail`.lines.drop(1)
filesystems.map do |filesystem, pretty_name|
matching_entry = entries.map(&:split).find { |e| e.first == filesystem }
next "#{filesystem} was not found" unless matching_entry
filesystem_name, size, used, avail = matching_entry
{
pretty_name: pretty_name,
filesystem_name: filesystem_name,
size: size.to_i * 1024,
used: used.to_i * 1024,
avail: avail.to_i * 1024,
}
end
end
end
| ruby | MIT | d1cc6db9220243e83fbb1a2bbf91c6a143b9f559 | 2026-01-04T17:46:36.398098Z | false |
taylorthurlow/panda-motd | https://github.com/taylorthurlow/panda-motd/blob/d1cc6db9220243e83fbb1a2bbf91c6a143b9f559/lib/panda_motd/components/fail_2_ban.rb | lib/panda_motd/components/fail_2_ban.rb | # frozen_string_literal: true
class Fail2Ban < Component
def initialize(motd)
super(motd, "fail_2_ban")
end
def process
@results = {
jails: {},
}
@config["jails"].each do |jail|
status = jail_status(jail)
@results[:jails][jail] = {
total: status[:total],
current: status[:current],
}
end
end
def to_s
result = +"Fail2Ban:\n"
@results[:jails].each do |name, stats|
result << " #{name}:\n"
result << " Total bans: #{stats[:total]}\n"
result << " Current bans: #{stats[:current]}\n"
end
result.gsub!(/\s$/, "")
end
private
def jail_status(jail)
cmd_result = `fail2ban-client status #{jail}`
if cmd_result =~ /Sorry but the jail '#{jail}' does not exist/
@errors << ComponentError.new(self, "Invalid jail name '#{jail}'.")
else
total = cmd_result.match(/Total banned:\s+([0-9]+)/)[1].to_i
current = cmd_result.match(/Currently banned:\s+([0-9]+)/)[1].to_i
end
{ total: total, current: current }
end
end
| ruby | MIT | d1cc6db9220243e83fbb1a2bbf91c6a143b9f559 | 2026-01-04T17:46:36.398098Z | false |
taylorthurlow/panda-motd | https://github.com/taylorthurlow/panda-motd/blob/d1cc6db9220243e83fbb1a2bbf91c6a143b9f559/lib/panda_motd/components/service_status.rb | lib/panda_motd/components/service_status.rb | # frozen_string_literal: true
require "colorize"
class ServiceStatus < Component
def initialize(motd)
super(motd, "service_status")
end
# @see Component#process
def process
@services = @config["services"]
@results = parse_services(@services)
end
# Gets a printable string to be printed in the MOTD. If there are no services
# found in the result, it prints a warning message.
def to_s
return "Services:\n No matching services found." unless @results.any?
longest_name_size = @results.keys.map { |k| k.to_s.length }.max
result = <<~HEREDOC
Services:
#{@results.map do |(name, status)|
spaces = (" " * (longest_name_size - name.to_s.length + 1))
status_part = status.to_s.colorize(service_colors[status.to_sym])
" #{name}#{spaces}#{status_part}"
end.join("\n")}
HEREDOC
result.gsub(/\s$/, "")
end
private
# Runs a `systemctl` command to determine the state of a service. If the state
# of the service was unable to be determined, an error will be added to the
# component.
#
# @param service [String] the name of the systemctl service
#
# @return [String] the state of the systemctl service
def parse_service(service)
cmd_result = `systemctl is-active #{service[0]}`.strip
if cmd_result.empty?
@errors << ComponentError.new(self, "systemctl output was blank.")
end
cmd_result
end
# Takes a list of services from a configuration file, and turns them into a
# hash with the service states as values.
#
# @param services [Array] a two-element array where the first element is the
# name of the systemctl service, and the second is the pretty name that
# represents it.
#
# @return [Hash]
# * `key`: The symbolized name of the systemctl service
# * `value`: The symbolized service state
def parse_services(services)
services.map { |s| [s[1].to_sym, parse_service(s).to_sym] }.to_h
end
# A hash of mappings between a service state and a color which represents it.
# The hash has a default value of red in order to handle unexpected service
# status strings returned by `systemctl`.
def service_colors
colors = Hash.new(:red)
colors[:active] = :green
colors[:inactive] = :yellow
colors[:failed] = :red
colors
end
end
| ruby | MIT | d1cc6db9220243e83fbb1a2bbf91c6a143b9f559 | 2026-01-04T17:46:36.398098Z | false |
taylorthurlow/panda-motd | https://github.com/taylorthurlow/panda-motd/blob/d1cc6db9220243e83fbb1a2bbf91c6a143b9f559/lib/panda_motd/components/last_login.rb | lib/panda_motd/components/last_login.rb | # frozen_string_literal: true
require "date"
class LastLogin < Component
def initialize(motd)
super(motd, "last_login")
end
# @see Component#process
def process
@users = @config["users"]
@results = parse_last_logins
end
# @see Component#to_s
def to_s
<<~HEREDOC
Last Login:
#{@results.map { |u, l| parse_result(u, l) }.join("\n")}
HEREDOC
end
private
# Takes the list of processed results and generates a complete printable
# component string.
#
# @param user [String] the username to generate a string for
# @param logins [Array<Hash>] an array of hashes with username keys and hash
# values containing the login data (see {#hashify_login})
#
# @return [String] the printable string for a single user
def parse_result(user, logins)
logins_part = if logins.empty?
" no logins found for user."
else
longest_size = logins.map { |l| l[:location].length }.max
logins.map { |l| parse_login(l, longest_size) }.join("\n")
end
<<~HEREDOC
#{user}:
#{logins_part}
HEREDOC
end
# Takes login data and converts it to a heplful printable string.
#
# @param login [Hash] the login data, see {#hashify_login}
# @param longest_size [Integer] the longest string length to help with string
# formatting
#
# @return [String] the formatted string for printing
def parse_login(login, longest_size)
location = login[:location].ljust(longest_size, " ")
start = login[:time_start].strftime("%m/%d/%Y %I:%M%p")
finish = if login[:time_end].is_a? String # not a date
if login[:time_end] == "still logged in"
login[:time_end].green
else
login[:time_end].yellow
end
else
"#{((login[:time_end] - login[:time_start]) / 60).to_i} minutes"
end
" from #{location} at #{start} (#{finish})"
end
# Takes a list of configured usernames and grabs login data from the system.
#
# @return [Hash{Symbol => Hash}] a hash with username keys and hash values
# containing the login data (see {#hashify_login})
def parse_last_logins
@users.map do |(username, num_logins)|
cmd_result = `last --time-format=iso #{username}`
logins = cmd_result.lines
.select { |entry| entry.start_with?(username) }
.take(num_logins)
[username.to_sym, logins.map! { |l| hashify_login(l, username) }]
end.to_h
end
# A hash representation of a single login.
#
# @param login [String] the raw string result from the call to the system
# containing various bits of login information
# @param username [String] the username of the logged user
#
# @return [Hash] the parsed login entry data, with symbol keys
def hashify_login(login, username)
re = login.chomp.split(/(?:\s{2,})|(?<=\d)(?:\s-\s)/)
date = re[4].scan(/\d{4}-\d{2}-[\dT:]+-\d{4}/)
time_end = date.any? ? Time.parse(re[4]) : re[4]
{
username: username, # string username
location: re[2], # string login location, an IP address
time_start: Time.parse(re[3]),
time_end: time_end, # Time or string, could be "still logged in"
}
end
end
| ruby | MIT | d1cc6db9220243e83fbb1a2bbf91c6a143b9f559 | 2026-01-04T17:46:36.398098Z | false |
eggcaker/jekyll-org | https://github.com/eggcaker/jekyll-org/blob/a49fb272b64c063ba11cb3334f73df7c85c12b77/spec/helper.rb | spec/helper.rb | require 'jekyll'
require File.expand_path('../lib/jekyll-org', File.dirname(__FILE__))
Jekyll.logger.log_level = :error
RSpec.configure do |config|
config.run_all_when_everything_filtered = true
config.filter_run :focus
config.order = 'random'
SOURCE_DIR = File.expand_path("../fixtures", __FILE__)
DEST_DIR = File.expand_path("../dest", __FILE__)
def source_dir(*files)
File.join(SOURCE_DIR, *files)
end
def dest_dir(*files)
File.join(DEST_DIR, *files)
end
end
| ruby | MIT | a49fb272b64c063ba11cb3334f73df7c85c12b77 | 2026-01-04T17:46:40.336272Z | false |
eggcaker/jekyll-org | https://github.com/eggcaker/jekyll-org/blob/a49fb272b64c063ba11cb3334f73df7c85c12b77/spec/test_jekyll-org.rb | spec/test_jekyll-org.rb | require 'helper'
describe("should working with unit test") do
it "added some test cases" do
end
end
| ruby | MIT | a49fb272b64c063ba11cb3334f73df7c85c12b77 | 2026-01-04T17:46:40.336272Z | false |
eggcaker/jekyll-org | https://github.com/eggcaker/jekyll-org/blob/a49fb272b64c063ba11cb3334f73df7c85c12b77/lib/jekyll-org.rb | lib/jekyll-org.rb | if Jekyll::VERSION < '3.0'
raise Jekyll::FatalException, 'This version of jekyll-org is only compatible with Jekyll v3 and above.'
end
require_relative './jekyll-org/converter'
module Jekyll
module Filters
def orgify(input)
site = @context.registers[:site]
converter = site.find_converter_instance(Jekyll::Converters::Org)
converter.convert(input)
end
end
module OrgDocument
def org_file?
Jekyll::Converters::Org.matches(extname)
end
## override: read file & parse YAML... in this case, don't parse YAML
# see also: https://github.com/jekyll/jekyll/blob/master/lib/jekyll/document.rb
def read_content(opts = {})
return super(**opts) unless org_file? # defer to default behaviour when not org file
self.content = File.read(path, **Utils.merged_file_read_opts(site, opts))
converter = site.find_converter_instance(Jekyll::Converters::Org)
parser, settings = converter.parse_org(self.content)
@data = Utils.deep_merge_hashes(self.data, settings)
self.content = converter.actually_convert(parser)
end
end
module OrgPage
# Don't parse YAML blocks when working with an org file, parse it as
# an org file and then extracts the settings from there.
def read_yaml(base, name, opts = {})
extname = File.extname(name)
return super unless Jekyll::Converters::Org.matches(extname)
filename = File.join(base, name)
self.data ||= Hash.new()
self.content = File.read(@path || site.in_source_dir(base, name),
**Utils.merged_file_read_opts(site, opts))
converter = site.find_converter_instance(Jekyll::Converters::Org)
parser, settings = converter.parse_org(self.content)
self.content = converter.actually_convert(parser)
self.data = Utils.deep_merge_hashes(self.data, settings)
end
end
class Collection
# make jekyll collections aside from _posts also convert org files.
def read
filtered_entries.each do |file_path|
full_path = collection_dir(file_path)
next if File.directory?(full_path)
if Utils.has_yaml_header?(full_path) ||
Jekyll::Converters::Org.matches_path(full_path)
read_document(full_path)
else
read_static_file(file_path, full_path)
end
end
# TODO remove support for jekyll 3 on 4s release
(Jekyll::VERSION < '4.0') ? docs.sort! : sort_docs!
end
end
class Reader
def retrieve_org_files(dir, files)
retrieve_pages(dir, files)
end
# don't interpret org files without YAML as static files.
def retrieve_static_files(dir, files)
org_files, static_files = files.partition(&Jekyll::Converters::Org.method(:matches_path))
retrieve_org_files(dir, org_files) unless org_files.empty?
site.static_files.concat(StaticFileReader.new(site, dir).read(static_files))
end
end
end
Jekyll::Document.prepend(Jekyll::OrgDocument)
Jekyll::Page.prepend(Jekyll::OrgPage)
| ruby | MIT | a49fb272b64c063ba11cb3334f73df7c85c12b77 | 2026-01-04T17:46:40.336272Z | false |
eggcaker/jekyll-org | https://github.com/eggcaker/jekyll-org/blob/a49fb272b64c063ba11cb3334f73df7c85c12b77/lib/jekyll-org/converter.rb | lib/jekyll-org/converter.rb | require 'csv'
require 'org-ruby'
require_relative './utils'
module Jekyll
module Converters
class Org < Converter
include Jekyll::OrgUtils
safe true
priority :low
# true if current file is an org file
def self.matches(ext)
ext =~ /org/i
end
# matches, but accepts complete path
def self.matches_path(path)
matches(File.extname(path))
end
def matches(ext)
self.class.matches ext
end
def output_ext(ext)
'.html'
end
# because by the time an org file reaches the
# converter... it will have already been converted.
def convert(content)
content
end
def actually_convert(content)
case content
when Orgmode::Parser
if liquid_enabled?(content)
content.to_html.gsub("‘", "'").gsub("’", "'")
else
'{% raw %} ' + content.to_html + ' {% endraw %}'
end
else
parser, variables = parse_org(content)
convert(parser)
end
end
def parse_org(content)
parser = Orgmode::Parser.new(content, parser_options)
settings = { :liquid => org_config.fetch("liquid", false) }
parser.in_buffer_settings.each_pair do |key, value|
# Remove #+TITLE from the buffer settings to avoid double exporting
parser.in_buffer_settings.delete(key) if key =~ /title/i
assign_setting(key, value, settings)
end
return parser, settings
end
private
def config_liquid_enabled?
org_config.fetch("liquid", false)
end
def liquid_enabled?(parser)
tuple = parser.in_buffer_settings.each_pair.find do |key, _|
key =~ /liquid/i
end
if tuple.nil?
config_liquid_enabled? # default value, as per config
else
_parse_boolean(tuple[1], "unknown LIQUID setting")
end
end
# see https://github.com/bdewey/org-ruby/blob/master/lib/org-ruby/parser.rb
def parser_options
org_config.fetch("parser_options", { markup_file: 'html.tags.yml' })
end
def assign_setting(key, value, settings)
key = key.downcase
case key
when "liquid"
value = _parse_boolean(value, "unknown LIQUID setting")
settings[:liquid] = value unless value.nil?
when "tags", "categories"
# Parse a string of tags separated by spaces into a list.
# Tags containing spaces can be wrapped in quotes,
# e.g. '#+TAGS: foo "with spaces"'.
#
# The easiest way to do this is to use rubys builtin csv parser
# and use spaces instead of commas as column separator.
settings[key] = CSV::parse_line(value, col_sep: ' ')
else
value_bool = _parse_boolean(value)
settings[key] = (value_bool.nil?) ? value : value_bool
end
end
@@truthy_regexps = [/^enabled$/, /^yes$/, /^true$/]
@@falsy_regexps = [/^disabled$/, /^no$/, /^false$/]
def _parse_boolean(value, error_msg=nil)
case value.downcase
when *@@truthy_regexps
true
when *@@falsy_regexps
false
else
unless error_msg.nil?
Jekyll.logger.warn("OrgDocument:", error_msg + ": #{value}")
end
end
end
end
end
end
| ruby | MIT | a49fb272b64c063ba11cb3334f73df7c85c12b77 | 2026-01-04T17:46:40.336272Z | false |
eggcaker/jekyll-org | https://github.com/eggcaker/jekyll-org/blob/a49fb272b64c063ba11cb3334f73df7c85c12b77/lib/jekyll-org/utils.rb | lib/jekyll-org/utils.rb | module Jekyll
module OrgUtils
def self.site
@@site ||= Jekyll.configuration({})
end
def self.org_config
site["org"] || Hash.new()
end
def site
OrgUtils.site
end
def org_config
OrgUtils.org_config
end
end
end
| ruby | MIT | a49fb272b64c063ba11cb3334f73df7c85c12b77 | 2026-01-04T17:46:40.336272Z | false |
beenhero/omniauth-weibo-oauth2 | https://github.com/beenhero/omniauth-weibo-oauth2/blob/5ef094fe0e264a98e99055bae958f55c17638786/lib/omniauth-weibo-oauth2.rb | lib/omniauth-weibo-oauth2.rb | require "omniauth-weibo-oauth2/version"
require 'omniauth/strategies/weibo'
| ruby | MIT | 5ef094fe0e264a98e99055bae958f55c17638786 | 2026-01-04T17:46:39.390113Z | false |
beenhero/omniauth-weibo-oauth2 | https://github.com/beenhero/omniauth-weibo-oauth2/blob/5ef094fe0e264a98e99055bae958f55c17638786/lib/omniauth-weibo-oauth2/version.rb | lib/omniauth-weibo-oauth2/version.rb | module OmniAuth
module WeiboOauth2
VERSION = "0.5.3"
end
end
| ruby | MIT | 5ef094fe0e264a98e99055bae958f55c17638786 | 2026-01-04T17:46:39.390113Z | false |
beenhero/omniauth-weibo-oauth2 | https://github.com/beenhero/omniauth-weibo-oauth2/blob/5ef094fe0e264a98e99055bae958f55c17638786/lib/omniauth/strategies/weibo.rb | lib/omniauth/strategies/weibo.rb | require "omniauth-oauth2"
module OmniAuth
module Strategies
class Weibo < OmniAuth::Strategies::OAuth2
option :client_options, {
:site => "https://api.weibo.com",
:authorize_url => "/oauth2/authorize",
:token_url => "/oauth2/access_token",
:token_method => :post
}
option :token_params, {
:parse => :json
}
uid do
raw_info['id']
end
info do
{
:nickname => raw_info['screen_name'],
:name => raw_info['name'],
:location => raw_info['location'],
:image => image_url,
:description => raw_info['description'],
:urls => {
'Blog' => raw_info['url'],
'Weibo' => raw_info['domain'].empty? ? "https://weibo.com/u/#{raw_info['id']}" : "https://weibo.com/#{raw_info['domain']}",
}
}
end
extra do
{
:raw_info => raw_info
}
end
def callback_url
token_params_redirect || (full_host + script_name + callback_path)
end
def token_params_redirect
token_params['redirect_uri'] || token_params[:redirect_uri]
end
def raw_info
access_token.options[:mode] = :query
access_token.options[:param_name] = 'access_token'
@uid ||= access_token.get('/2/account/get_uid.json').parsed["uid"]
@raw_info ||= access_token.get("/2/users/show.json", :params => {:uid => @uid}).parsed
end
def find_image
raw_info[%w(avatar_hd avatar_large profile_image_url).find { |e| raw_info[e].present? }]
end
#url: option: size:
#avatar_hd original original_size
#avatar_large large 180x180
#profile_image_url middle 50x50
# small 30x30
#default is middle
def image_url
image_size = options[:image_size] || :middle
case image_size.to_sym
when :original
url = raw_info['avatar_hd']
when :large
url = raw_info['avatar_large']
when :small
url = raw_info['avatar_large'].sub('/180/','/30/')
else
url = raw_info['profile_image_url']
end
end
##
# You can pass +display+, +with_offical_account+ or +state+ params to the auth request, if
# you need to set them dynamically. You can also set these options
# in the OmniAuth config :authorize_params option.
#
# /auth/weibo?display=mobile&with_offical_account=1
#
def authorize_params
super.tap do |params|
%w[display with_offical_account forcelogin state].each do |v|
if request.params[v]
params[v.to_sym] = request.params[v]
end
session["omniauth.state"] = params[v.to_sym] if v == 'state'
end
end
end
protected
def build_access_token
params = {
'client_id' => client.id,
'client_secret' => client.secret,
'code' => request.params['code'],
'grant_type' => 'authorization_code',
'redirect_uri' => callback_url
}.merge(token_params.to_hash(symbolize_keys: true))
client.get_token(params, deep_symbolize(options.token_params))
end
end
end
end
OmniAuth.config.add_camelization "weibo", "Weibo"
| ruby | MIT | 5ef094fe0e264a98e99055bae958f55c17638786 | 2026-01-04T17:46:39.390113Z | false |
codykrieger/ace-rails-ap | https://github.com/codykrieger/ace-rails-ap/blob/d28a3e929b7d4b0fb842afb1fdef024a752fca1a/lib/ace-rails-ap.rb | lib/ace-rails-ap.rb | require 'ace/rails'
| ruby | MIT | d28a3e929b7d4b0fb842afb1fdef024a752fca1a | 2026-01-04T17:46:18.855250Z | false |
codykrieger/ace-rails-ap | https://github.com/codykrieger/ace-rails-ap/blob/d28a3e929b7d4b0fb842afb1fdef024a752fca1a/lib/ace/rails.rb | lib/ace/rails.rb | module Ace
module Rails
if ::Rails.version < "3.1"
# no dice!
else
require 'ace/rails/engine'
end
require "ace/rails/version"
end
end
| ruby | MIT | d28a3e929b7d4b0fb842afb1fdef024a752fca1a | 2026-01-04T17:46:18.855250Z | false |
codykrieger/ace-rails-ap | https://github.com/codykrieger/ace-rails-ap/blob/d28a3e929b7d4b0fb842afb1fdef024a752fca1a/lib/ace/rails/version.rb | lib/ace/rails/version.rb | module Ace
module Rails
VERSION = "4.5"
end
end
| ruby | MIT | d28a3e929b7d4b0fb842afb1fdef024a752fca1a | 2026-01-04T17:46:18.855250Z | false |
codykrieger/ace-rails-ap | https://github.com/codykrieger/ace-rails-ap/blob/d28a3e929b7d4b0fb842afb1fdef024a752fca1a/lib/ace/rails/engine.rb | lib/ace/rails/engine.rb | module Ace
module Rails
mattr_accessor :include_modes
class Engine < ::Rails::Engine
initializer 'ace-rails-ap.assets.precompile' do |app|
app.config.assets.precompile +=
if Ace::Rails.include_modes.present?
Ace::Rails.include_modes.each_with_object([]) { |mode, assets|
assets << "ace/worker-#{mode}-*.js"
assets << "ace/mode-#{mode}-*.js"
}
else
%w[ace/worker-*.js ace/mode-*.js]
end
end
end
end
end
| ruby | MIT | d28a3e929b7d4b0fb842afb1fdef024a752fca1a | 2026-01-04T17:46:18.855250Z | false |
twopoint718/reactive_record | https://github.com/twopoint718/reactive_record/blob/0d688eeeb508933d239e00ed3740dc5b93160720/spec/reactive_record_spec.rb | spec/reactive_record_spec.rb | require 'rspec'
require_relative '../lib/reactive_record'
include ReactiveRecord
describe 'ReactiveRecord' do
before :all do
# db setup
@dbname = "reactive_record_test_#{Process.pid}"
# N.B. all reactive_record methods are read only and so I believe
# that it is valid to share a db connection. Nothing reactive record
# does should mutate any global state
system "createdb #{@dbname}"
@db = PG.connect dbname: @dbname
@db.exec File.read('spec/seed/database.sql')
end
after :all do
# db teardown
@db.close
system "dropdb #{@dbname}"
end
context '#model_definition' do
it 'generates an employee model def' do
model_definition(@db, 'employees').should ==
<<-EOS.gsub(/^ {10}/, '')
class Employees < ActiveRecord::Base
set_table_name 'employees'
set_primary_key :id
validate :id, :name, :email, :start_date, presence: true
validate :email, uniqueness: true
validate { errors.add(:email, "Expected TODO") unless email =~ /.*@example.com/ }
validate { errors.add(:start_date, "Expected TODO") unless start_date >= Date.parse(\"2009-04-13\") }
validate { errors.add(:start_date, "Expected TODO") unless start_date <= Time.now.to_date + 365 }
end
EOS
end
it 'generates a project model def' do
model_definition(@db, 'projects').should ==
<<-EOS.gsub(/^ {10}/, '')
class Projects < ActiveRecord::Base
set_table_name 'projects'
set_primary_key :id
validate :id, :name, presence: true
validate :name, uniqueness: true
end
EOS
end
end
context '#constraints' do
it 'gathers all constraints on the employees table' do
constraints(@db, 'employees').to_a.should == [
{"table_name"=>"employees", "constraint_name"=>"company_email", "constraint_src"=>"CHECK (((email)::text ~~ '%@example.com'::text))"},
{"table_name"=>"employees", "constraint_name"=>"employees_email_key", "constraint_src"=>"UNIQUE (email)"},
{"table_name"=>"employees", "constraint_name"=>"employees_pkey", "constraint_src"=>"PRIMARY KEY (id)"},
{"table_name"=>"employees", "constraint_name"=>"founding_date", "constraint_src"=>"CHECK ((start_date >= '2009-04-13'::date))"},
{"table_name"=>"employees", "constraint_name"=>"future_start_date", "constraint_src"=>"CHECK ((start_date <= (('now'::text)::date + 365)))"}
]
end
it 'gathers all constraints on the projects table' do
constraints(@db, 'projects').to_a.should == [
{"table_name"=>"projects", "constraint_name"=>"projects_name_key", "constraint_src"=>"UNIQUE (name)"},
{"table_name"=>"projects", "constraint_name"=>"projects_pkey", "constraint_src"=>"PRIMARY KEY (id)"}
]
end
it 'gathers all constraints on the employees_projects table' do
constraints(@db, 'employees_projects').to_a.should == [
{
"table_name"=>"employees_projects",
"constraint_name"=>"employees_projects_employee_id_fkey",
"constraint_src"=>"FOREIGN KEY (employee_id) REFERENCES employees(id) ON DELETE RESTRICT"
},
{
"table_name"=>"employees_projects",
"constraint_name"=>"employees_projects_pkey",
"constraint_src"=>"PRIMARY KEY (employee_id, project_id)"
},
{
"table_name"=>"employees_projects",
"constraint_name"=>"employees_projects_project_id_fkey",
"constraint_src"=>"FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE"
}
]
end
end
context '#generate_constraints' do
it 'generates ruby code for employees constraints' do
generate_constraints(@db, 'employees').should == [
"validate { errors.add(:email, \"Expected TODO\") unless email =~ /.*@example.com/ }",
"validate { errors.add(:start_date, \"Expected TODO\") unless start_date >= Date.parse(\"2009-04-13\") }",
"validate { errors.add(:start_date, \"Expected TODO\") unless start_date <= Time.now.to_date + 365 }",
]
end
end
context '#unique_columns' do
it 'returns email for employees' do
unique_columns(@db, 'employees').should == ['email']
end
end
context '#cols_with_contype' do
it 'identifies UNIQUE columns in database' do
cols_with_contype(@db, 'employees', 'u').to_a.should == [{"column_name"=>"email", "conname"=>"employees_email_key"},
{"column_name"=>"name", "conname"=>"projects_name_key"}]
end
end
context '#non_nullable_columns' do
it 'identifies NOT NULL columns in employees' do
non_nullable_columns(@db, 'employees').should == ['id', 'name', 'email', 'start_date']
end
end
end
| ruby | MIT | 0d688eeeb508933d239e00ed3740dc5b93160720 | 2026-01-04T17:46:45.928007Z | false |
twopoint718/reactive_record | https://github.com/twopoint718/reactive_record/blob/0d688eeeb508933d239e00ed3740dc5b93160720/spec/parser_spec.rb | spec/parser_spec.rb | require 'rspec'
require_relative '../lib/lexer.rb'
require_relative '../lib/parser.rb'
require_relative '../lib/code_generator.rb'
describe ConstraintParser::Parser do
let(:lex){ConstraintParser::Lexer}
let(:par){ConstraintParser::Parser}
it 'CHECK ()' do
@parser = par.new(lex.new StringIO.new 'CHECK ()')
@parser.parse.gen.should == 'validate { true }'
end
it "CHECK (((email)::text ~~ '%@bendyworks.com'::text))" do
@parser = par.new(lex.new StringIO.new "CHECK (((email)::text ~~ '%@bendyworks.com'::text))")
@parser.parse.gen.should == 'validate { errors.add(:email, "Expected TODO") unless email =~ /.*@bendyworks.com/ }'
end
it "UNIQUE (email)" do
@parser = par.new(lex.new StringIO.new 'UNIQUE (email)')
@parser.parse.gen.should == "validates :email, uniqueness: true"
end
it "CHECK ((start_date <= ('now'::text)::date))" do
@parser = par.new(lex.new StringIO.new "CHECK ((start_date <= ('now'::text)::date))")
@parser.parse.gen.should == "validate { errors.add(:start_date, \"Expected TODO\") unless start_date <= Time.now.to_date }"
end
it "CHECK ((start_date <= (('now'::text)::date + 365)))" do
@parser = par.new(lex.new StringIO.new "CHECK ((start_date <= (('now'::text)::date + 365)))")
@parser.parse.gen.should == 'validate { errors.add(:start_date, "Expected TODO") unless start_date <= Time.now.to_date + 365 }'
end
it "CHECK (((port >= 1024) AND (port <= 65634)))" do
@parser = par.new(lex.new StringIO.new "CHECK (((port >= 1024) AND (port <= 65634)))")
@parser.parse.gen.should == 'validate { errors.add(:port, "Expected TODO") unless port >= 1024 && port <= 65634 }'
end
it "FOREIGN KEY (employee_id) REFERENCES employees(employee_id) ON DELETE RESTRICT" do
@parser = par.new(lex.new StringIO.new "FOREIGN KEY (employee_id) REFERENCES employees(employee_id) ON DELETE RESTRICT")
@parser.parse.gen.should == "belongs_to :employees, foreign_key: 'employee_id', class: 'Employees', primary_key: 'employee_id'"
end
end
| ruby | MIT | 0d688eeeb508933d239e00ed3740dc5b93160720 | 2026-01-04T17:46:45.928007Z | false |
twopoint718/reactive_record | https://github.com/twopoint718/reactive_record/blob/0d688eeeb508933d239e00ed3740dc5b93160720/spec/lexer_spec.rb | spec/lexer_spec.rb | require 'rspec'
require_relative '../lib/lexer.rb'
describe ConstraintParser::Lexer do
let(:lex){ConstraintParser::Lexer}
it "CHECK (((email)::text ~~ '%@bendyworks.com'::text))" do
@lex = lex.new \
StringIO.new "CHECK (((email)::text ~~ '%@bendyworks.com'::text))"
@lex.tokenize.should == [
[:CHECK, 'CHECK'],
[:LPAREN, '('],
[:LPAREN, '('],
[:LPAREN, '('],
[:IDENT, 'email'],
[:RPAREN, ')'],
[:TYPE, '::'],
[:IDENT, 'text'],
[:MATCH_OP, '~~'],
[:STRLIT, "'%@bendyworks.com'"],
[:TYPE, '::'],
[:IDENT, 'text'],
[:RPAREN, ')'],
[:RPAREN, ')'],
]
end
it "UNIQUE (email)" do
@lex = lex.new StringIO.new "UNIQUE (email)"
@lex.tokenize.should == [
[:UNIQUE, 'UNIQUE'],
[:LPAREN, '('],
[:IDENT, 'email'],
[:RPAREN, ')']
]
end
it "PRIMARY KEY (employee_id)" do
@lex = lex.new StringIO.new "PRIMARY KEY (employee_id)"
@lex.tokenize.should == [
[:PRIMARY_KEY, 'PRIMARY KEY'],
[:LPAREN, '('],
[:IDENT, 'employee_id'],
[:RPAREN, ')']
]
end
it "CHECK ((start_date >= '2009-04-13'::date))" do
@lex = lex.new StringIO.new "CHECK ((start_date >= '2009-04-13'::date))"
@lex.tokenize.should == [
[:CHECK, 'CHECK'],
[:LPAREN, '('],
[:LPAREN, '('],
[:IDENT, 'start_date'],
[:GTEQ, '>='],
[:STRLIT, "'2009-04-13'"],
[:TYPE, '::'],
[:IDENT, 'date'],
[:RPAREN, ')'],
[:RPAREN, ')'],
]
end
it '"CHECK ((start_date <= ((\'now\'::text)::date + 365)))"' do
@lex = lex.new StringIO.new "CHECK ((start_date <= ((\'now\'::text)::date + 365)))"
@lex.tokenize.should == [
[:CHECK, 'CHECK'],
[:LPAREN, '('],
[:LPAREN, '('],
[:IDENT, 'start_date'],
[:LTEQ, '<='],
[:LPAREN, '('],
[:LPAREN, '('],
[:STRLIT, "'now'"],
[:TYPE, '::'],
[:IDENT, 'text'],
[:RPAREN, ')'],
[:TYPE, '::'],
[:IDENT, 'date'],
[:PLUS, '+'],
[:INT, '365'],
[:RPAREN, ')'],
[:RPAREN, ')'],
[:RPAREN, ')'],
]
end
it "FOREIGN KEY (employee_id) REFERENCES employees(employee_id) ON DELETE RESTRICT" do
@lex = lex.new StringIO.new "FOREIGN KEY (employee_id) REFERENCES employees(employee_id) ON DELETE RESTRICT"
@lex.tokenize.should == [
[:FOREIGN_KEY, 'FOREIGN KEY'],
[:LPAREN, '('],
[:IDENT, 'employee_id'],
[:RPAREN, ')'],
[:REFERENCES, 'REFERENCES'],
[:IDENT, 'employees'],
[:LPAREN, '('],
[:IDENT, 'employee_id'],
[:RPAREN, ')'],
[:ON, 'ON'],
[:DELETE, 'DELETE'],
[:RESTRICT, 'RESTRICT'],
]
end
it "PRIMARY KEY (employee_id, project_id)" do
@lex = lex.new StringIO.new "PRIMARY KEY (employee_id, project_id)"
@lex.tokenize.should == [
[:PRIMARY_KEY, 'PRIMARY KEY'],
[:LPAREN, '('],
[:IDENT, 'employee_id'],
[:COMMA, ','],
[:IDENT, 'project_id'],
[:RPAREN, ')']
]
end
it "FOREIGN KEY (project_id) REFERENCES projects(project_id) ON DELETE CASCADE" do
@lex = lex.new StringIO.new "FOREIGN KEY (project_id) REFERENCES projects(project_id) ON DELETE CASCADE"
@lex.tokenize.should == [
[:FOREIGN_KEY, 'FOREIGN KEY'],
[:LPAREN, '('],
[:IDENT, 'project_id'],
[:RPAREN, ')'],
[:REFERENCES, 'REFERENCES'],
[:IDENT, 'projects'],
[:LPAREN, '('],
[:IDENT, 'project_id'],
[:RPAREN, ')'],
[:ON, 'ON'],
[:DELETE, 'DELETE'],
[:CASCADE, 'CASCADE'],
]
end
it "PRIMARY KEY (project_id)" do
@lex = lex.new StringIO.new "PRIMARY KEY (project_id)"
@lex.tokenize.should == [
[:PRIMARY_KEY, 'PRIMARY KEY'],
[:LPAREN, '('],
[:IDENT, 'project_id'],
[:RPAREN, ')'],
]
end
it "CHECK (((port >= 1024) AND (port <= 65634)))" do
@lex = lex.new StringIO.new "CHECK (((port >= 1024) AND (port <= 65634)))"
@lex.tokenize.should == [
[:CHECK, 'CHECK'],
[:LPAREN, '('],
[:LPAREN, '('],
[:LPAREN, '('],
[:IDENT, 'port'],
[:GTEQ, '>='],
[:INT, "1024"],
[:RPAREN, ')'],
[:AND, 'AND'],
[:LPAREN, '('],
[:IDENT, 'port'],
[:LTEQ, '<='],
[:INT, "65634"],
[:RPAREN, ')'],
[:RPAREN, ')'],
[:RPAREN, ')'],
]
end
end
| ruby | MIT | 0d688eeeb508933d239e00ed3740dc5b93160720 | 2026-01-04T17:46:45.928007Z | false |
twopoint718/reactive_record | https://github.com/twopoint718/reactive_record/blob/0d688eeeb508933d239e00ed3740dc5b93160720/lib/parser.rb | lib/parser.rb | #
# DO NOT MODIFY!!!!
# This file is automatically generated by Racc 1.4.9
# from Racc grammer file "".
#
require 'racc/parser.rb'
module ConstraintParser
class Parser < Racc::Parser
require 'lexer'
require 'code_generator'
def initialize tokenizer, handler = nil
@tokenizer = tokenizer
super()
end
def next_token
@tokenizer.next_token
end
def parse
do_parse
end
##### State transition tables begin ###
racc_action_table = [
27, 28, 21, 22, 23, 24, 25, 26, 29, 27,
28, 21, 22, 23, 24, 25, 26, 29, 46, 12,
14, 11, 12, 14, 11, 30, 36, 32, 6, 13,
45, 7, 13, 33, 30, 27, 28, 21, 22, 23,
24, 25, 26, 29, 5, 12, 14, 11, 16, 18,
17, 9, 39, 40, 8, 13, 42, 37, 16, 44,
30, 34 ]
racc_action_check = [
10, 10, 10, 10, 10, 10, 10, 10, 10, 35,
35, 35, 35, 35, 35, 35, 35, 35, 44, 11,
11, 11, 20, 20, 20, 10, 30, 15, 0, 11,
44, 0, 20, 16, 35, 31, 31, 31, 31, 31,
31, 31, 31, 31, 0, 6, 6, 6, 7, 9,
8, 5, 32, 33, 1, 6, 38, 31, 39, 42,
31, 18 ]
racc_action_pointer = [
16, 54, nil, nil, nil, 33, 29, 30, 50, 33,
-2, 3, nil, nil, nil, 5, 17, nil, 37, nil,
6, nil, nil, nil, nil, nil, nil, nil, nil, nil,
10, 33, 36, 29, nil, 7, nil, nil, 36, 40,
nil, nil, 45, nil, 7, nil, nil ]
racc_action_default = [
-29, -29, -1, -2, -3, -29, -6, -29, -29, -29,
-5, -6, -10, -11, -12, -29, -29, 47, -29, -8,
-6, -13, -14, -15, -16, -17, -18, -19, -20, -21,
-29, -29, -29, -29, -4, -9, -22, -7, -23, -29,
-25, -24, -29, -26, -29, -27, -28 ]
racc_goto_table = [
15, 10, 1, 4, 3, 2, 31, 38, 41, nil,
nil, nil, nil, nil, nil, 35, nil, nil, nil, nil,
nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
nil, nil, 43 ]
racc_goto_check = [
8, 5, 1, 4, 3, 2, 5, 9, 10, nil,
nil, nil, nil, nil, nil, 5, nil, nil, nil, nil,
nil, nil, nil, nil, nil, nil, nil, nil, nil, nil,
nil, nil, 8 ]
racc_goto_pointer = [
nil, 2, 5, 4, 3, -5, nil, nil, -7, -25,
-30 ]
racc_goto_default = [
nil, nil, nil, nil, nil, nil, 19, 20, nil, nil,
nil ]
racc_reduce_table = [
0, 0, :racc_error,
1, 30, :_reduce_1,
1, 30, :_reduce_2,
1, 30, :_reduce_3,
4, 31, :_reduce_4,
2, 32, :_reduce_5,
0, 34, :_reduce_6,
3, 34, :_reduce_7,
2, 34, :_reduce_8,
3, 34, :_reduce_9,
1, 34, :_reduce_10,
1, 34, :_reduce_11,
1, 34, :_reduce_12,
1, 36, :_reduce_13,
1, 36, :_reduce_14,
1, 36, :_reduce_15,
1, 36, :_reduce_16,
1, 36, :_reduce_17,
1, 36, :_reduce_18,
1, 36, :_reduce_19,
1, 36, :_reduce_20,
1, 36, :_reduce_21,
2, 35, :_reduce_22,
4, 33, :_reduce_23,
5, 33, :_reduce_24,
3, 37, :_reduce_25,
2, 38, :_reduce_26,
3, 39, :_reduce_27,
3, 39, :_reduce_28 ]
racc_reduce_n = 29
racc_shift_n = 47
racc_token_table = {
false => 0,
:error => 1,
:PLUS => 2,
:MATCH_OP => 3,
:GTEQ => 4,
:LTEQ => 5,
:NEQ => 6,
:EQ => 7,
:GT => 8,
:LT => 9,
:AND => 10,
:CASCADE => 11,
:CHECK => 12,
:COMMA => 13,
:DELETE => 14,
:FOREIGN_KEY => 15,
:IDENT => 16,
:INT => 17,
:LPAREN => 18,
:NEWLINE => 19,
:ON => 20,
:PRIMARY_KEY => 21,
:REFERENCES => 22,
:RESTRICT => 23,
:RPAREN => 24,
:SPACE => 25,
:STRLIT => 26,
:TYPE => 27,
:UNIQUE => 28 }
racc_nt_base = 29
racc_use_result_var = true
Racc_arg = [
racc_action_table,
racc_action_check,
racc_action_default,
racc_action_pointer,
racc_goto_table,
racc_goto_check,
racc_goto_default,
racc_goto_pointer,
racc_nt_base,
racc_reduce_table,
racc_token_table,
racc_shift_n,
racc_reduce_n,
racc_use_result_var ]
Racc_token_to_s_table = [
"$end",
"error",
"PLUS",
"MATCH_OP",
"GTEQ",
"LTEQ",
"NEQ",
"EQ",
"GT",
"LT",
"AND",
"CASCADE",
"CHECK",
"COMMA",
"DELETE",
"FOREIGN_KEY",
"IDENT",
"INT",
"LPAREN",
"NEWLINE",
"ON",
"PRIMARY_KEY",
"REFERENCES",
"RESTRICT",
"RPAREN",
"SPACE",
"STRLIT",
"TYPE",
"UNIQUE",
"$start",
"constraint",
"unique_column",
"check_statement",
"foreign_key",
"expr",
"type_signature",
"operator",
"column_spec",
"table_spec",
"action_spec" ]
Racc_debug_parser = false
##### State transition tables end #####
# reduce 0 omitted
def _reduce_1(val, _values, result)
result = val[0]
result
end
def _reduce_2(val, _values, result)
result = val[0]
result
end
def _reduce_3(val, _values, result)
result = val[0]
result
end
def _reduce_4(val, _values, result)
result = UniqueNode.new(IdentNode.new(val[2]))
result
end
def _reduce_5(val, _values, result)
result = CheckNode.new(val[1])
result
end
def _reduce_6(val, _values, result)
result = EmptyExprNode.new :empty
result
end
def _reduce_7(val, _values, result)
result = ExprNode.new(val[1])
result
end
def _reduce_8(val, _values, result)
result = TypedExprNode.new(val[0], val[1])
result
end
def _reduce_9(val, _values, result)
result = OperatorNode.new(val[1], val[0], val[2])
result
end
def _reduce_10(val, _values, result)
result = IdentNode.new(val[0])
result
end
def _reduce_11(val, _values, result)
result = StrLitNode.new(val[0])
result
end
def _reduce_12(val, _values, result)
result = IntNode.new(val[0])
result
end
def _reduce_13(val, _values, result)
result = :gteq
result
end
def _reduce_14(val, _values, result)
result = :lteq
result
end
def _reduce_15(val, _values, result)
result = :neq
result
end
def _reduce_16(val, _values, result)
result = :eq
result
end
def _reduce_17(val, _values, result)
result = :gt
result
end
def _reduce_18(val, _values, result)
result = :lt
result
end
def _reduce_19(val, _values, result)
result = :plus
result
end
def _reduce_20(val, _values, result)
result = :match
result
end
def _reduce_21(val, _values, result)
result = :and
result
end
def _reduce_22(val, _values, result)
result = IdentNode.new(val[1])
result
end
def _reduce_23(val, _values, result)
result = ForeignKeyNode.new(val[1], val[3])
result
end
def _reduce_24(val, _values, result)
result = ForeignKeyNode.new(val[1], val[3], val[4])
result
end
def _reduce_25(val, _values, result)
result = IdentNode.new(val[1])
result
end
def _reduce_26(val, _values, result)
result = TableNode.new(IdentNode.new(val[0]), val[1])
result
end
def _reduce_27(val, _values, result)
result = ActionNode.new(:delete, :restrict)
result
end
def _reduce_28(val, _values, result)
result = ActionNode.new(:delete, :cascade)
result
end
def _reduce_none(val, _values, result)
val[0]
end
end # class Parser
end # module ConstraintParser
| ruby | MIT | 0d688eeeb508933d239e00ed3740dc5b93160720 | 2026-01-04T17:46:45.928007Z | false |
twopoint718/reactive_record | https://github.com/twopoint718/reactive_record/blob/0d688eeeb508933d239e00ed3740dc5b93160720/lib/reactive_record.rb | lib/reactive_record.rb | require_relative "./reactive_record/version"
require 'pg'
require 'active_support/inflector'
require 'parser'
module ReactiveRecord
def model_definition db, table_name
header = "class #{table_name.classify.pluralize} < ActiveRecord::Base\n"
footer = "end\n"
body = []
body << "set_table_name '#{table_name}'"
body << "set_primary_key :#{primary_key db, table_name}"
body << "#{validate_definition non_nullable_columns(db, table_name), 'presence'}"
body << "#{validate_definition unique_columns(db, table_name), 'uniqueness'}"
generate_constraints(db, table_name).each do |con|
body << con
end
indent = " "
body = indent + body.join("\n" + indent) + "\n"
header + body + footer
end
def validate_definition cols, type
return '' if cols.empty?
symbols = cols.map { |c| ":#{c}" }
"validate #{symbols.join ', '}, #{type}: true"
end
def table_names db
results = db.exec(
"select table_name from information_schema.tables where table_schema = $1",
['public']
)
results.map { |r| r['table_name'] }
end
def constraints db, table
db.exec("""
SELECT c.relname AS table_name,
con.conname AS constraint_name,
pg_get_constraintdef( con.oid, false) AS constraint_src
FROM pg_constraint con
JOIN pg_namespace n on (n.oid = con.connamespace)
JOIN pg_class c on (c.oid = con.conrelid)
WHERE con.conrelid != 0
AND c.relname = $1
ORDER BY con.conname;
""", [table])
end
def generate_constraints db, table
key_or_pkey = lambda do |row|
row['constraint_name'].end_with?('_key') || row['constraint_name'].end_with?('_pkey')
end
constraints(db, table)
.reject(&key_or_pkey)
.map(&parse_constraint)
end
def parse_constraint
lambda do |row|
src = row['constraint_src']
parser = ConstraintParser::Parser.new(ConstraintParser::Lexer.new(StringIO.new src))
parser.parse.gen
end
end
def cols_with_contype db, table_name, type
db.exec """
SELECT column_name, conname
FROM pg_constraint, information_schema.columns
WHERE table_name = $1
AND contype = $2
AND ordinal_position = any(conkey);
""", [table_name, type]
end
def column_name
lambda {|row| row['column_name']}
end
def table_name
lambda {|row| row['table_name']}
end
def primary_key db, table_name
matching_primary_key = lambda {|row| row['conname'] == "#{table_name}_pkey"}
cols_with_contype(db, table_name, 'p')
.select(&matching_primary_key)
.map(&column_name)
.first
end
def unique_columns db, table_name
matching_unique_constraint = lambda {|row| row['conname'] == "#{table_name}_#{row['column_name']}_key"}
cols_with_contype(db, table_name, 'u')
.select(&matching_unique_constraint)
.map(&column_name)
end
def non_nullable_columns db, table_name
result = db.exec """
SELECT column_name
FROM information_schema.columns
WHERE table_name = $1
AND is_nullable = $2
""", [table_name, 'NO']
result.map { |r| r['column_name'] }
end
end
| ruby | MIT | 0d688eeeb508933d239e00ed3740dc5b93160720 | 2026-01-04T17:46:45.928007Z | false |
twopoint718/reactive_record | https://github.com/twopoint718/reactive_record/blob/0d688eeeb508933d239e00ed3740dc5b93160720/lib/lexer.rb | lib/lexer.rb | require 'strscan'
module ConstraintParser
class Lexer
AND = /AND/
CASCADE = /CASCADE/
CHECK = /CHECK/
COMMA = /,/
DELETE = /DELETE/
EQ = /\=/
FOREIGN_KEY = /FOREIGN KEY/
GT = /\>/
GTEQ = /\>=/
IDENT = /[a-zA-Z][a-zA-Z0-9_]*/
INT = /[0-9]+/
LPAREN = /\(/
LT = /\</
LTEQ = /\<=/
MATCH_OP = /~~/
NEQ = /\<\>/
NEWLINE = /\n/
ON = /ON/
PLUS = /\+/
PRIMARY_KEY = /PRIMARY KEY/
REFERENCES = /REFERENCES/
RESTRICT = /RESTRICT/
RPAREN = /\)/
SPACE = /[\ \t]+/
STRLIT = /\'(\\.|[^\\'])*\'/
TYPE = /::/
UNIQUE = /UNIQUE/
def initialize io
@ss = StringScanner.new io.read
end
def next_token
return if @ss.eos?
result = false
while !result
result = case
when text = @ss.scan(SPACE) then #ignore whitespace
# Operators
when text = @ss.scan(GTEQ) then [:GTEQ, text]
when text = @ss.scan(LTEQ) then [:LTEQ, text]
when text = @ss.scan(NEQ) then [:NEQ, text]
when text = @ss.scan(GT) then [:GT, text]
when text = @ss.scan(LT) then [:LT, text]
when text = @ss.scan(EQ) then [:EQ, text]
when text = @ss.scan(PLUS) then [:PLUS, text]
when text = @ss.scan(MATCH_OP) then [:MATCH_OP, text]
when text = @ss.scan(AND) then [:AND, text]
# SQL Keywords
when text = @ss.scan(CHECK) then [:CHECK, text]
when text = @ss.scan(UNIQUE) then [:UNIQUE, text]
when text = @ss.scan(PRIMARY_KEY) then [:PRIMARY_KEY, text]
when text = @ss.scan(FOREIGN_KEY) then [:FOREIGN_KEY, text]
when text = @ss.scan(REFERENCES) then [:REFERENCES, text]
when text = @ss.scan(DELETE) then [:DELETE, text]
when text = @ss.scan(ON) then [:ON, text]
when text = @ss.scan(RESTRICT) then [:RESTRICT, text]
when text = @ss.scan(CASCADE) then [:CASCADE, text]
# Values
when text = @ss.scan(IDENT) then [:IDENT, text]
when text = @ss.scan(STRLIT) then [:STRLIT, text]
when text = @ss.scan(INT) then [:INT, text]
# Syntax
when text = @ss.scan(LPAREN) then [:LPAREN, text]
when text = @ss.scan(RPAREN) then [:RPAREN, text]
when text = @ss.scan(TYPE) then [:TYPE, text]
when text = @ss.scan(COMMA) then [:COMMA, text]
else
x = @ss.getch
[x, x]
end
end
result
end
def tokenize
out = []
while (tok = next_token)
out << tok
end
out
end
end
end
| ruby | MIT | 0d688eeeb508933d239e00ed3740dc5b93160720 | 2026-01-04T17:46:45.928007Z | false |
twopoint718/reactive_record | https://github.com/twopoint718/reactive_record/blob/0d688eeeb508933d239e00ed3740dc5b93160720/lib/code_generator.rb | lib/code_generator.rb | class Node
def initialize val, *args
@value = val
@children = args
end
def gen
raise "gen is not implemented: #{self}"
end
def column
'base'
end
end
class UniqueNode < Node
def initialize val; super(val, nil); end
def gen
"validates :#{@value.gen}, uniqueness: true"
end
end
class IdentNode < Node
def initialize val; super(val, nil); end
def gen
# bottoms out: IDENT is a string
@value
end
def column
# ident is likely a column (must be?)
@value
end
end
class ExprNode < Node
def initialize val; super(val); end
def column
@value.column
end
def gen
@value.gen
end
end
class EmptyExprNode < Node
def gen
nil
end
def column
nil
end
end
class CheckNode < Node
def initialize val; super(val); end
def gen
column = @value.column
val = @value.gen
if val
"validate { errors.add(:#{column}, \"Expected TODO\") unless #{val} }"
else
"validate { true }"
end
end
end
class TypedExprNode < Node
def initialize val, *args
@children = args
@type = @children[0]
@value = case @type.gen
when 'text' then TextNode.new(val)
when 'date' then DateExprNode.new(val)
else
raise "Unknown type: #{@children[0]}"
end
end
def column
@value.column
end
def gen
@value.gen
end
end
class TextNode < Node
def gen
@value.gen
end
def column
@value.column
end
end
class DateExprNode < Node
def initialize val
@value = val
end
def gen
val = @value.gen
if val == 'now'
"Time.now.to_date"
else
# YYYY-MM-DD
"Date.parse(\"#{val}\")"
end
end
end
class StrLitNode < Node
def initialize val; super(val); end
def gen
#FIXME HACK
if @value.respond_to? :gen
val = @value.gen
else
val = @value
end
val.gsub(/^'(.*)'$/, '\1')
end
end
class IntNode < Node
def initialize val; super(val); end
def gen
@value.to_s
end
end
class OperatorNode < Node
def initialize op, *args
@value = op
@children = args
@expr1 = @children[0]
@expr2 = @children[1]
end
def operation
case @value
when :gteq, :lteq, :neq, :eq, :gt, :lt
ComparisonExpr.new @value, @expr1, @expr2
when :plus
MathExpr.new @value, @expr1, @expr2
when :match
MatchExpr.new @expr1, @expr2
when :and
AndExpr.new @expr1, @expr2
end
end
def error_msg
case @value
when :gteq then 'to be greater than or equal to'
when :lteq then 'to be less than or equal to'
when :neq then 'to not equal'
when :eq then 'to be equal to'
when :gt then 'to be greater than'
when :lt then 'to be less than'
when :plus then 'plus'
when :match then 'to match'
end
end
def column
c1 = @expr1.column
c2 = @expr1.column
return c1 if c1 != 'base'
return c2 if c2 != 'base'
'base'
end
def gen
operation.gen
end
end
class ComparisonExpr
def initialize comparison, e1, e2
@e1, @e2 = e1, e2
@comparison = {
gteq: '>=',
lteq: '<=',
neq: '!=',
eq: '==',
gt: '>',
lt: '<',
}[comparison]
end
def gen
"#{@e1.gen} #{@comparison} #{@e2.gen}"
end
end
class AndExpr
def initialize e1, e2
@e1, @e2 = e1, e2
end
def gen
"#{@e1.gen} && #{@e2.gen}"
end
end
class MathExpr
def initialize op, e1, e2
@e1, @e2 = e1, e2
@operation = { plus: '+', minus: '-' }[op]
end
def gen
"#{@e1.gen} #{@operation} #{@e2.gen}"
end
end
class MatchExpr
def initialize e1, e2
@e1 = e1
@e2 = e2
end
def convert_wildcard str
str.gsub(/%/, '.*')
end
def gen
#raise "RHS: #{@e2.class} #{@e2.gen.class}"
"#{@e1.gen} =~ /#{convert_wildcard @e2.gen}/"
end
end
class TableNode < Node
def initialize tab, col
@tab = tab
@col = col
end
def table_to_class
@tab.gen.capitalize
end
def key_name
@col.gen
end
def gen
@tab.gen
end
end
class ActionNode < Node
def initialize action, consequence
@action = action
@consequence = consequence
end
def gen
"ON #{@action} #{@consequence}"
end
end
class ForeignKeyNode < Node
def initialize col, table, *actions
@col = col
@table = table
if actions.count > 0
@action = actions[0]
end
end
def gen
col = @col.gen
table_name = @table.gen
class_name = @table.table_to_class
key = @table.key_name
"belongs_to :#{table_name}, foreign_key: '#{col}', class: '#{class_name}', primary_key: '#{key}'"
end
end
| ruby | MIT | 0d688eeeb508933d239e00ed3740dc5b93160720 | 2026-01-04T17:46:45.928007Z | false |
twopoint718/reactive_record | https://github.com/twopoint718/reactive_record/blob/0d688eeeb508933d239e00ed3740dc5b93160720/lib/reactive_record/version.rb | lib/reactive_record/version.rb | module ReactiveRecord
VERSION = "0.0.4"
end
| ruby | MIT | 0d688eeeb508933d239e00ed3740dc5b93160720 | 2026-01-04T17:46:45.928007Z | false |
twopoint718/reactive_record | https://github.com/twopoint718/reactive_record/blob/0d688eeeb508933d239e00ed3740dc5b93160720/lib/generators/reactive_record/install_generator.rb | lib/generators/reactive_record/install_generator.rb | require "reactive_record"
module ReactiveRecord
module Generators
class InstallGenerator < Rails::Generators::Base
include ReactiveRecord
desc "Adds models based upon your existing Postgres DB"
def create_models
db_env = Rails.configuration.database_configuration[Rails.env]
raise 'You must use the pg database adapter' unless db_env['adapter'] == 'postgresql'
db = PG.connect dbname: db_env['database']
table_names(db).each do |table|
unless table == 'schema_migrations'
create_file "app/models/#{table.underscore.pluralize}.rb", model_definition(db, table)
end
end
end
end
end
end
| ruby | MIT | 0d688eeeb508933d239e00ed3740dc5b93160720 | 2026-01-04T17:46:45.928007Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/jobs/yard_copy_assets_job.rb | app/jobs/yard_copy_assets_job.rb | class YARDCopyAssetsJob < ApplicationJob
queue_as :default
def perform
# Copy static assets from the yard to the public directory
Rails.logger.info "YARD: Copying static system files..."
YARD::Templates::Engine.template(:default, :fulldoc, :html).full_paths.each do |path|
%w[css js images].each do |ext|
srcdir, dstdir = Pathname.new(path).join(ext), Rails.root.join("public", "assets", ext)
next unless srcdir.directory?
dstdir.mkpath
FileUtils.cp_r(srcdir.glob("*"), dstdir)
end
end
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/jobs/generate_docs_job.rb | app/jobs/generate_docs_job.rb | class GenerateDocsJob < ApplicationJob
limits_concurrency to: 1, key: ->(lv) { lv.to_s }, duration: 5.minutes
include ShellHelper
extend ShellHelper
queue_as :docparse
@prepare_mutex = Mutex.new
IMAGE = "docmeta/rubydoc-docparse"
attr_accessor :library_version
def perform(library_version)
ensure_image_prepared!
self.library_version = library_version
return if disallowed?
return if library_version.ready?
prepare_library
run_generate
clear_cache
clean_source
end
def self.prepare_image
@prepare_mutex.synchronize do
return if @image_prepared
sh "docker build -q -t #{IMAGE} -f #{context.join("Dockerfile")} #{context}",
title: "Building image: #{IMAGE}"
@image_prepared = true
end
end
def self.prepared?
@image_prepared
end
def self.context
Rails.root.join("docker", "docparse")
end
private
def ensure_image_prepared!
self.class.prepare_image
raise RuntimeError, "Image #{IMAGE} not prepared" unless self.class.prepared?
end
def context
self.class.context
end
def prepare_library
case library_version.source.to_sym
when :github
owner, project = *library_version.name.split("/")
GithubCheckoutJob.perform_now(owner:, project:, commit: library_version.version)
when :remote_gem
DownloadGemJob.perform_now(library_version)
end
end
def run_generate
FileUtils.rm_rf(library_version.yardoc_file)
sh "docker run --rm -u #{Process.uid}:#{Process.gid} -v #{library_version.source_path.inspect}:/build #{IMAGE}",
title: "Generating #{library_version} (#{library_version.source})"
end
def clear_cache
paths = []
controller_names_for_path.each do |controller_name|
paths << "/#{controller_name}/#{library_version.name}/"
paths << "/list/#{controller_name}/#{library_version.name}/"
paths << "/static/#{controller_name}/#{library_version.name}/"
end
CacheClearJob.perform_later(*paths)
end
def clean_source
SourceCleanerJob.perform_later(library_version)
end
def controller_names_for_path
case library_version.source.to_sym
when :github
%w[github]
when :remote_gem
%w[docs gems]
else
%w[stdlib]
end
end
def disallowed?
if library_version.disallowed?
logger.info "Skip generating docs for disallowed #{library_version.source}: #{library_version}"
true
else
false
end
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/jobs/source_cleaner_job.rb | app/jobs/source_cleaner_job.rb | class SourceCleanerJob < ApplicationJob
queue_as :default
attr_accessor :basepath
def perform(library_version)
return if skip?(library_version)
self.basepath = library_version.source_path
clean
end
private
def skip?(library_version)
skip = case library_version.source.to_sym
when :featured, :stdlib
true
when :github
Rubydoc.config.libraries.whitelisted_projects.include?(library_version.name)
when :remote_gem
Rubydoc.config.libraries.whitelisted_gems.include?(library_version.name)
else
false
end
if skip
logger.info "Skip cleaning for whitelisted #{library_version.name} (#{library_version.version})"
end
end
def clean
YARD::Config.options[:safe_mode] = true
yardopts = File.join(basepath, ".yardopts")
exclude = [ ".yardoc", ".yardopts", ".git", ".document" ]
exclude += Dir.glob(File.join(basepath, "README*")).map { |f| remove_basepath(f) }
if File.file?(yardopts)
yardoc = YARD::CLI::Yardoc.new
class << yardoc
def basepath=(bp) @basepath = bp end
def basepath; @basepath end
def add_extra_files(*files)
files.map! { |f| f.include?("*") ? Dir.glob(File.join(basepath, f)) : f }.flatten!
files.each do |f|
filename = f.sub(/^(#{File.realpath(basepath)}|#{basepath})\//, "")
options[:files] << YARD::CodeObjects::ExtraFileObject.new(filename, "")
end
end
def support_rdoc_document_file!(file = ".document")
return [] unless use_document_file
File.read(File.join(basepath, file)).
gsub(/^[ \t]*#.+/m, "").split(/\s+/)
rescue Errno::ENOENT
[]
end
end
yardoc.basepath = basepath
yardoc.options_file = yardopts if File.file?(yardopts)
yardoc.parse_arguments
exclude += yardoc.options[:files].map { |f| f.filename }
exclude += yardoc.assets.keys
end
# make sure to keep relevant symlink targets
link_exclude = exclude.inject(Array.new) do |lx, filespec|
filespec = filespec.filename if filespec.respond_to?(:filename)
Dir.glob(File.join(basepath, filespec)) do |file|
if File.symlink?(file)
ep = remove_basepath(File.realpath(file, basepath))
log.debug "Not deleting #{ep} (linked by #{file})"
lx << ep
end
end
lx
end
exclude += link_exclude
# delete all source files minus excluded ones
files = Dir.glob(basepath + "/**/**") +
Dir.glob(basepath + "/.*")
files = files.map { |f| remove_basepath(f) }
files -= [ ".", ".." ]
files = files.sort_by { |f| f.length }.reverse
files.each do |file|
begin
fullfile = File.join(basepath, file)
if exclude.any? { |ex| true if file == ex || file =~ /^#{ex}\// }
log.debug "Skipping #{fullfile}"
next
end
del = File.directory?(fullfile) ? Dir : File
log.debug "Deleting #{fullfile}"
del.delete(fullfile)
rescue Errno::ENOTEMPTY, Errno::ENOENT, Errno::ENOTDIR
end
end
end
def remove_basepath(p)
p.sub(/^(#{File.realpath(basepath)}|#{basepath})\//, "")
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/jobs/register_libraries_job.rb | app/jobs/register_libraries_job.rb | class RegisterLibrariesJob < ApplicationJob
queue_as :default
def perform(library_version = nil)
find_github(library_version)
find_stdlib if library_version.nil?
end
def find_github(library_version = nil)
logger.info "Registering GitHub libraries (#{library_version&.name || "all"})"
(library_version ? [ Pathname.new(library_version.source_path).parent ] : GithubLibrary.base_path.glob("*/*")).each do |dir|
next unless dir.directory?
lib = Library.github.find_or_create_by(owner: dir.basename.to_s, name: dir.parent.basename.to_s)
lib.versions = dir.glob("*").map { |d| d.directory? ? d.basename.to_s : nil }.compact
lib.save
lib.touch if library_version.present?
end
end
def find_stdlib
logger.info "Registering Stdlib libraries"
StdlibLibrary.base_path.glob("*").each do |dir|
next unless dir.directory?
lib = Library.stdlib.find_or_create_by(name: dir.basename.to_s)
lib.versions = VersionSorter.sort(dir.glob("*").map { |d| d.directory? ? d.basename.to_s : nil }.compact)
lib.save
end
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/jobs/update_remote_gems_list_job.rb | app/jobs/update_remote_gems_list_job.rb | class UpdateRemoteGemsListJob < ApplicationJob
limits_concurrency to: 1, key: "updated_gems", duration: 5.minutes
queue_as :update_gems
def self.clear_lock_file
lock_file.delete rescue nil
end
def self.locked?
lock_file.exist?
end
def self.lock_file
@lock_file ||= Rubydoc.storage_path.join("update_gems.lock")
end
def perform
return if self.class.locked?
FileUtils.touch(self.class.lock_file)
@can_clear_lock_file = true
logger.info "Updating remote RubyGems..."
inserts = []
# Use pluck + index to reduce memory usage instead of loading full AR objects
changed_gems = Library.gem.pluck(:name, :id, :versions).each_with_object({}) do |(name, id, versions), hash|
hash[name] = { id: id, versions: versions }
end
removed_gems = changed_gems.keys.to_set
fetch_remote_gems.each do |name, versions|
versions = pick_best_versions(versions)
lib_data = changed_gems[name]
if lib_data
removed_gems.delete(name)
if lib_data[:versions] != versions
Library.where(id: lib_data[:id]).update_all(versions: versions)
else
changed_gems.delete(name)
end
else
inserts << { name: name, source: :remote_gem, versions: versions }
end
end
if inserts.size > 0
Library.insert_all(inserts, unique_by: [ :name, :source, :owner ])
end
if changed_gems.size > 0
flush_cache(changed_gems.keys)
logger.info "Updated #{changed_gems.size} gems: #{changed_gems.keys.join(', ')}"
end
if removed_gems.size > 0
Library.where(source: :remote_gem, name: removed_gems.to_a).delete_all
logger.info "Removed #{removed_gems.size} gems: #{removed_gems.to_a.join(', ')}"
end
ensure
self.class.clear_lock_file if @can_clear_lock_file
end
private
def ensure_only_one_job_running!
!self.class.lock_file.exist?
end
def fetch_remote_gems
spec_fetcher.available_specs(:released).first.values.flatten(1).group_by(&:name)
end
def spec_fetcher
source = Gem::Source.new(Rubydoc.config.gem_hosting.source)
@spec_fetcher ||= Gem::SpecFetcher.new(Gem::SourceList.from([ source ]))
end
def pick_best_versions(versions)
seen = {}
uniqversions = []
versions.each do |ver|
uniqversions |= [ ver.version ]
(seen[ver.version] ||= []).send(ver.platform == "ruby" ? :unshift : :push, ver)
end
VersionSorter.sort(uniqversions.map { |v| version_string(seen[v].first) })
end
def version_string(gem_version)
gem_version.platform == "ruby" ? gem_version.version.to_s : [ gem_version.version, gem_version.platform ].join(",")
end
def flush_cache(gem_names)
index_map = {}
gem_names.each do |gem_name|
index_map[gem_name[0, 1]] = true
end
CacheClearJob.perform_later("/gems", "/featured", *index_map.keys.map { |k| "/gems/~#{k}" })
# Batch into larger chunks to reduce job overhead
gem_names.each_slice(100) do |list|
CacheClearJob.perform_later(*list.flat_map { |k| [ "/gems/#{k}/", "/list/gems/#{k}/", "/static/gems/#{k}" ] })
end
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/jobs/cache_clear_job.rb | app/jobs/cache_clear_job.rb | require "net/http"
require "net/http/persistent"
class CacheClearJob < ApplicationJob
queue_as :default
def perform(*paths)
clear_from_cloudflare(*paths)
end
private
def clear_from_cloudflare(*paths)
return unless cloudflare_token
[ cloudflare_zones ].flatten.compact.each do |zone|
uri = URI("https://api.cloudflare.com")
uri_path = "/client/v4/zones/#{zone}/purge_cache"
headers = {
"Content-Type" => "application/json",
"Authorization" => "Bearer #{cloudflare_token}"
}
http = Net::HTTP::Persistent.new
logger.info "Flushing CloudFlare cache: #{paths}"
paths.each_slice(30) do |path_slice|
begin
req = Net::HTTP::Post.new(uri_path, headers)
req.body = { "files" => path_slice }.to_json
http.request(uri, req)
rescue
logger.info "Could not invalidate CF cache for: #{path}"
end
end
http.shutdown
end
end
def cloudflare_token
@cloudflare_token ||= Rubydoc.config.integrations.cloudflare_token
end
def cloudflare_zones
@cloudflare_zones ||= Rubydoc.config.integrations.cloudflare_zones
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/jobs/reap_generate_docs_job.rb | app/jobs/reap_generate_docs_job.rb | class ReapGenerateDocsJob < ApplicationJob
queue_as :default
def perform
running_containers.each do |id, created_at|
if created_at < 10.minutes.ago
logger.info "Stopping DEAD container #{id} (created at #{created_at})"
`docker rm -f #{id}`
end
end
end
private
def running_containers
`docker ps -f status=running -f ancestor=#{GenerateDocsJob::IMAGE} --format '{{.ID}},{{.CreatedAt}}'`
.strip
.split("\n")
.map { |line| id, time = line.split(","); [ id, DateTime.parse(time) ] }
.to_h
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/jobs/application_job.rb | app/jobs/application_job.rb | class ApplicationJob < ActiveJob::Base
# Automatically retry jobs that encountered a deadlock
# retry_on ActiveRecord::Deadlocked
# Most jobs are safe to ignore if the underlying records are no longer available
# discard_on ActiveJob::DeserializationError
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/jobs/delete_docs_job.rb | app/jobs/delete_docs_job.rb | class DeleteDocsJob < ApplicationJob
queue_as :default
def perform(library_version)
# Make sure library version still has not been accessed since this job was queued
return unless CleanupUnvisitedDocsJob.should_invalidate?(library_version.source_path)
unregister_library(library_version)
remove_directory(library_version)
logger.info "Removed #{library_version} (#{library_version.source})"
end
private
def unregister_library(library_version)
opts = case library_version.source.to_sym
when :github
owner, name = *library_version.name.split("/")
{ owner:, name: }
when :remote_gem
{ name: library_version.name }
end
library = Library.where(opts.merge(source: library_version.source)).first
if library
library.versions.delete(library_version.version)
if library.versions.empty?
library.destroy
else
library.save
end
end
CacheClearJob.perform_later(library_version)
end
def remove_directory(library_version)
Pathname.new(library_version.source_path).rmtree
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/jobs/cleanup_unvisited_docs_job.rb | app/jobs/cleanup_unvisited_docs_job.rb | class CleanupUnvisitedDocsJob < ApplicationJob
queue_as :default
INVALIDATES_AT = 1.week.ago
def self.should_invalidate?(directory)
Pathname.new(directory).mtime < INVALIDATES_AT
end
def perform
cleanup_github
cleanup_gems
end
private
def cleanup_github
logger.info "Cleaning up unvisited GitHub libraries"
remove_directories :github, GithubLibrary.base_path.glob("*/*/*")
end
def cleanup_gems
logger.info "Cleaning up unvisited gems"
remove_directories :remote_gem, GemLibrary.base_path.glob("*/*/*")
end
def remove_directories(source, dirs)
dirs.each do |dir|
if self.class.should_invalidate?(dir)
version = dir.basename.to_s
name = case source
when :github
"#{dir.parent.basename}/#{dir.parent.parent.basename}"
when :remote_gem
dir.parent.basename.to_s
end
DeleteDocsJob.perform_later YARD::Server::LibraryVersion.new(name, version, nil, source)
end
end
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/jobs/github_checkout_job.rb | app/jobs/github_checkout_job.rb | require "open-uri"
require "shellwords"
class GithubCheckoutJob < ApplicationJob
include ShellHelper
queue_as :default
attr_accessor :owner, :project, :commit, :library_version
def commit=(value)
value = nil if value == ""
if value
value = value[0, 6] if value.length == 40
value = value[/\A\s*([a-z0-9.\/-_]+)/i, 1]
end
@commit = value
end
after_perform do
temp_clone_path.rmtree if temp_clone_path.directory?
end
def perform(owner:, project:, commit: nil)
commit = nil if commit.blank?
self.owner = owner
self.project = project
self.commit = commit.present? ? commit : primary_branch
raise DisallowedCheckoutError.new(owner:, project:) if library_version.disallowed?
if run_checkout
register_project
flush_cache
end
end
def name
"#{owner}/#{project}"
end
def url
"https://github.com/#{name}"
end
def run_checkout
if commit.present? && repository_path.directory?
run_checkout_pull
else
run_checkout_clone
end
end
def run_checkout_pull
write_fork_data
sh("cd #{Shellwords.escape(repository_path.to_s)} && git reset --hard origin/#{Shellwords.escape(commit)} && git pull --force",
title: "Updating project #{name}")
yardoc = repository_path.join(".yardoc")
yardoc.rmtree if yardoc.directory?
end
def run_checkout_clone
temp_clone_path.parent.mkpath
branch_opt = commit ? "--branch #{Shellwords.escape(commit)} " : ""
clone_cmd = "git clone --depth 1 --single-branch #{branch_opt}#{Shellwords.escape(url)} #{Shellwords.escape(temp_clone_path.to_s)}"
sh(clone_cmd, title: "Cloning project #{name}")
if commit.blank?
self.commit = `git -C #{Shellwords.escape(temp_clone_path.to_s)} rev-parse --abbrev-ref HEAD`.strip
end
repository_path.parent.mkpath
write_primary_branch_file if branch_opt.blank?
write_fork_data
sh("rm -rf #{Shellwords.escape(repository_path.to_s)} && mv #{Shellwords.escape(temp_clone_path.to_s)} #{Shellwords.escape(repository_path.to_s)}",
title: "Move #{name} into place")
true
end
def temp_clone_path
@temp_clone_path ||= Rubydoc.storage_path.join("github_clones", "#{project}-#{owner}-#{Time.now.to_f}")
end
def repository_path
@repository_path ||= GithubLibrary.base_path.join(project, owner, commit)
end
def library_version
YARD::Server::LibraryVersion.new(name, commit, nil, :github)
end
def flush_cache
CacheClearJob.perform_now("/", "/github", "/github/~#{project[0, 1]}",
"/github/#{name}/", "/list/github/#{name}/", "/static/github/#{name}/")
end
def register_project
RegisterLibrariesJob.perform_now(library_version)
end
def primary_branch_file
GithubLibrary.base_path.join(project, owner, ".primary_branch")
end
def primary_branch
primary_branch_file.read
rescue Errno::ENOENT
end
def write_primary_branch_file
primary_branch_file.write(commit)
end
def write_fork_data
return if fork_file.file? || fork?
fork_file.write(name)
end
def fork_file
GithubLibrary.base_path.join(project, ".primary_fork")
end
def fork?
return @is_fork unless @is_fork.nil?
json = JSON.parse(URI.open("https://api.github.com/repos/#{owner}/#{project}", &:read))
@is_fork = json["fork"] if json
rescue IOError, OpenURI::HTTPError, Timeout::Error
@is_fork = nil
false
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/jobs/download_gem_job.rb | app/jobs/download_gem_job.rb | require "open-uri"
require "rubygems/package"
require "rubygems/package/tar_reader"
class DownloadGemJob < ApplicationJob
queue_as :default
def perform(library_version)
return if disallowed?(library_version)
return if library_version.ready?
# Remote gemfile from rubygems.org
suffix = library_version.platform ? "-#{library_version.platform}" : ""
base_url = (Rubydoc.config.gem_source || "http://rubygems.org").gsub(%r{/$}, "")
url = "#{base_url}/gems/#{library_version.to_s(false)}#{suffix}.gem"
logger.info "Downloading remote gem file #{url}"
FileUtils.rm_rf(library_version.source_path)
FileUtils.mkdir_p(library_version.source_path)
URI.open(url) do |io|
expand_gem(io, library_version)
end
rescue OpenURI::HTTPError => e
logger.warn "Error downloading gem: #{url}! (#{e.message})"
FileUtils.rmdir(library_version.source_path)
end
def expand_gem(io, library_version)
logger.info "Expanding remote gem #{library_version.to_s(false)} to #{library_version.source_path}..."
reader = Gem::Package::TarReader.new(io)
reader.each do |pkg|
if pkg.full_name == "data.tar.gz"
Zlib::GzipReader.wrap(pkg) do |gzio|
tar = Gem::Package::TarReader.new(gzio)
tar.each do |entry|
file = File.join(library_version.source_path, entry.full_name)
FileUtils.mkdir_p(File.dirname(file))
File.open(file, "wb") do |out|
out.write(entry.read)
out.fsync rescue nil
end
end
end
break
end
end
end
def disallowed?(library_version)
if library_version.disallowed?
logger.info "Skip downloading for disallowed gem #{library_version}"
true
else
false
end
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/serializers/library_version_serializer.rb | app/serializers/library_version_serializer.rb | class LibraryVersionSerializer < ActiveJob::Serializers::ObjectSerializer
def serialize(library_version)
super("marshal" => Marshal.dump(library_version))
end
def deserialize(data)
Marshal.load(data["marshal"])
end
def klass
YARD::Server::LibraryVersion
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/helpers/shell_helper.rb | app/helpers/shell_helper.rb | module ShellHelper
def sh(command, title: nil, show_output: false, raise_error: true)
title ||= command
logger.info("#{title}: #{command}")
if raise_error
result, out_data, err_data = 0, "", ""
Open3.popen3(command) do |_, out, err, thr|
out_data, err_data, result = out.read, err.read, thr.value
end
else
`#{command}`
result = $?
end
log = "#{title}, result=#{result.to_i}"
logger.info(log)
output = "STDOUT:\n#{out_data}\n\nSTDERR:\n#{err_data}"
if raise_error && result != 0
data = "#{log}\n\n#{output}\n\n"
logger.error("STDERR:\n#{err_data}\n")
raise IOError, "Error executing command (exit=#{result}): #{data}"
elsif show_output
puts(output)
end
result
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/helpers/application_helper.rb | app/helpers/application_helper.rb | module ApplicationHelper
LIBRARY_TYPES = {
featured: "Gem",
stdlib: "Standard Library",
gems: "Gem",
github: "GitHub repository"
}.freeze
LIBRARY_ALT_TYPES = {
featured: "Gem",
stdlib: "Standard Library",
gems: "Gem",
github: "GitHub Project"
}.freeze
HAS_SEARCH = Set.new(%w[github gems])
def nav_links
{
"Featured" => featured_index_path,
"Stdlib" => stdlib_index_path,
"RubyGems" => gems_path,
"GitHub" => github_index_path
}
end
def settings
Rubydoc.config
end
def page_title
"#{settings.name}: #{title_content}"
end
def title_content
@page_title || content_for(:title) || page_description
end
def page_description
@page_description || content_for(:description) || settings.description
end
def link_to_library(library, version = nil)
prefix = case library.source
when :featured
"docs"
when :remote_gem
"gems"
else
library.source.to_s
end
url = "#/#{prefix}/#{library.name}#{version ? "/" : ""}#{version}"
link_to(version || library.name, url, data: { controller: "rewrite-link", turbo: false })
end
def library_name
params[:name] || [ params[:username], params[:project] ].join("/")
end
def library_type
LIBRARY_TYPES[action_name.to_sym]
end
def library_type_alt
LIBRARY_ALT_TYPES[action_name.to_sym]
end
def has_search?
HAS_SEARCH.include?(controller_name)
end
def sorted_versions(library)
library.library_versions.map(&:version)
end
def has_featured?
Rubydoc.config.libraries[:featured].size > 0
end
def featured_libraries
featured_config = Rubydoc.config.libraries[:featured]
return [] if featured_config.blank?
# Batch load all gem libraries in one query to avoid N+1
gem_names = featured_config.select { |_, source| source == "gem" }.keys
gem_libraries = Library.gem.where(name: gem_names).index_by(&:name)
featured_config.map do |name, source|
if source == "gem"
gem_libraries[name.to_s]
elsif source == "featured"
versions = FeaturedLibrary.versions_for(name)
Library.new(name: name, source: :featured, versions: versions)
end
end.compact
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/controllers/help_controller.rb | app/controllers/help_controller.rb | class HelpController < ApplicationController
layout "modal"
def index
@no_margin = true
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/controllers/rubygems_webhook_controller.rb | app/controllers/rubygems_webhook_controller.rb | class RubygemsWebhookController < ApplicationController
def create
if settings.integrations.rubygems.blank?
logger.error "RubyGems integration not configured, failing webhook request"
render status: :unauthorized
return
end
data = JSON.parse(request.body.read || "{}")
authorization = Digest::SHA2.hexdigest(data["name"] + data["version"] + settings.integrations.rubygems)
if request.headers["Authorization"] != authorization
logger.error "RubyGems webhook unauthorized: #{request.headers["Authorization"]}"
render status: :unauthorized
return
end
lib = Library.gem.find_or_create_by!(name: data["name"])
lib.versions ||= []
lib.versions |= [ data["version"] ]
lib.save!
render status: :ok
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/controllers/github_controller.rb | app/controllers/github_controller.rb | class GithubController < ApplicationController
include AlphaIndexable
include Searchable
include Pageable
include Cacheable
layout "modal", only: [ :add_project, :create ]
prepend_before_action do
@title = "GitHub Projects"
# Select only needed columns to reduce memory usage
@collection = Library.allowed_github.select(:id, :name, :source, :owner, :versions, :updated_at)
end
def index
render "shared/library_list"
end
def add_project
@project ||= GithubProject.new
end
def create
@project = GithubProject.new(params.require(:github_project).permit(%i[url commit]))
if @project.validate
GithubCheckoutJob.perform_now(owner: @project.owner, project: @project.name, commit: @project.commit)
redirect_to yard_github_path(@project.owner, @project.name, @project.commit)
else
render :add_project
end
rescue IOError => e
logger.error "Failed to create GitHub project: #{e.message}"
@project.errors.add(:url, "could not be cloned. Please check the URL and try again.")
render :add_project
rescue DisallowedCheckoutError => e
logger.error "Failed to create GitHub project: #{e.message}"
@project.errors.add(:url, "is not allowed. Please check the URL and try again.")
render :add_project
end
private
def default_alpha_index
nil
end
def set_alpha_index_collection
@collection = @collection.reorder(updated_at: :desc).limit(10) if @letter.blank?
super
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/controllers/yard_controller.rb | app/controllers/yard_controller.rb | class YARDController < ApplicationController
include Skylight::Helpers
layout "yard"
ADAPTERS = {
featured: { store: LibraryStore::FeaturedStore, router: LibraryRouter::FeaturedRouter },
stdlib: { store: LibraryStore::StdlibStore, router: LibraryRouter::StdlibRouter },
gems: { store: LibraryStore::GemStore, router: LibraryRouter::GemRouter },
github: { store: LibraryStore::GithubStore, router: LibraryRouter::GithubRouter }
}.freeze
def stdlib; respond end
def featured; respond end
def gems
if Rubydoc.config.gem_hosting.enabled
respond
else
render plain: "Gem hosting is disabled", status: 404
end
end
def github
if Rubydoc.config.github_hosting.enabled
respond
else
render plain: "GitHub hosting is disabled", status: 404
end
end
private
def set_adapter
values = ADAPTERS[action_name.to_sym]
@store = values[:store].new
@router = values[:router]
@adapter = YARD::Server::RackAdapter.new(
@store,
{ single_library: false, caching: false, safe_mode: true, router: @router },
{ DocumentRoot: Rails.root.join("storage", "yard_public") }
)
end
def set_whitelisted
YARD::Config.options[:safe_mode] = case action_name
when "featured", "stdlib"
false
when "gems"
Rubydoc.config.whitelisted_gems&.include?(library_version.name) || false
when "github"
Rubydoc.config.whitelisted_projects&.include?(library_version.name) || false
else
true
end
end
def respond
set_adapter
if library_version.blank?
render "errors/library_not_found", status: 404, layout: "application"
return
end
status, headers, body = call_adapter
@contents, @title = extract_title_and_body(body)
status = 404 if @contents.blank?
if status == 404
render "errors/library_not_found", status: 404, layout: "application"
return
elsif status == 200
visit_library
expires_in 1.day, public: true
end
if status == 200 && Mime::Type.lookup(headers["Content-Type"]).html?
render :show
else
render plain: body.first, status: status, headers: headers, content_type: headers["Content-Type"]
end
end
def visit_library
FileUtils.touch(library_version.source_path)
end
def library_version
route = [ params[:name], params[:username], params[:project], params[:rest] ].compact.join("/")
@library_version ||= @router.new(@adapter).parse_library_from_path(route.split("/")).first
end
def call_adapter
@@adapter_mutex ||= Mutex.new
@@adapter_mutex.synchronize do
set_whitelisted
@adapter.call(request.env)
end
end
def extract_title_and_body(body)
if body.first.to_s =~ /<title>(.*?)<\/title>(.*)/mi
[ $2, $1 ]
else
[ body.first, nil ]
end
end
%i[call_adapter visit_library library_version respond render set_adapter set_whitelisted extract_title_and_body].each do |m|
instrument_method(m)
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/controllers/gems_controller.rb | app/controllers/gems_controller.rb | class GemsController < ApplicationController
include AlphaIndexable
include Searchable
include Pageable
include Cacheable
prepend_before_action do
@title = "RubyGems"
# Select only needed columns to reduce memory usage
@collection = Library.allowed_gem.select(:id, :name, :source, :owner, :versions)
end
def index
render "shared/library_list"
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/controllers/github_webhook_controller.rb | app/controllers/github_webhook_controller.rb | class GithubWebhookController < ApplicationController
def create
data = JSON.parse(request.body.read || "{}")
payload = data.has_key?("payload") ? data["payload"] : data
url = (payload["repository"] || {})["url"]
commit = (payload["repository"] || {})["commit"]
@project = GithubProject.new(url:, commit:)
GithubCheckoutJob.perform_later(owner: @project.owner, project: @project.name, commit: @project.commit)
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/controllers/stdlib_controller.rb | app/controllers/stdlib_controller.rb | class StdlibController < ApplicationController
include Cacheable
prepend_before_action do
@title = "Ruby Standard Library"
@page_title = @title
@collection = Library.stdlib.all
end
def index
render "shared/library_list"
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/controllers/errors_controller.rb | app/controllers/errors_controller.rb | class ErrorsController < ApplicationController
VALID_STATUS_CODES = %w[400 404 406 422 500].freeze
def self.constraints
{ code: Regexp.new(VALID_STATUS_CODES.join("|")) }
end
def show
status_code = VALID_STATUS_CODES.include?(params[:code]) ? params[:code] : 500
respond_to do |format|
format.html { render status: status_code }
format.any { head status_code }
end
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/controllers/about_controller.rb | app/controllers/about_controller.rb | class AboutController < ApplicationController
layout "modal"
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/controllers/featured_controller.rb | app/controllers/featured_controller.rb | class FeaturedController < ApplicationController
include Cacheable
include ApplicationHelper
prepend_before_action do
@title = "Featured Libraries"
@page_title = @title
@collection = featured_libraries
end
def index
render "shared/library_list"
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/controllers/application_controller.rb | app/controllers/application_controller.rb | class ApplicationController < ActionController::Base
skip_forgery_protection
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/controllers/concerns/pageable.rb | app/controllers/concerns/pageable.rb | module Pageable
extend ActiveSupport::Concern
PAGE_SIZE = 100
included do
before_action :set_pagination
end
def set_pagination
@page = params[:page]&.to_i || 1
@total_pages = (@collection.except(:select).count / PAGE_SIZE.to_f).ceil
@collection = @collection.offset((@page - 1) * PAGE_SIZE).limit(PAGE_SIZE)
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/controllers/concerns/searchable.rb | app/controllers/concerns/searchable.rb | module Searchable
extend ActiveSupport::Concern
included do
before_action :load_search_query, if: -> { params[:q].present? }
end
def load_search_query
@search = params[:q]
@page_description = "#{@title} Search Results for '#{h @search}'"
@exact_match = @collection.dup.where("lower(name) = ?", @search.downcase).first
@collection = @collection.where("lower(name) LIKE ? AND lower(name) != ?", "%#{@search.downcase}%", @search.downcase)
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/controllers/concerns/alpha_indexable.rb | app/controllers/concerns/alpha_indexable.rb | module AlphaIndexable
extend ActiveSupport::Concern
included do
before_action :set_alpha_index
end
def set_alpha_index
@has_alpha_index = true
@letter = params[:letter] || default_alpha_index
@page_title = "#{@title} Index: #{@letter.upcase}" if @letter.present?
set_alpha_index_collection
end
def default_alpha_index
"a"
end
def set_alpha_index_collection
@collection = @collection.where("lower(name) LIKE ?", "#{@letter.downcase}%") if @letter.present?
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/controllers/concerns/cacheable.rb | app/controllers/concerns/cacheable.rb | module Cacheable
extend ActiveSupport::Concern
included do
before_action :set_cache_headers
end
private
def set_cache_headers
expires_in 1.day, public: true
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/models/library.rb | app/models/library.rb | class Library < ApplicationRecord
enum :source, %i[remote_gem github stdlib featured].index_with(&:to_s)
default_scope { order("lower(name) ASC") }
scope :gem, -> { where(source: :remote_gem) }
scope :github, -> { where(source: :github) }
scope :stdlib, -> { where(source: :stdlib) }
scope :allowed_gem, -> do
list = Rubydoc.config.libraries.disallowed_gems
list.blank? ? gem : gem.where.not("name LIKE ANY (array[?])", wildcard(list))
end
scope :allowed_github, -> do
list = Rubydoc.config.libraries.disallowed_projects
list.blank? ? github : github.where.not("concat(owner, '/', name) LIKE ANY (array[?])", wildcard(list))
end
def self.wildcard(list)
list.map { |item| item.gsub("*", "%") }
end
def library_versions
@library_versions ||= begin
items = versions.map do |v|
ver, platform = *v.split(",")
lib = YARD::Server::LibraryVersion.new(name, ver, nil, source)
lib.platform = platform
lib
end
source == :github ? sorted_github_library_versions(items) : items
end
end
def name
case source
when :github
"#{owner}/#{self[:name]}"
else
self[:name]
end
end
def project
self[:name]
end
def source
self[:source].to_sym
end
private
def sorted_github_library_versions(items)
root = GithubLibrary.base_path.join(project, owner)
primary_branch = begin
root.join(".primary_branch").read.strip rescue nil
rescue Errno::ENOENT
nil
end
items.sort_by do |item|
path = Pathname.new(item.source_path)
begin
path.basename.to_s == primary_branch ? -1 : path.join(".yardoc", "complete").mtime.to_i
rescue Errno::ENOENT
0
end
end.reverse
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/models/stdlib_installer.rb | app/models/stdlib_installer.rb | class StdlibInstaller
PREFIX = StdlibLibrary.base_path.to_s
attr_accessor :path, :version
def initialize(version)
self.version = version
setup_ruby_clone
self.path = ruby_root.to_s
end
def ruby_root
@ruby_root ||= Rubydoc.storage_path.join("ruby")
end
def setup_ruby_clone
system "git clone https://github.com/ruby/ruby #{ruby_root}" unless ruby_root.directory?
system "git -C #{ruby_root} fetch --all"
system "git -C #{ruby_root} checkout v#{version.gsub('.', '_')}"
end
def install
FileUtils.mkdir_p(PREFIX)
install_exts
install_libs
install_core
end
private
def install_core
puts "Installing core libraries"
FileUtils.mkdir_p(repo_path("core"))
dstpath = repo_path("core")
[ "*.c", "*.y", "README", "README.EXT", "LEGAL" ].each do |file|
FileUtils.cp(Dir.glob(File.join(path, file)), dstpath)
end
File.open(File.join(dstpath, ".yardopts"), "w") do |file|
file.puts "--protected --private *.c *.y - README.EXT LEGAL"
end
end
def install_exts
exts = Dir[File.join(path, "ext", "*")].select { |t| File.directory?(t) && !t.ends_with?(".gemspec") }
exts = exts.reject { |t| t =~ /-test-/ }
exts.each do |ext|
extpath = repo_path(ext)
puts "Installing extension #{clean_glob(ext)}..."
FileUtils.mkdir_p(File.dirname(extpath))
FileUtils.cp_r(ext, extpath)
write_yardopts(ext)
end
end
def install_libs
libs = Dir[File.join(path, "lib", "*")]
installed = { "ubygems" => true }
libs.each do |lib|
libname = clean_glob(lib)
next if libname.ends_with?(".gemspec")
next if installed[libname]
libpath = repo_path(lib)
puts "Installing library #{libname}..."
libfilename = lib.gsub(/\.rb$/, "") + ".rb"
dstpath = File.join(libpath, "lib")
FileUtils.mkdir_p(dstpath)
FileUtils.cp_r(lib, dstpath) if lib !~ /\.rb$/
if File.file?(libfilename)
FileUtils.cp(libfilename, dstpath)
extract_readme(libfilename)
end
write_yardopts(lib)
installed[lib] = true
end
end
def clean_glob(directory)
directory.sub(/^#{path}\/(ext|lib)\//, "").sub(/\.rb$/, "")
end
def repo_path(name)
File.join(PREFIX, clean_glob(name), version)
end
def write_yardopts(name)
File.open(File.join(repo_path(name), ".yardopts"), "w") do |file|
file.puts "**/*.rb **/*.c"
end
end
def extract_readme(name)
puts "Extracting README from #{clean_glob(name)}"
readme_contents = ""
File.readlines(name).each do |line|
if line =~ /^\s*#\s(.*)/
readme_contents << $1 << "\n"
elsif readme_contents != ""
break
end
end
File.open(File.join(repo_path(name), "README.rdoc"), "w") do |file|
file.write(readme_contents)
end
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/models/application_record.rb | app/models/application_record.rb | class ApplicationRecord < ActiveRecord::Base
primary_abstract_class
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/models/github_project.rb | app/models/github_project.rb | class GithubProject
include ActiveModel::API
attr_accessor :url, :commit
validates_format_of :url, with: %r{\Ahttps://github.com/[a-z0-9\-_\.]+/[a-z0-9\-_\.]+\z}i
validates_format_of :commit, with: /\A[0-9a-z_\.-]{1,40}\z/i, allow_blank: true
def owner
path.first
end
def name
path.second
end
def path
URI(url).path[1..].split("/")
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/models/disallowed_checkout_error.rb | app/models/disallowed_checkout_error.rb | class DisallowedCheckoutError < StandardError
def initialize(owner:, project:)
super("Invalid checkout for #{owner}/#{project}")
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/models/concerns/stdlib_library.rb | app/models/concerns/stdlib_library.rb | module StdlibLibrary
extend ActiveSupport::Concern
def load_yardoc_from_stdlib
return if ready?
GenerateDocsJob.perform_later(self)
raise YARD::Server::LibraryNotPreparedError
end
def source_path_for_stdlib
StdlibLibrary.base_path.join(name, version).to_s
end
def yardoc_file_for_stdlib
source_yardoc_file
end
def self.base_path
@base_path ||= Rubydoc.storage_path.join("repos", "stdlib")
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/models/concerns/featured_library.rb | app/models/concerns/featured_library.rb | module FeaturedLibrary
extend ActiveSupport::Concern
def load_yardoc_from_featured
return if ready?
GenerateDocsJob.perform_later(self)
raise YARD::Server::LibraryNotPreparedError
end
def source_path_for_featured
FeaturedLibrary.base_path.join(name, version).to_s
end
def yardoc_file_for_featured
source_yardoc_file
end
def self.base_path
@base_path ||= Rubydoc.storage_path.join("repos", "featured")
end
def self.versions_for(name)
VersionSorter.sort(base_path.join(name.to_s).children.select(&:directory?).map(&:basename).map(&:to_s))
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/models/concerns/github_library.rb | app/models/concerns/github_library.rb | module GithubLibrary
extend ActiveSupport::Concern
def load_yardoc_from_github
return if ready?
GenerateDocsJob.perform_later(self)
raise YARD::Server::LibraryNotPreparedError
end
def source_path_for_github
GithubLibrary.base_path.join(name.split("/", 2).reverse.join("/"), version).to_s
end
def yardoc_file_for_github
source_yardoc_file
end
def self.base_path
@base_path ||= Rubydoc.storage_path.join("repos", "github")
end
def disallowed_list
source.to_sym == :github ? Rubydoc.config.libraries.disallowed_projects : super
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/models/concerns/gem_library.rb | app/models/concerns/gem_library.rb | module GemLibrary
extend ActiveSupport::Concern
def load_yardoc_from_remote_gem
return if ready?
GenerateDocsJob.perform_later(self)
raise YARD::Server::LibraryNotPreparedError
end
def source_path_for_remote_gem
GemLibrary.base_path.join(name[0].downcase, name, version).to_s
end
def yardoc_file_for_remote_gem
source_yardoc_file
end
def self.base_path
@base_path ||= Rubydoc.storage_path.join("repos", "gems")
end
def disallowed_list
source.to_sym == :remote_gem ? Rubydoc.config.libraries.disallowed_gems : super
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/models/concerns/disallowed_library.rb | app/models/concerns/disallowed_library.rb | module DisallowedLibrary
extend ActiveSupport::Concern
def disallowed?
disallowed_list.any? { |disallowed_name| wilcard_match?(name, disallowed_name) }
end
def disallowed_list
[]
end
def wilcard_match?(name, disallowed_name)
return true if name == disallowed_name
return true if disallowed_name == "*"
regex = Regexp.new(disallowed_name.gsub("*", ".*"))
regex.match?(name)
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/models/library_router/github_router.rb | app/models/library_router/github_router.rb | module LibraryRouter
class GithubRouter < YARD::Server::Router
def docs_prefix; "github" end
def list_prefix; "list/github" end
def search_prefix; "search/github" end
def static_prefix; "static/github" end
def parse_library_from_path(paths)
library, paths = nil, paths.dup
github_proj = paths[0, 2].join("/")
if libs = adapter.libraries[github_proj]
paths.shift; paths.shift
if library = libs.find { |l| l.version == paths.first }
request.version_supplied = true if request
paths.shift
else # use the last lib in the list
request.version_supplied = false if request
library = libs.last
end
end
[ library, paths ]
end
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/models/library_router/stdlib_router.rb | app/models/library_router/stdlib_router.rb | module LibraryRouter
class StdlibRouter < YARD::Server::Router
def docs_prefix; "stdlib" end
def list_prefix; "list/stdlib" end
def search_prefix; "search/stdlib" end
def static_prefix; "static/stdlib" end
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/models/library_router/featured_router.rb | app/models/library_router/featured_router.rb | module LibraryRouter
class FeaturedRouter < YARD::Server::Router
def docs_prefix; "docs" end
def list_prefix; "list/docs" end
def search_prefix; "search/docs" end
def static_prefix; "static/docs" end
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/models/library_router/gem_router.rb | app/models/library_router/gem_router.rb | module LibraryRouter
class GemRouter < YARD::Server::Router
def docs_prefix; "gems" end
def list_prefix; "list/gems" end
def search_prefix; "search/gems" end
def static_prefix; "static/gems" end
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/models/library_store/github_store.rb | app/models/library_store/github_store.rb | module LibraryStore
class GithubStore
include Enumerable
def [](name)
(@items ||= {})[name] ||= begin
parts = parse_name(name)
Library.allowed_github.find_by(owner: parts.first, name: parts.last)&.library_versions
end
end
def []=(name, versions)
# read-only access
end
def has_key?(name) parts = parse_name(name); Library.allowed_github.exists?(owner: parts.first, name: parts.last) end
def each(&block) Library.allowed_github.all.each { |lib| yield "#{lib.owner}/#{lib.name}", lib.library_versions } end
def size; Library.allowed_github.count end
def empty?; size == 0 end
def keys
[]
end
def values
[]
end
def parse_name(name)
name.split("/")
end
def scope
Library.allowed_github
end
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/models/library_store/stdlib_store.rb | app/models/library_store/stdlib_store.rb | module LibraryStore
class StdlibStore
include Enumerable
def base_path
@base_path ||= StdlibLibrary.base_path.to_s
end
def [](name)
versions = Dir.glob(File.join(base_path, name, "*")).map { |path| File.basename(path) }
VersionSorter.sort(versions).map do |version|
YARD::Server::LibraryVersion.new(name, version, nil, :stdlib)
end
end
def []=(name, value)
# read-only db
end
def has_key?(key)
self[key] ? true : false
end
def keys
Dir.entries(base_path).map do |name|
next unless dir_valid?(name)
name
end.flatten.compact.uniq
end
def values
keys.map { |key| self[key] }
end
private
def dir_valid?(*dir)
File.directory?(File.join(base_path, *dir)) && dir.last !~ /^\.\.?$/
end
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/models/library_store/gem_store.rb | app/models/library_store/gem_store.rb | module LibraryStore
class GemStore
include Enumerable
def [](name)
(@items ||= {})[name] ||= scope.find_by(name: name)&.library_versions
end
def []=(name, versions)
# read-only access
end
def has_key?(name) scope.exists?(name: name) end
def each(&block) scope.all.each { |lib| yield lib.name, lib.library_versions } end
def size; scope.count end
def empty?; size == 0 end
def keys
[]
end
def values
[]
end
def scope
Library.allowed_gem
end
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/app/models/library_store/featured_store.rb | app/models/library_store/featured_store.rb | module LibraryStore
class FeaturedStore
include Enumerable
def [](name)
(@items ||= {})[name] ||= case Rubydoc.config.libraries.featured[name]
when "gem"
Library.gem.find_by(name: name)&.library_versions
when "featured"
versions = FeaturedLibrary.versions_for(name)
Library.new(name: name, source: :featured, versions: versions).library_versions
end
end
def []=(name, versions)
# read-only access
end
def has_key?(name) Rubydoc.config.libraries.featured.has_key?(name) end
def each(&block) Rubydoc.config.libraries.featured.keys.each { |k| self[k] } end
def size; Library.gem.count end
def empty?; size == 0 end
def keys; [] end
def values; [] end
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/docker/docparse/generate.rb | docker/docparse/generate.rb | #!/usr/bin/env ruby
require 'shellwords'
if File.exist?('.yardopts')
args = Shellwords.split(File.read('.yardopts').gsub(/^[ \t]*#.+/m, ''))
args.each_with_index do |arg, i|
next unless arg == '--plugin'
next unless args[i + 1]
cmd = "gem install --user-install yard-#{args[i + 1].inspect}"
puts "[docparse] Installing plugin: #{cmd}"
system(cmd)
end
end
require 'yard'
class YARD::CLI::Yardoc
def yardopts(file = options_file)
list = IO.read(file).shell_split
list.map { |a| %w[-c --use-cache --db -b --query].include?(a) ? '-o' : a }
rescue Errno::ENOENT
[]
end
end
YARD::CLI::Yardoc.run('-n', '-q')
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/db/seeds.rb | db/seeds.rb | # This file should ensure the existence of records required to run the application in every environment (production,
# development, test). The code here should be idempotent so that it can be executed at any point in every environment.
# The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup).
#
# Example:
#
# ["Action", "Comedy", "Drama", "Horror"].each do |genre_name|
# MovieGenre.find_or_create_by!(name: genre_name)
# end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/db/schema.rb | db/schema.rb | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# This file is the source Rails uses to define your schema when running `bin/rails
# db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to
# be faster and is potentially less error prone than running all of your
# migrations from scratch. Old migrations may fail to apply correctly if those
# migrations use external dependencies or application code.
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema[8.1].define(version: 2025_12_01_000001) do
# These are extensions that must be enabled in order to support this database
enable_extension "pg_catalog.plpgsql"
create_table "libraries", force: :cascade do |t|
t.datetime "created_at", null: false
t.string "name"
t.string "owner"
t.boolean "primary_fork", default: true
t.string "source"
t.datetime "updated_at", null: false
t.json "versions"
t.index "lower((name)::text) varchar_pattern_ops", name: "index_libraries_on_lower_name_pattern"
t.index ["name", "source", "owner"], name: "index_libraries_on_name_and_source_and_owner", unique: true
t.index ["owner"], name: "index_libraries_on_owner"
t.index ["source"], name: "index_libraries_on_source"
end
create_table "solid_cache_entries", force: :cascade do |t|
t.integer "byte_size", null: false
t.datetime "created_at", null: false
t.binary "key", null: false
t.bigint "key_hash", null: false
t.binary "value", null: false
t.index ["byte_size"], name: "index_solid_cache_entries_on_byte_size"
t.index ["key_hash", "byte_size"], name: "index_solid_cache_entries_on_key_hash_and_byte_size"
t.index ["key_hash"], name: "index_solid_cache_entries_on_key_hash", unique: true
end
create_table "solid_queue_blocked_executions", force: :cascade do |t|
t.string "concurrency_key", null: false
t.datetime "created_at", null: false
t.datetime "expires_at", null: false
t.bigint "job_id", null: false
t.integer "priority", default: 0, null: false
t.string "queue_name", null: false
t.index ["concurrency_key", "priority", "job_id"], name: "index_solid_queue_blocked_executions_for_release"
t.index ["expires_at", "concurrency_key"], name: "index_solid_queue_blocked_executions_for_maintenance"
t.index ["job_id"], name: "index_solid_queue_blocked_executions_on_job_id", unique: true
end
create_table "solid_queue_claimed_executions", force: :cascade do |t|
t.datetime "created_at", null: false
t.bigint "job_id", null: false
t.bigint "process_id"
t.index ["job_id"], name: "index_solid_queue_claimed_executions_on_job_id", unique: true
t.index ["process_id", "job_id"], name: "index_solid_queue_claimed_executions_on_process_id_and_job_id"
end
create_table "solid_queue_failed_executions", force: :cascade do |t|
t.datetime "created_at", null: false
t.text "error"
t.bigint "job_id", null: false
t.index ["job_id"], name: "index_solid_queue_failed_executions_on_job_id", unique: true
end
create_table "solid_queue_jobs", force: :cascade do |t|
t.string "active_job_id"
t.text "arguments"
t.string "class_name", null: false
t.string "concurrency_key"
t.datetime "created_at", null: false
t.datetime "finished_at"
t.integer "priority", default: 0, null: false
t.string "queue_name", null: false
t.datetime "scheduled_at"
t.datetime "updated_at", null: false
t.index ["active_job_id"], name: "index_solid_queue_jobs_on_active_job_id"
t.index ["class_name"], name: "index_solid_queue_jobs_on_class_name"
t.index ["finished_at"], name: "index_solid_queue_jobs_on_finished_at"
t.index ["queue_name", "finished_at"], name: "index_solid_queue_jobs_for_filtering"
t.index ["scheduled_at", "finished_at"], name: "index_solid_queue_jobs_for_alerting"
end
create_table "solid_queue_pauses", force: :cascade do |t|
t.datetime "created_at", null: false
t.string "queue_name", null: false
t.index ["queue_name"], name: "index_solid_queue_pauses_on_queue_name", unique: true
end
create_table "solid_queue_processes", force: :cascade do |t|
t.datetime "created_at", null: false
t.string "hostname"
t.string "kind", null: false
t.datetime "last_heartbeat_at", null: false
t.text "metadata"
t.string "name", null: false
t.integer "pid", null: false
t.bigint "supervisor_id"
t.index ["last_heartbeat_at"], name: "index_solid_queue_processes_on_last_heartbeat_at"
t.index ["name", "supervisor_id"], name: "index_solid_queue_processes_on_name_and_supervisor_id", unique: true
t.index ["supervisor_id"], name: "index_solid_queue_processes_on_supervisor_id"
end
create_table "solid_queue_ready_executions", force: :cascade do |t|
t.datetime "created_at", null: false
t.bigint "job_id", null: false
t.integer "priority", default: 0, null: false
t.string "queue_name", null: false
t.index ["job_id"], name: "index_solid_queue_ready_executions_on_job_id", unique: true
t.index ["priority", "job_id"], name: "index_solid_queue_poll_all"
t.index ["queue_name", "priority", "job_id"], name: "index_solid_queue_poll_by_queue"
end
create_table "solid_queue_recurring_executions", force: :cascade do |t|
t.datetime "created_at", null: false
t.bigint "job_id", null: false
t.datetime "run_at", null: false
t.string "task_key", null: false
t.index ["job_id"], name: "index_solid_queue_recurring_executions_on_job_id", unique: true
t.index ["task_key", "run_at"], name: "index_solid_queue_recurring_executions_on_task_key_and_run_at", unique: true
end
create_table "solid_queue_recurring_tasks", force: :cascade do |t|
t.text "arguments"
t.string "class_name"
t.string "command", limit: 2048
t.datetime "created_at", null: false
t.text "description"
t.string "key", null: false
t.integer "priority", default: 0
t.string "queue_name"
t.string "schedule", null: false
t.boolean "static", default: true, null: false
t.datetime "updated_at", null: false
t.index ["key"], name: "index_solid_queue_recurring_tasks_on_key", unique: true
t.index ["static"], name: "index_solid_queue_recurring_tasks_on_static"
end
create_table "solid_queue_scheduled_executions", force: :cascade do |t|
t.datetime "created_at", null: false
t.bigint "job_id", null: false
t.integer "priority", default: 0, null: false
t.string "queue_name", null: false
t.datetime "scheduled_at", null: false
t.index ["job_id"], name: "index_solid_queue_scheduled_executions_on_job_id", unique: true
t.index ["scheduled_at", "priority", "job_id"], name: "index_solid_queue_dispatch_all"
end
create_table "solid_queue_semaphores", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "expires_at", null: false
t.string "key", null: false
t.datetime "updated_at", null: false
t.integer "value", default: 1, null: false
t.index ["expires_at"], name: "index_solid_queue_semaphores_on_expires_at"
t.index ["key", "value"], name: "index_solid_queue_semaphores_on_key_and_value"
t.index ["key"], name: "index_solid_queue_semaphores_on_key", unique: true
end
add_foreign_key "solid_queue_blocked_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade
add_foreign_key "solid_queue_claimed_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade
add_foreign_key "solid_queue_failed_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade
add_foreign_key "solid_queue_ready_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade
add_foreign_key "solid_queue_recurring_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade
add_foreign_key "solid_queue_scheduled_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/db/migrate/20250426212855_create_libraries.rb | db/migrate/20250426212855_create_libraries.rb | class CreateLibraries < ActiveRecord::Migration[8.0]
def change
create_table :libraries do |t|
t.string :name
t.string :source
t.string :owner
t.boolean :primary_fork, default: true
t.json :versions
t.timestamps
end
add_index :libraries, [ :name, :source, :owner ], unique: true
add_index :libraries, :source
add_index :libraries, :owner
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/db/migrate/20251201000001_add_lower_name_index_to_libraries.rb | db/migrate/20251201000001_add_lower_name_index_to_libraries.rb | class AddLowerNameIndexToLibraries < ActiveRecord::Migration[8.0]
def change
# Add a functional index for efficient alphabetical filtering
# This improves the LIKE 'a%' queries used in AlphaIndexable concern
add_index :libraries, "lower(name) varchar_pattern_ops", name: "index_libraries_on_lower_name_pattern"
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/db/migrate/20250425155411_add_solid.rb | db/migrate/20250425155411_add_solid.rb | class AddSolid < ActiveRecord::Migration[8.0]
def change
create_table "solid_cache_entries", force: :cascade do |t|
t.binary "key", limit: 1024, null: false
t.binary "value", limit: 536870912, null: false
t.datetime "created_at", null: false
t.integer "key_hash", limit: 8, null: false
t.integer "byte_size", limit: 4, null: false
t.index [ "byte_size" ], name: "index_solid_cache_entries_on_byte_size"
t.index [ "key_hash", "byte_size" ], name: "index_solid_cache_entries_on_key_hash_and_byte_size"
t.index [ "key_hash" ], name: "index_solid_cache_entries_on_key_hash", unique: true
end
create_table "solid_queue_blocked_executions", force: :cascade do |t|
t.bigint "job_id", null: false
t.string "queue_name", null: false
t.integer "priority", default: 0, null: false
t.string "concurrency_key", null: false
t.datetime "expires_at", null: false
t.datetime "created_at", null: false
t.index [ "concurrency_key", "priority", "job_id" ], name: "index_solid_queue_blocked_executions_for_release"
t.index [ "expires_at", "concurrency_key" ], name: "index_solid_queue_blocked_executions_for_maintenance"
t.index [ "job_id" ], name: "index_solid_queue_blocked_executions_on_job_id", unique: true
end
create_table "solid_queue_claimed_executions", force: :cascade do |t|
t.bigint "job_id", null: false
t.bigint "process_id"
t.datetime "created_at", null: false
t.index [ "job_id" ], name: "index_solid_queue_claimed_executions_on_job_id", unique: true
t.index [ "process_id", "job_id" ], name: "index_solid_queue_claimed_executions_on_process_id_and_job_id"
end
create_table "solid_queue_failed_executions", force: :cascade do |t|
t.bigint "job_id", null: false
t.text "error"
t.datetime "created_at", null: false
t.index [ "job_id" ], name: "index_solid_queue_failed_executions_on_job_id", unique: true
end
create_table "solid_queue_jobs", force: :cascade do |t|
t.string "queue_name", null: false
t.string "class_name", null: false
t.text "arguments"
t.integer "priority", default: 0, null: false
t.string "active_job_id"
t.datetime "scheduled_at"
t.datetime "finished_at"
t.string "concurrency_key"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index [ "active_job_id" ], name: "index_solid_queue_jobs_on_active_job_id"
t.index [ "class_name" ], name: "index_solid_queue_jobs_on_class_name"
t.index [ "finished_at" ], name: "index_solid_queue_jobs_on_finished_at"
t.index [ "queue_name", "finished_at" ], name: "index_solid_queue_jobs_for_filtering"
t.index [ "scheduled_at", "finished_at" ], name: "index_solid_queue_jobs_for_alerting"
end
create_table "solid_queue_pauses", force: :cascade do |t|
t.string "queue_name", null: false
t.datetime "created_at", null: false
t.index [ "queue_name" ], name: "index_solid_queue_pauses_on_queue_name", unique: true
end
create_table "solid_queue_processes", force: :cascade do |t|
t.string "kind", null: false
t.datetime "last_heartbeat_at", null: false
t.bigint "supervisor_id"
t.integer "pid", null: false
t.string "hostname"
t.text "metadata"
t.datetime "created_at", null: false
t.string "name", null: false
t.index [ "last_heartbeat_at" ], name: "index_solid_queue_processes_on_last_heartbeat_at"
t.index [ "name", "supervisor_id" ], name: "index_solid_queue_processes_on_name_and_supervisor_id", unique: true
t.index [ "supervisor_id" ], name: "index_solid_queue_processes_on_supervisor_id"
end
create_table "solid_queue_ready_executions", force: :cascade do |t|
t.bigint "job_id", null: false
t.string "queue_name", null: false
t.integer "priority", default: 0, null: false
t.datetime "created_at", null: false
t.index [ "job_id" ], name: "index_solid_queue_ready_executions_on_job_id", unique: true
t.index [ "priority", "job_id" ], name: "index_solid_queue_poll_all"
t.index [ "queue_name", "priority", "job_id" ], name: "index_solid_queue_poll_by_queue"
end
create_table "solid_queue_recurring_executions", force: :cascade do |t|
t.bigint "job_id", null: false
t.string "task_key", null: false
t.datetime "run_at", null: false
t.datetime "created_at", null: false
t.index [ "job_id" ], name: "index_solid_queue_recurring_executions_on_job_id", unique: true
t.index [ "task_key", "run_at" ], name: "index_solid_queue_recurring_executions_on_task_key_and_run_at", unique: true
end
create_table "solid_queue_recurring_tasks", force: :cascade do |t|
t.string "key", null: false
t.string "schedule", null: false
t.string "command", limit: 2048
t.string "class_name"
t.text "arguments"
t.string "queue_name"
t.integer "priority", default: 0
t.boolean "static", default: true, null: false
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index [ "key" ], name: "index_solid_queue_recurring_tasks_on_key", unique: true
t.index [ "static" ], name: "index_solid_queue_recurring_tasks_on_static"
end
create_table "solid_queue_scheduled_executions", force: :cascade do |t|
t.bigint "job_id", null: false
t.string "queue_name", null: false
t.integer "priority", default: 0, null: false
t.datetime "scheduled_at", null: false
t.datetime "created_at", null: false
t.index [ "job_id" ], name: "index_solid_queue_scheduled_executions_on_job_id", unique: true
t.index [ "scheduled_at", "priority", "job_id" ], name: "index_solid_queue_dispatch_all"
end
create_table "solid_queue_semaphores", force: :cascade do |t|
t.string "key", null: false
t.integer "value", default: 1, null: false
t.datetime "expires_at", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index [ "expires_at" ], name: "index_solid_queue_semaphores_on_expires_at"
t.index [ "key", "value" ], name: "index_solid_queue_semaphores_on_key_and_value"
t.index [ "key" ], name: "index_solid_queue_semaphores_on_key", unique: true
end
add_foreign_key "solid_queue_blocked_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade
add_foreign_key "solid_queue_claimed_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade
add_foreign_key "solid_queue_failed_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade
add_foreign_key "solid_queue_ready_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade
add_foreign_key "solid_queue_recurring_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade
add_foreign_key "solid_queue_scheduled_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade
end
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/spec/rails_helper.rb | spec/rails_helper.rb | # This file is copied to spec/ when you run 'rails generate rspec:install'
require 'spec_helper'
ENV['RAILS_ENV'] ||= 'test'
require_relative '../config/environment'
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
# Uncomment the line below in case you have `--require rails_helper` in the `.rspec` file
# that will avoid rails generators crashing because migrations haven't been run yet
# return unless Rails.env.test?
require 'rspec/rails'
# Add additional requires below this line. Rails is not loaded until this point!
# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
# Rails.root.glob('spec/support/**/*.rb').sort_by(&:to_s).each { |f| require f }
`rails rubydoc:db:start` unless ENV["CI"].present?
Capybara.configure do |config|
config.default_selector = :css
end
# Ensures that the test database schema matches the current schema file.
# If there are pending migrations it will invoke `db:test:prepare` to
# recreate the test database by loading the schema.
# If you are not using ActiveRecord, you can remove these lines.
begin
ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
abort e.to_s.strip
end
RSpec.configure do |config|
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_paths = [
Rails.root.join('spec/fixtures')
]
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = true
# You can uncomment this line to turn off ActiveRecord support entirely.
# config.use_active_record = false
# RSpec Rails uses metadata to mix in different behaviours to your tests,
# for example enabling you to call `get` and `post` in request specs. e.g.:
#
# RSpec.describe UsersController, type: :request do
# # ...
# end
#
# The different available types are documented in the features, such as in
# https://rspec.info/features/8-0/rspec-rails
#
# You can also this infer these behaviours automatically by location, e.g.
# /spec/models would pull in the same behaviour as `type: :model` but this
# behaviour is considered legacy and will be removed in a future version.
#
# To enable this behaviour uncomment the line below.
# config.infer_spec_type_from_file_location!
# Filter lines from Rails gems in backtraces.
config.filter_rails_from_backtrace!
# arbitrary gems may also be filtered via:
# config.filter_gems_from_backtrace("gem name")
config.include FactoryBot::Syntax::Methods
end
# Reset storage
Rubydoc.storage_path.rmtree if Rubydoc.storage_path.directory?
Rubydoc.storage_path.mkpath
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
docmeta/rubydoc.info | https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/spec/spec_helper.rb | spec/spec_helper.rb | # This file was generated by the `rails generate rspec:install` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause
# this file to always be loaded, without a need to explicitly require it in any
# files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need
# it.
#
# See https://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
config.before(type: :system) do
driven_by :selenium, using: :headless_chrome, screen_size: [ 1200, 800 ]
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
# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
=begin
# This allows you to limit a spec run to individual examples or groups
# you care about by tagging them with `:focus` metadata. When nothing
# is tagged with `:focus`, all examples get run. RSpec also provides
# aliases for `it`, `describe`, and `context` that include `:focus`
# metadata: `fit`, `fdescribe` and `fcontext`, respectively.
config.filter_run_when_matching :focus
# Allows RSpec to persist some state between runs in order to support
# the `--only-failures` and `--next-failure` CLI options. We recommend
# you configure your source control system to ignore this file.
config.example_status_persistence_file_path = "spec/examples.txt"
# Limits the available syntax to the non-monkey patched syntax that is
# recommended. For more details, see:
# https://rspec.info/features/3-12/rspec-core/configuration/zero-monkey-patching-mode/
config.disable_monkey_patching!
# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = "doc"
end
# Print the 10 slowest examples and example groups at the
# end of the spec run, to help surface which specs are running
# particularly slow.
config.profile_examples = 10
# 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
# Seed global randomization in this process using the `--seed` CLI option.
# Setting this allows you to use `--seed` to deterministically reproduce
# test failures related to randomization by passing the same `--seed` value
# as the one that triggered the failure.
Kernel.srand config.seed
=end
end
def with_rubydoc_config(config)
let(:original_config) { Rubydoc.config }
before { Rubydoc.config = config }
after { Rubydoc.config = original_config }
yield
end
| ruby | MIT | 05379203c0f7e84c6f5df9bbbd384db5ff7ac532 | 2026-01-04T17:46:46.862481Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.