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
docmeta/rubydoc.info
https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/spec/jobs/download_gem_job_spec.rb
spec/jobs/download_gem_job_spec.rb
require 'rails_helper' RSpec.describe DownloadGemJob, type: :job do let(:library_version) do double('LibraryVersion', disallowed?: false, ready?: false, to_s: 'rails-7.0.0', platform: nil, source_path: '/tmp/gems/rails/7.0.0', source: :remote_gem, name: 'rails' ) end describe '#perform' do before do allow(FileUtils).to receive(:rm_rf) allow(FileUtils).to receive(:mkdir_p) allow(FileUtils).to receive(:rmdir) end context 'when library version is ready' do it 'skips download' do allow(library_version).to receive(:ready?).and_return(true) expect(URI).not_to receive(:open) subject.perform(library_version) end end context 'when library version is not ready' do it 'prepares directory structure' do expect(FileUtils).to receive(:rm_rf).with('/tmp/gems/rails/7.0.0') expect(FileUtils).to receive(:mkdir_p).with('/tmp/gems/rails/7.0.0') allow(URI).to receive(:open).and_raise(OpenURI::HTTPError.new('404', nil)) subject.perform(library_version) end it 'constructs correct gem URL' do expected_url = 'http://rubygems.org/gems/rails-7.0.0.gem' expect(URI).to receive(:open).with(expected_url) allow(URI).to receive(:open).and_raise(OpenURI::HTTPError.new('404', nil)) subject.perform(library_version) end context 'with platform specified' do before do allow(library_version).to receive(:platform).and_return('ruby') end it 'includes platform in URL' do expected_url = 'http://rubygems.org/gems/rails-7.0.0-ruby.gem' expect(URI).to receive(:open).with(expected_url) allow(URI).to receive(:open).and_raise(OpenURI::HTTPError.new('404', nil)) subject.perform(library_version) end end context 'with custom gem source' do with_rubydoc_config(gem_source: 'https://custom.gems.org/') do it 'uses custom gem source' do expected_url = 'https://custom.gems.org/gems/rails-7.0.0.gem' expect(URI).to receive(:open).with(expected_url) allow(URI).to receive(:open).and_raise(OpenURI::HTTPError.new('404', nil)) subject.perform(library_version) end end end context 'when download fails' do it 'removes directory and logs warning' do allow(URI).to receive(:open).and_raise(OpenURI::HTTPError.new('404 Not Found', nil)) expect(FileUtils).to receive(:rmdir).with('/tmp/gems/rails/7.0.0') subject.perform(library_version) end end end end describe '#expand_gem' do let(:io) { double('IO') } it 'expands gem data archive' do expect(Gem::Package::TarReader).to receive(:new).with(io) allow(Gem::Package::TarReader).to receive(:new).and_return([]) subject.expand_gem(io, library_version) end end end
ruby
MIT
05379203c0f7e84c6f5df9bbbd384db5ff7ac532
2026-01-04T17:46:46.862481Z
false
docmeta/rubydoc.info
https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/spec/jobs/delete_docs_job_spec.rb
spec/jobs/delete_docs_job_spec.rb
require 'rails_helper' RSpec.describe DeleteDocsJob, type: :job do let(:library_version) do double('LibraryVersion', source_path: '/tmp/gems/rails/7.0.0', source: :remote_gem, name: 'rails', version: '7.0.0', to_s: 'rails-7.0.0' ) end let(:library) do create(:gem, name: 'rails', versions: [ '7.0.0', '6.1.0' ]) end describe '#perform' do before do allow(CleanupUnvisitedDocsJob).to receive(:should_invalidate?).and_return(true) end context 'when library version should be invalidated' do it 'removes the library version from database' do allow(Library).to receive(:where).and_return(double(first: library)) allow(library).to receive(:versions).and_return([ '7.0.0', '6.1.0' ]) allow(library).to receive(:save) allow(Pathname).to receive(:new).and_return(double(rmtree: nil)) allow(CacheClearJob).to receive(:perform_later) expect(library.versions).to receive(:delete).with('7.0.0') subject.perform(library_version) end it 'removes the directory' do allow(Library).to receive(:where).and_return(double(first: library)) allow(library).to receive(:versions).and_return([ '7.0.0' ]) allow(library.versions).to receive(:delete) allow(library).to receive(:save) allow(CacheClearJob).to receive(:perform_later) path_double = double('Pathname') expect(Pathname).to receive(:new).with('/tmp/gems/rails/7.0.0').and_return(path_double) expect(path_double).to receive(:rmtree) subject.perform(library_version) end it 'queues cache clear job' do allow(Library).to receive(:where).and_return(double(first: library)) allow(library).to receive(:versions).and_return([ '7.0.0' ]) allow(library.versions).to receive(:delete) allow(library).to receive(:save) allow(Pathname).to receive(:new).and_return(double(rmtree: nil)) expect(CacheClearJob).to receive(:perform_later).with(library_version) subject.perform(library_version) end context 'when it is the last version' do it 'destroys the library record' do library.versions = [ '7.0.0' ] allow(Library).to receive(:where).and_return(double(first: library)) allow(library.versions).to receive(:delete) allow(library.versions).to receive(:empty?).and_return(true) allow(Pathname).to receive(:new).and_return(double(rmtree: nil)) allow(CacheClearJob).to receive(:perform_later) expect(library).to receive(:destroy) subject.perform(library_version) end end context 'when there are other versions' do it 'keeps the library record and saves' do allow(Library).to receive(:where).and_return(double(first: library)) allow(library).to receive(:versions).and_return([ '7.0.0', '6.1.0' ]) allow(library.versions).to receive(:delete) allow(library.versions).to receive(:empty?).and_return(false) allow(Pathname).to receive(:new).and_return(double(rmtree: nil)) allow(CacheClearJob).to receive(:perform_later) expect(library).to receive(:save) subject.perform(library_version) end end end context 'when library version should not be invalidated' do it 'does not remove anything' do allow(CleanupUnvisitedDocsJob).to receive(:should_invalidate?).and_return(false) expect(Library).not_to receive(:where) expect(Pathname).not_to receive(:new) subject.perform(library_version) end end context 'for GitHub library' do let(:github_version) do double('LibraryVersion', source_path: '/tmp/github/rails/rails/main', source: :github, name: 'rails/rails', version: 'main', to_s: 'rails/rails-main' ) end it 'handles owner/name format' do allow(CleanupUnvisitedDocsJob).to receive(:should_invalidate?).and_return(true) github_lib = create(:github, name: 'rails', owner: 'rails', versions: [ 'main' ]) allow(Library).to receive(:where).and_return(double(first: github_lib)) allow(github_lib.versions).to receive(:delete) allow(github_lib).to receive(:save) allow(Pathname).to receive(:new).and_return(double(rmtree: nil)) allow(CacheClearJob).to receive(:perform_later) expect { subject.perform(github_version) }.not_to raise_error 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/spec/jobs/github_checkout_job_spec.rb
spec/jobs/github_checkout_job_spec.rb
require 'rails_helper' RSpec.describe GithubCheckoutJob, type: :job do let(:owner) { 'rails' } let(:project) { 'rails' } let(:commit) { 'main' } subject { described_class.new } before do allow(subject).to receive(:sh).and_return(true) end describe '#perform' do let(:library_version) { double('LibraryVersion', disallowed?: false) } before do allow(subject).to receive(:library_version).and_return(library_version) allow(subject).to receive(:run_checkout).and_return(true) allow(subject).to receive(:register_project) allow(subject).to receive(:flush_cache) end it 'sets owner, project, and commit' do subject.perform(owner: owner, project: project, commit: commit) expect(subject.owner).to eq(owner) expect(subject.project).to eq(project) expect(subject.commit).to eq(commit) end it 'runs checkout process' do expect(subject).to receive(:run_checkout).and_return(true) subject.perform(owner: owner, project: project, commit: commit) end it 'registers the project after successful checkout' do expect(subject).to receive(:register_project) subject.perform(owner: owner, project: project, commit: commit) end it 'flushes cache after successful checkout' do expect(subject).to receive(:flush_cache) subject.perform(owner: owner, project: project, commit: commit) end context 'when commit is blank' do it 'uses primary branch' do allow(subject).to receive(:primary_branch).and_return('master') subject.perform(owner: owner, project: project, commit: '') expect(subject.commit).to eq('master') end end context 'when library is disallowed' do before do allow(library_version).to receive(:disallowed?).and_return(true) end it 'raises DisallowedCheckoutError' do expect { subject.perform(owner: owner, project: project, commit: commit) }.to raise_error(DisallowedCheckoutError) end end context 'when checkout fails' do before do allow(subject).to receive(:run_checkout).and_return(false) end it 'does not register project' do expect(subject).not_to receive(:register_project) subject.perform(owner: owner, project: project, commit: commit) end it 'does not flush cache' do expect(subject).not_to receive(:flush_cache) subject.perform(owner: owner, project: project, commit: commit) end end end describe '#commit=' do it 'converts empty string to nil' do subject.commit = '' expect(subject.commit).to be_nil end it 'truncates 40-character SHA to 6 characters' do subject.commit = 'a' * 40 expect(subject.commit).to eq('a' * 6) end it 'extracts valid commit reference' do subject.commit = ' abc123/branch_name ' expect(subject.commit).to eq('abc123/branch_name') end it 'handles branch names with dots, slashes, and underscores' do subject.commit = 'feature/my_branch.v1' expect(subject.commit).to eq('feature/my_branch.v1') end it 'sets nil value as nil' do subject.commit = nil expect(subject.commit).to be_nil end end describe '#name' do it 'returns owner/project format' do subject.owner = 'rails' subject.project = 'rails' expect(subject.name).to eq('rails/rails') end end describe '#url' do it 'returns GitHub URL' do subject.owner = 'rails' subject.project = 'rails' expect(subject.url).to eq('https://github.com/rails/rails') end end describe '#run_checkout' do let(:repository_path) { instance_double(Pathname, directory?: false) } before do allow(subject).to receive(:repository_path).and_return(repository_path) subject.commit = commit end context 'when commit is present and repository exists' do before do allow(repository_path).to receive(:directory?).and_return(true) end it 'runs checkout pull' do expect(subject).to receive(:run_checkout_pull).and_return(true) subject.run_checkout end end context 'when repository does not exist' do it 'runs checkout clone' do expect(subject).to receive(:run_checkout_clone).and_return(true) subject.run_checkout end end context 'when commit is not present' do before do subject.commit = nil end it 'runs checkout clone' do expect(subject).to receive(:run_checkout_clone).and_return(true) subject.run_checkout end end end describe '#run_checkout_pull' do let(:repository_path) { instance_double(Pathname, to_s: '/path/to/repo', join: yardoc_path) } let(:yardoc_path) { instance_double(Pathname, directory?: true, rmtree: nil) } before do allow(subject).to receive(:repository_path).and_return(repository_path) allow(subject).to receive(:write_fork_data) subject.owner = owner subject.project = project subject.commit = commit end it 'writes fork data' do expect(subject).to receive(:write_fork_data) subject.run_checkout_pull end it 'runs git reset and pull commands' do expect(subject).to receive(:sh).with( a_string_matching(/git reset --hard.*git pull --force/), hash_including(title: "Updating project #{owner}/#{project}") ) subject.run_checkout_pull end it 'removes .yardoc directory if present' do expect(yardoc_path).to receive(:rmtree) subject.run_checkout_pull end context 'when .yardoc does not exist' do before do allow(yardoc_path).to receive(:directory?).and_return(false) end it 'does not try to remove it' do expect(yardoc_path).not_to receive(:rmtree) subject.run_checkout_pull end end end describe '#run_checkout_clone' do let(:temp_clone_path) { instance_double(Pathname, to_s: '/tmp/clone', parent: temp_parent) } let(:temp_parent) { instance_double(Pathname, mkpath: nil) } let(:repository_path) { instance_double(Pathname, to_s: '/path/to/repo', parent: repo_parent) } let(:repo_parent) { instance_double(Pathname, mkpath: nil) } before do allow(subject).to receive(:temp_clone_path).and_return(temp_clone_path) allow(subject).to receive(:repository_path).and_return(repository_path) allow(subject).to receive(:write_primary_branch_file) allow(subject).to receive(:write_fork_data) allow(subject).to receive(:`).and_return('main') subject.owner = owner subject.project = project subject.commit = commit end it 'creates parent directory for temp clone path' do expect(temp_parent).to receive(:mkpath) subject.run_checkout_clone end it 'runs git clone command' do expect(subject).to receive(:sh).with( a_string_matching(/git clone.*--depth 1.*--single-branch/), hash_including(title: "Cloning project #{owner}/#{project}") ) allow(subject).to receive(:sh).with(a_string_matching(/rm -rf/), anything) subject.run_checkout_clone end it 'includes branch option when commit is present' do expect(subject).to receive(:sh).with( a_string_matching(/--branch #{commit}/), anything ) allow(subject).to receive(:sh).with(a_string_matching(/rm -rf/), anything) subject.run_checkout_clone end it 'creates parent directory for repository path' do expect(repo_parent).to receive(:mkpath) subject.run_checkout_clone end it 'writes fork data' do expect(subject).to receive(:write_fork_data) subject.run_checkout_clone end it 'moves temp clone to repository path' do expect(subject).to receive(:sh).with( a_string_matching(/rm -rf.*mv/), hash_including(title: "Move #{owner}/#{project} into place") ) subject.run_checkout_clone end it 'returns true' do expect(subject.run_checkout_clone).to be true end context 'when commit is blank' do before do subject.commit = nil end it 'does not include branch option' do expect(subject).to receive(:sh).with( a_string_matching(/git clone.*--depth 1.*--single-branch(?!.*--branch)/), anything ) allow(subject).to receive(:sh).with(a_string_matching(/rm -rf/), anything) subject.run_checkout_clone end it 'writes primary branch file' do expect(subject).to receive(:write_primary_branch_file) subject.run_checkout_clone end it 'detects current branch' do expect(subject).to receive(:`).with(a_string_matching(/git.*rev-parse.*HEAD/)) subject.run_checkout_clone expect(subject.commit).to eq('main') end end context 'when commit is present' do it 'does not write primary branch file' do expect(subject).not_to receive(:write_primary_branch_file) subject.run_checkout_clone end end end describe 'shell injection prevention' do let(:malicious_commit) { "main; rm -rf /" } let(:malicious_owner) { "owner'; rm -rf /; echo '" } let(:malicious_project) { "project`rm -rf /`" } before do allow(subject).to receive(:write_fork_data) allow(subject).to receive(:write_primary_branch_file) allow(subject).to receive(:`).and_return('main') end describe '#run_checkout_pull' do let(:repository_path) { instance_double(Pathname, to_s: '/tmp/repo', join: yardoc_path) } let(:yardoc_path) { instance_double(Pathname, directory?: false) } before do allow(subject).to receive(:repository_path).and_return(repository_path) end it 'escapes commit parameter in git commands' do subject.owner = owner subject.project = project subject.commit = malicious_commit expect(subject).to receive(:sh) do |cmd, _| # Verify semicolon is escaped (becomes \;) expect(cmd).to include('main\\;') # Verify the malicious part doesn't execute as a separate command expect(cmd).not_to match(/; rm/) end subject.run_checkout_pull end it 'escapes repository path in git commands' do subject.owner = owner subject.project = project subject.commit = commit expect(subject).to receive(:sh).with( a_string_including(Shellwords.escape(repository_path.to_s)), anything ) subject.run_checkout_pull end end describe '#run_checkout_clone' do let(:temp_clone_path) { instance_double(Pathname, to_s: '/tmp/clone', parent: temp_parent) } let(:temp_parent) { instance_double(Pathname, mkpath: nil) } let(:repository_path) { instance_double(Pathname, to_s: '/path/to/repo', parent: repo_parent) } let(:repo_parent) { instance_double(Pathname, mkpath: nil) } before do allow(subject).to receive(:temp_clone_path).and_return(temp_clone_path) allow(subject).to receive(:repository_path).and_return(repository_path) end it 'escapes malicious commit in branch option' do subject.owner = owner subject.project = project subject.commit = malicious_commit expect(subject).to receive(:sh) do |cmd, _| # Verify semicolon is escaped expect(cmd).to include('--branch main\\;') # Verify the rm command doesn't execute as separate command expect(cmd).not_to match(/; rm/) end allow(subject).to receive(:sh).with(a_string_matching(/rm -rf/), anything) subject.run_checkout_clone end it 'escapes URL in git clone command' do subject.owner = malicious_owner subject.project = project subject.commit = commit expected_url = "https://github.com/#{malicious_owner}/#{project}" expect(subject).to receive(:sh).with( a_string_including(Shellwords.escape(expected_url)), anything ) allow(subject).to receive(:sh).with(a_string_matching(/rm -rf/), anything) subject.run_checkout_clone end it 'escapes temp clone path in git clone command' do subject.owner = owner subject.project = project subject.commit = commit expect(subject).to receive(:sh).with( a_string_including(Shellwords.escape(temp_clone_path.to_s)), anything ) allow(subject).to receive(:sh).with(a_string_matching(/rm -rf/), anything) subject.run_checkout_clone end it 'escapes paths in git -C command for branch detection' do subject.owner = owner subject.project = project subject.commit = nil expect(subject).to receive(:`).with( a_string_including(Shellwords.escape(temp_clone_path.to_s)) ) allow(subject).to receive(:sh) subject.run_checkout_clone end it 'escapes all paths in mv command' do subject.owner = owner subject.project = project subject.commit = commit allow(subject).to receive(:sh) expect(subject).to receive(:sh).with( a_string_matching(/rm -rf #{Regexp.escape(Shellwords.escape(repository_path.to_s))}.*mv #{Regexp.escape(Shellwords.escape(temp_clone_path.to_s))} #{Regexp.escape(Shellwords.escape(repository_path.to_s))}/), anything ) subject.run_checkout_clone end it 'prevents command injection through owner name' do subject.owner = malicious_owner subject.project = project subject.commit = commit # Should not execute arbitrary commands expect(subject).to receive(:sh) do |cmd, _| # Verify the malicious content is properly escaped and won't execute expect(cmd).to include(Shellwords.escape("https://github.com/#{malicious_owner}/#{project}")) expect(cmd).not_to include("rm -rf /;") end allow(subject).to receive(:sh).with(a_string_matching(/rm -rf/), anything) subject.run_checkout_clone end it 'prevents command injection through project name' do subject.owner = owner subject.project = malicious_project subject.commit = commit expect(subject).to receive(:sh) do |cmd, _| # Verify backtick is escaped (becomes \`) expect(cmd).to include('project\\`rm') # Original URL should be escaped expect(cmd).to include(Shellwords.escape("https://github.com/#{owner}/#{malicious_project}")) end allow(subject).to receive(:sh).with(a_string_matching(/rm -rf/), anything) subject.run_checkout_clone end end describe 'commit sanitization' do it 'sanitizes dangerous commit values' do dangerous_commits = [ "; rm -rf /", "main && malicious_command", "$(evil_command)", "`evil_command`", "| evil_command", "main\nmalicious_line" ] dangerous_commits.each do |dangerous_commit| subject.commit = dangerous_commit # The commit setter should sanitize or the escaping should protect # Just verify it doesn't cause an exception expect { subject.commit }.not_to raise_error end end end describe 'path construction' do it 'safely handles paths with special characters' do subject.owner = "owner-with-special" subject.project = "project.with.dots" subject.commit = "branch/with/slashes" # Should not raise errors with special characters expect { subject.repository_path }.not_to raise_error expect { subject.temp_clone_path }.not_to raise_error expect { subject.url }.not_to raise_error end end end describe '#temp_clone_path' do it 'returns path in github_clones directory' do subject.owner = owner subject.project = project path = subject.temp_clone_path expect(path.to_s).to include('github_clones') expect(path.to_s).to include(project) expect(path.to_s).to include(owner) end it 'includes timestamp for uniqueness' do path1 = subject.temp_clone_path subject.instance_variable_set(:@temp_clone_path, nil) sleep 0.01 path2 = subject.temp_clone_path expect(path1.to_s).not_to eq(path2.to_s) end end describe '#repository_path' do it 'returns path based on GithubLibrary base path' do subject.owner = owner subject.project = project subject.commit = commit expect(subject.repository_path.to_s).to include(project) expect(subject.repository_path.to_s).to include(owner) expect(subject.repository_path.to_s).to include(commit) end end describe '#library_version' do before do subject.owner = owner subject.project = project subject.commit = commit end it 'returns a LibraryVersion object' do expect(subject.library_version).to be_a(YARD::Server::LibraryVersion) end it 'has correct name' do expect(subject.library_version.name).to eq("#{owner}/#{project}") end it 'has correct version' do expect(subject.library_version.version).to eq(commit) end it 'has github source' do expect(subject.library_version.source).to eq(:github) end end describe '#flush_cache' do it 'calls CacheClearJob with correct paths' do subject.owner = owner subject.project = project expect(CacheClearJob).to receive(:perform_now).with( '/', '/github', "/github/~#{project[0, 1]}", "/github/#{owner}/#{project}/", "/list/github/#{owner}/#{project}/", "/static/github/#{owner}/#{project}/" ) subject.flush_cache end end describe '#register_project' do let(:library_version) { double('LibraryVersion') } before do allow(subject).to receive(:library_version).and_return(library_version) end it 'calls RegisterLibrariesJob' do expect(RegisterLibrariesJob).to receive(:perform_now).with(library_version) subject.register_project end end describe '#primary_branch' do let(:primary_branch_file) { instance_double(Pathname, read: 'master') } before do allow(subject).to receive(:primary_branch_file).and_return(primary_branch_file) end it 'reads from primary branch file' do expect(primary_branch_file).to receive(:read).and_return('master') expect(subject.primary_branch).to eq('master') end context 'when file does not exist' do before do allow(primary_branch_file).to receive(:read).and_raise(Errno::ENOENT) end it 'returns nil' do expect(subject.primary_branch).to be_nil end end end describe '#write_primary_branch_file' do let(:primary_branch_file) { instance_double(Pathname, write: nil) } before do allow(subject).to receive(:primary_branch_file).and_return(primary_branch_file) subject.commit = commit end it 'writes commit to file' do expect(primary_branch_file).to receive(:write).with(commit) subject.write_primary_branch_file end end describe '#write_fork_data' do let(:fork_file) { instance_double(Pathname, file?: false, write: nil) } before do allow(subject).to receive(:fork_file).and_return(fork_file) allow(subject).to receive(:fork?).and_return(false) subject.owner = owner subject.project = project end context 'when fork file already exists' do before do allow(fork_file).to receive(:file?).and_return(true) end it 'does not write' do expect(fork_file).not_to receive(:write) subject.write_fork_data end end context 'when repository is a fork' do before do allow(subject).to receive(:fork?).and_return(true) end it 'does not write' do expect(fork_file).not_to receive(:write) subject.write_fork_data end end context 'when fork file does not exist and not a fork' do it 'writes owner/project name to file' do expect(fork_file).to receive(:write).with("#{owner}/#{project}") subject.write_fork_data end end end describe '#fork?' do before do subject.owner = owner subject.project = project end context 'when repository is a fork' do before do allow(URI).to receive(:open).and_yield(StringIO.new('{"fork": true}')) end it 'returns true' do expect(subject.fork?).to be true end it 'caches the result' do expect(URI).to receive(:open).once.and_yield(StringIO.new('{"fork": true}')) subject.fork? subject.fork? end end context 'when repository is not a fork' do before do allow(URI).to receive(:open).and_yield(StringIO.new('{"fork": false}')) end it 'returns false' do expect(subject.fork?).to be false end end context 'when API call fails' do before do allow(URI).to receive(:open).and_raise(OpenURI::HTTPError.new('404', nil)) end it 'returns false' do expect(subject.fork?).to be false end it 'sets cache to nil' do subject.fork? expect(subject.instance_variable_get(:@is_fork)).to be_nil end end context 'when network timeout occurs' do before do allow(URI).to receive(:open).and_raise(Timeout::Error) end it 'returns false' do expect(subject.fork?).to be false end end end describe 'cleanup after perform' do it 'has an after_perform callback defined' do callbacks = described_class._perform_callbacks.select { |cb| cb.kind == :after } expect(callbacks).not_to be_empty end it 'cleans up temp clone path if it exists' do temp_path = double('Pathname', directory?: true, rmtree: nil) allow_any_instance_of(described_class).to receive(:temp_clone_path).and_return(temp_path) allow_any_instance_of(described_class).to receive(:library_version).and_return(double(disallowed?: false)) allow_any_instance_of(described_class).to receive(:run_checkout).and_return(true) allow_any_instance_of(described_class).to receive(:register_project) allow_any_instance_of(described_class).to receive(:flush_cache) expect(temp_path).to receive(:directory?).and_return(true) expect(temp_path).to receive(:rmtree) described_class.perform_now(owner: owner, project: project, commit: commit) end end end
ruby
MIT
05379203c0f7e84c6f5df9bbbd384db5ff7ac532
2026-01-04T17:46:46.862481Z
false
docmeta/rubydoc.info
https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/spec/jobs/cache_clear_job_spec.rb
spec/jobs/cache_clear_job_spec.rb
require 'rails_helper' RSpec.describe CacheClearJob, type: :job do describe '#perform' do let(:paths) { [ '/docs/rails/7.0.0', '/docs/rspec/3.12.0' ] } context 'when Cloudflare token is configured' do with_rubydoc_config(integrations: { cloudflare_token: 'test_token', cloudflare_zones: [ 'zone123' ] }) do it 'clears cache from Cloudflare' do http = instance_double(Net::HTTP::Persistent) allow(Net::HTTP::Persistent).to receive(:new).and_return(http) allow(http).to receive(:request) allow(http).to receive(:shutdown) expect(http).to receive(:request) subject.perform(*paths) end it 'batches paths in groups of 30' do paths = (1..65).map { |i| "/docs/gem#{i}" } http = instance_double(Net::HTTP::Persistent) allow(Net::HTTP::Persistent).to receive(:new).and_return(http) allow(http).to receive(:request) allow(http).to receive(:shutdown) # 65 paths divided by 30 per batch = 3 batches per zone expect(http).to receive(:request).at_least(3).times subject.perform(*paths) end it 'shuts down HTTP connection' do http = instance_double(Net::HTTP::Persistent) allow(Net::HTTP::Persistent).to receive(:new).and_return(http) allow(http).to receive(:request) expect(http).to receive(:shutdown).at_least(:once) subject.perform(*paths) end end end context 'when Cloudflare token is not configured' do it 'returns early without making API calls' do allow(Rubydoc.config.integrations).to receive(:cloudflare_token).and_return(nil) expect(Net::HTTP::Persistent).not_to receive(:new) subject.perform(*paths) end end context 'with multiple zones' do with_rubydoc_config(integrations: { cloudflare_token: 'test_token', cloudflare_zones: [ 'zone1', 'zone2' ] }) do it 'clears cache for all zones' do http = instance_double(Net::HTTP::Persistent) allow(http).to receive(:request) allow(http).to receive(:shutdown) # Each zone creates an HTTP object and shuts it down # Using at_least to allow for test environment config expect(Net::HTTP::Persistent).to receive(:new).at_least(2).times.and_return(http) subject.perform(*paths) end 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/spec/system/github_spec.rb
spec/system/github_spec.rb
require 'rails_helper' RSpec.describe "Github", type: :system do with_rubydoc_config({}) do context "GET /" do before do Library.gem.delete_all create_list(:github, 10) create(:gem, name: "yard", versions: [ "1.0.0", "2.0.0", "3.0.0", "4.0.0", "5.0.0" ]) create(:github, name: "abc", owner: "xyz", versions: [ "main" ]) create(:github, name: "bcd", owner: "xyz", versions: [ "main" ]) end context "when no featured libraries are configured" do it do visit root_path expect(page).to have_selector("h2", text: "GitHub Projects Listing") expect(page).to have_no_selector("h2", text: "Featured Libraries Listing") expect(page).to have_link(text: "xyz/abc", href: yard_github_path("xyz", "abc")) expect(page).not_to have_selector(".alpha a", text: "Latest") expect(page).to have_selector(".alpha .selected", text: "Latest") expect(page).to have_selector("nav .selected", text: "GitHub") (?a.. ?z).each do |letter| expect(page).to have_selector(".alpha a", text: letter.chr.upcase) end end end context "when featured libraries are configured" do with_rubydoc_config(libraries: { featured: { yard: "gem" } }) do it do visit root_path(letter: "b") expect(page).to have_selector(".alpha .selected", text: "B") expect(page).to have_selector("h2", text: "Featured Libraries Listing") expect(page).to have_link(text: "yard", href: yard_gems_path("yard")) expect(page).to have_link(text: "4.0.0", href: yard_gems_path("yard", "4.0.0")) expect(page).to have_link(text: "3.0.0", href: yard_gems_path("yard", "3.0.0")) expect(page).to have_link(text: "2.0.0", href: yard_gems_path("yard", "2.0.0")) expect(page).to have_selector("h2", text: "GitHub Projects Listing") expect(page).to have_link(text: "xyz/bcd", href: yard_github_path("xyz", "bcd")) end end end end context "POST /+" do context "fails to add an invalid project" do it do visit root_path expect(page).to have_selector(".top-nav a", text: "Add Project") click_on "Add Project" expect(page).to have_selector("#modal form", visible: true) within("#modal form") do fill_in "GitHub URL", with: "invalid_url" click_on "Add Project" end expect(page).to have_selector("form .errors", text: "URL is invalid") end end context "fails to add invalid commit" do it do visit root_path expect(page).to have_selector(".top-nav a", text: "Add Project") click_on "Add Project" expect(page).to have_selector("#modal form", visible: true) within("#modal form") do fill_in "Commit (optional)", with: "/" click_on "Add Project" end expect(page).to have_selector("form .errors", text: "URL is invalid and commit is invalid") end end context "succeeds to add a valid project" do it do visit root_path expect(page).to have_selector(".top-nav a", text: "Add Project") click_on "Add Project" expect(page).to have_selector("#modal form", visible: true) within("#modal form") do fill_in "GitHub URL", with: "https://github.com/docmeta/rubydoc.info" click_on "Add Project" end expect(page).to have_current_path(yard_github_path("docmeta", "rubydoc.info")) end 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/spec/system/gem_spec.rb
spec/system/gem_spec.rb
require 'rails_helper' RSpec.describe "Github", type: :system do with_rubydoc_config({}) do context "GET /" do before do Library.gem.delete_all end context "when no gems are available" do it do visit gems_path expect(page).to have_selector("h2", text: "RubyGems Listing") expect(page).to have_selector("nav .selected", text: "RubyGems") expect(page).to have_selector(".alpha .selected", text: "A") (?b.. ?z).each do |letter| expect(page).to have_selector(".alpha a", text: letter.chr.upcase) end expect(page).to have_selector(".row", text: "No matches found.") end end context "when gems are available" do before do Library.gem.delete_all create(:gem, name: "yard", versions: [ "1.0.0", "2.0.0", "3.0.0", "4.0.0", "5.0.0" ]) end it do visit gems_path(letter: "y") expect(page).to have_selector(".alpha .selected", text: "Y") expect(page).to have_link(text: "yard", href: yard_gems_path("yard")) expect(page).to have_link(text: "4.0.0", href: yard_gems_path("yard", "4.0.0")) expect(page).to have_link(text: "3.0.0", href: yard_gems_path("yard", "3.0.0")) expect(page).to have_link(text: "2.0.0", href: yard_gems_path("yard", "2.0.0")) end 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/spec/helpers/shell_helper_spec.rb
spec/helpers/shell_helper_spec.rb
require 'rails_helper' RSpec.describe ShellHelper, type: :helper do describe '#sh' do context 'with successful command' do it 'executes the command and returns result' do result = helper.sh('echo "test"', raise_error: true) expect(result).to be_success end it 'logs the command and result' do expect(Rails.logger).to receive(:info).at_least(:once) helper.sh('echo "test"', raise_error: true) end it 'uses custom title if provided' do expect(Rails.logger).to receive(:info).at_least(:once).with(a_string_matching(/Custom Title/)) helper.sh('echo "test"', title: 'Custom Title', raise_error: true) end end context 'with failing command' do it 'raises IOError when raise_error is true' do expect { helper.sh('exit 1', raise_error: true) }.to raise_error(IOError, /Error executing command/) end it 'does not raise error when raise_error is false' do expect { helper.sh('exit 1', raise_error: false) }.not_to raise_error end it 'logs error details' do expect(Rails.logger).to receive(:error).with(a_string_matching(/STDERR/)) expect { helper.sh('exit 1', raise_error: true) }.to raise_error(IOError) end end context 'with show_output option' do it 'prints output when show_output is true' do expect { helper.sh('echo "visible"', show_output: true, raise_error: true) }.to output(/visible/).to_stdout end end context 'command output capture' do it 'captures stdout and stderr' do expect { helper.sh('echo "stdout"; echo "stderr" >&2', raise_error: true) }.not_to raise_error 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/spec/helpers/application_helper_spec.rb
spec/helpers/application_helper_spec.rb
require 'rails_helper' RSpec.describe ApplicationHelper, type: :helper do describe 'constants' do it 'defines LIBRARY_TYPES' do expect(ApplicationHelper::LIBRARY_TYPES).to be_a(Hash) expect(ApplicationHelper::LIBRARY_TYPES[:featured]).to eq("Gem") expect(ApplicationHelper::LIBRARY_TYPES[:stdlib]).to eq("Standard Library") expect(ApplicationHelper::LIBRARY_TYPES[:gems]).to eq("Gem") expect(ApplicationHelper::LIBRARY_TYPES[:github]).to eq("GitHub repository") end it 'defines LIBRARY_ALT_TYPES' do expect(ApplicationHelper::LIBRARY_ALT_TYPES).to be_a(Hash) expect(ApplicationHelper::LIBRARY_ALT_TYPES[:github]).to eq("GitHub Project") end it 'defines HAS_SEARCH' do expect(ApplicationHelper::HAS_SEARCH).to be_a(Set) expect(ApplicationHelper::HAS_SEARCH).to include('github', 'gems') end end describe '#nav_links' do it 'returns navigation links hash' do links = helper.nav_links expect(links).to be_a(Hash) expect(links.keys).to include("Featured", "Stdlib", "RubyGems", "GitHub") end it 'includes correct paths' do links = helper.nav_links expect(links["Featured"]).to eq(featured_index_path) expect(links["Stdlib"]).to eq(stdlib_index_path) expect(links["RubyGems"]).to eq(gems_path) expect(links["GitHub"]).to eq(github_index_path) end end describe '#settings' do it 'returns Rubydoc config' do expect(helper.settings).to eq(Rubydoc.config) end end describe '#page_title' do it 'combines settings name and title content' do allow(Rubydoc.config).to receive(:name).and_return('RubyDoc.info') assign(:page_title, 'Test Page') expect(helper.page_title).to eq('RubyDoc.info: Test Page') end end describe '#title_content' do it 'returns page_title instance variable if set' do assign(:page_title, 'Custom Title') expect(helper.title_content).to eq('Custom Title') end it 'falls back to page_description' do assign(:page_description, 'Custom Description') expect(helper.title_content).to eq('Custom Description') end end describe '#page_description' do it 'returns page_description instance variable if set' do assign(:page_description, 'Custom Description') expect(helper.page_description).to eq('Custom Description') end it 'falls back to settings description' do allow(Rubydoc.config).to receive(:description).and_return('Default Description') expect(helper.page_description).to eq('Default Description') end end describe '#link_to_library' do let(:gem_library) { create(:gem, name: 'rails') } let(:github_library) { create(:github, name: 'rails', owner: 'rails') } it 'creates link for gem library' do link = helper.link_to_library(gem_library) expect(link).to include('href="#/gems/rails"') expect(link).to include('rails') end it 'creates link with version' do link = helper.link_to_library(gem_library, '7.0.0') expect(link).to include('href="#/gems/rails/7.0.0"') expect(link).to include('7.0.0') end it 'creates link for github library' do link = helper.link_to_library(github_library) expect(link).to include('href="#/github/rails/rails"') end it 'creates link for featured library' do featured_library = create(:featured, name: 'yard') link = helper.link_to_library(featured_library) expect(link).to include('href="#/docs/yard"') end end describe '#library_name' do it 'returns name param if present' do allow(helper).to receive(:params).and_return({ name: 'rails' }) expect(helper.library_name).to eq('rails') end it 'joins username and project params' do allow(helper).to receive(:params).and_return({ username: 'rails', project: 'rails' }) expect(helper.library_name).to eq('rails/rails') end end describe '#library_type' do it 'returns library type for action' do allow(helper).to receive(:action_name).and_return('github') expect(helper.library_type).to eq("GitHub repository") end end describe '#library_type_alt' do it 'returns alternative library type for action' do allow(helper).to receive(:action_name).and_return('github') expect(helper.library_type_alt).to eq("GitHub Project") end end describe '#has_search?' do it 'returns true for github controller' do allow(helper).to receive(:controller_name).and_return('github') expect(helper.has_search?).to be true end it 'returns true for gems controller' do allow(helper).to receive(:controller_name).and_return('gems') expect(helper.has_search?).to be true end it 'returns false for other controllers' do allow(helper).to receive(:controller_name).and_return('stdlib') expect(helper.has_search?).to be false end end describe '#sorted_versions' do it 'returns sorted versions' do library = create(:gem, name: 'rails', versions: [ '7.0.0', '6.1.0', '5.2.0' ]) versions = helper.sorted_versions(library) expect(versions).to eq([ '7.0.0', '6.1.0', '5.2.0' ]) end end describe '#has_featured?' do context 'when featured libraries are configured' do with_rubydoc_config(libraries: { featured: { rails: 'gem' } }) do it 'returns true' do expect(helper.has_featured?).to be true end end end context 'when no featured libraries are configured' do with_rubydoc_config(libraries: { featured: {} }) do it 'returns false' do expect(helper.has_featured?).to be false end end end end describe '#featured_libraries' do context 'when no featured libraries configured' do with_rubydoc_config(libraries: { featured: {} }) do it 'returns empty array' do expect(helper.featured_libraries).to eq([]) end end end context 'when featured gems are configured' do with_rubydoc_config(libraries: { featured: { rails: 'gem', rspec: 'gem' } }) do before do create(:gem, name: 'rails', versions: [ '7.0.0' ]) create(:gem, name: 'rspec', versions: [ '3.12.0' ]) end it 'returns featured gem libraries' do libraries = helper.featured_libraries expect(libraries.size).to eq(2) expect(libraries.map(&:name)).to contain_exactly('rails', 'rspec') end it 'loads libraries in batch to avoid N+1' do expect(Library).to receive(:gem).once.and_call_original helper.featured_libraries end 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/spec/factories/libraries.rb
spec/factories/libraries.rb
FactoryBot.define do factory :library do name { Faker::Internet.unique.username } versions { Faker::Number.between(from: 1, to: 10).to_i.times.map { Faker::Number.number(digits: 3).to_s.split("").join(".") } } factory :gem do source { :remote_gem } end factory :github do source { :github } owner { Faker::Internet.unique.username } versions { Faker::Number.between(from: 1, to: 10).to_i.times.map { Faker::Internet.unique.username } } end factory :stdlib do source { :stdlib } end factory :featured do source { :featured } end end end
ruby
MIT
05379203c0f7e84c6f5df9bbbd384db5ff7ac532
2026-01-04T17:46:46.862481Z
false
docmeta/rubydoc.info
https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/spec/controllers/github_controller_spec.rb
spec/controllers/github_controller_spec.rb
require 'rails_helper' RSpec.describe GithubController, type: :controller do describe "GET #index" do before do create(:github, name: 'rails', owner: 'rails', versions: [ 'main' ]) create(:github, name: 'ruby', owner: 'ruby', versions: [ 'master' ]) end it "returns a successful response" do get :index expect(response).to be_successful end it "sets the title" do get :index expect(assigns(:title)).to eq("GitHub Projects") end it "loads allowed github projects" do get :index expect(assigns(:collection).count).to eq(2) end context "with letter filter" do it "filters by letter" do get :index, params: { letter: 'r' } expect(response).to be_successful end end context "without letter filter" do it "shows latest 10 projects" do get :index expect(response).to be_successful end end end describe "GET #add_project" do it "returns a successful response" do get :add_project expect(response).to be_successful end it "initializes a new project" do get :add_project expect(assigns(:project)).to be_a(GithubProject) expect(assigns(:project).url).to be_nil end it "uses modal layout" do get :add_project expect(response).to render_template(layout: 'modal') end end describe "POST #create" do let(:valid_params) do { github_project: { url: 'https://github.com/rails/rails', commit: '' } } end let(:invalid_params) do { github_project: { url: 'invalid-url', commit: '' } } end context "with valid parameters" do it "creates a github checkout job" do expect(GithubCheckoutJob).to receive(:perform_now) .with(owner: 'rails', project: 'rails', commit: '') post :create, params: valid_params end it "redirects to the yard path" do allow(GithubCheckoutJob).to receive(:perform_now) post :create, params: valid_params expect(response).to redirect_to(yard_github_path('rails', 'rails', '')) end end context "with invalid parameters" do it "renders add_project template" do post :create, params: invalid_params expect(response).to render_template(:add_project) end it "sets errors on the project" do post :create, params: invalid_params expect(assigns(:project).errors).to be_present end end context "when IOError is raised" do it "adds error and renders add_project" do allow(GithubCheckoutJob).to receive(:perform_now).and_raise(IOError, "Network error") post :create, params: valid_params expect(response).to render_template(:add_project) expect(assigns(:project).errors[:url]).to include("could not be cloned. Please check the URL and try again.") end end context "when DisallowedCheckoutError is raised" do it "adds error and renders add_project" do allow(GithubCheckoutJob).to receive(:perform_now).and_raise(DisallowedCheckoutError.new(owner: 'rails', project: 'rails')) post :create, params: valid_params expect(response).to render_template(:add_project) expect(assigns(:project).errors[:url]).to include("is not allowed. Please check the URL and try again.") 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/spec/controllers/stdlib_controller_spec.rb
spec/controllers/stdlib_controller_spec.rb
require 'rails_helper' RSpec.describe StdlibController, type: :controller do describe "GET #index" do before do create(:stdlib, name: 'json', versions: [ '2.6.0' ]) create(:stdlib, name: 'csv', versions: [ '3.2.0' ]) end it "returns a successful response" do get :index expect(response).to be_successful end it "sets the title" do get :index expect(assigns(:title)).to eq("Ruby Standard Library") expect(assigns(:page_title)).to eq("Ruby Standard Library") end it "loads stdlib libraries" do get :index expect(assigns(:collection).count).to eq(2) end it "renders the library_list template" do get :index expect(response).to render_template("shared/library_list") end end end
ruby
MIT
05379203c0f7e84c6f5df9bbbd384db5ff7ac532
2026-01-04T17:46:46.862481Z
false
docmeta/rubydoc.info
https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/spec/controllers/gems_controller_spec.rb
spec/controllers/gems_controller_spec.rb
require 'rails_helper' RSpec.describe GemsController, type: :controller do describe "GET #index" do before do create(:gem, name: 'activerecord', versions: [ '7.0.0' ]) create(:gem, name: 'actionpack', versions: [ '3.12.0' ]) end it "returns a successful response" do get :index expect(response).to be_successful end it "sets the title" do get :index expect(assigns(:title)).to eq("RubyGems") end it "loads allowed gems" do get :index expect(assigns(:collection).to_a.count).to eq(2) end context "with letter filter" do it "filters by letter" do get :index, params: { letter: 'r' } expect(response).to be_successful expect(assigns(:letter)).to eq('r') end end context "with pagination" do before do 30.times { |i| create(:gem, name: "gem#{i}") } end it "paginates results" do get :index, params: { page: 2 } expect(response).to be_successful 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/spec/models/library_spec.rb
spec/models/library_spec.rb
require 'rails_helper' RSpec.describe Library, type: :model do describe 'enums' do it 'defines source enum' do expect(Library.sources).to eq('remote_gem' => 'remote_gem', 'github' => 'github', 'stdlib' => 'stdlib', 'featured' => 'featured') end end describe 'scopes' do before do @gem1 = create(:gem, name: 'activerecord') @gem2 = create(:gem, name: 'rails') @github1 = create(:github, name: 'rails', owner: 'rails') @stdlib1 = create(:stdlib, name: 'json') end describe '.gem' do it 'returns only gems' do expect(Library.gem).to contain_exactly(@gem1, @gem2) end end describe '.github' do it 'returns only github libraries' do expect(Library.github).to contain_exactly(@github1) end end describe '.stdlib' do it 'returns only stdlib libraries' do expect(Library.stdlib).to contain_exactly(@stdlib1) end end describe '.allowed_gem' do context 'when no disallowed gems configured' do it 'returns all gems' do expect(Library.allowed_gem).to contain_exactly(@gem1, @gem2) end end context 'when disallowed gems are configured' do with_rubydoc_config(libraries: { disallowed_gems: [ 'rails*' ] }) do it 'excludes disallowed gems' do expect(Library.allowed_gem).to contain_exactly(@gem1) end end end end describe '.allowed_github' do context 'when no disallowed projects configured' do it 'returns all github projects' do expect(Library.allowed_github).to contain_exactly(@github1) end end context 'when disallowed projects are configured' do with_rubydoc_config(libraries: { disallowed_projects: [ 'rails/*' ] }) do it 'excludes disallowed projects' do expect(Library.allowed_github).to be_empty end end end end end describe '.wildcard' do it 'converts asterisks to SQL wildcards' do expect(Library.wildcard([ 'rails*', '*gem*' ])).to eq([ 'rails%', '%gem%' ]) end end describe '#name' do context 'for github source' do it 'returns owner/name format' do library = create(:github, name: 'rails', owner: 'rails') expect(library.name).to eq('rails/rails') end end context 'for non-github source' do it 'returns the name' do library = create(:gem, name: 'rails') expect(library.name).to eq('rails') end end end describe '#project' do it 'returns the name attribute' do library = create(:github, name: 'rails', owner: 'rails') expect(library.project).to eq('rails') end end describe '#source' do it 'returns source as a symbol' do library = create(:gem) expect(library.source).to eq(:remote_gem) expect(library.source).to be_a(Symbol) end end describe '#library_versions' do context 'for gem library' do it 'returns library versions' do library = create(:gem, name: 'rails', versions: [ '7.0.0', '6.1.0', '5.2.0' ]) versions = library.library_versions expect(versions.size).to eq(3) expect(versions.first).to be_a(YARD::Server::LibraryVersion) expect(versions.map(&:version)).to eq([ '7.0.0', '6.1.0', '5.2.0' ]) end end context 'for github library' do it 'returns library versions' do library = create(:github, name: 'rails', owner: 'rails', versions: [ 'main', 'develop' ]) versions = library.library_versions expect(versions.size).to eq(2) expect(versions.first).to be_a(YARD::Server::LibraryVersion) end end it 'caches the result' do library = create(:gem, name: 'rails', versions: [ '7.0.0' ]) first_call = library.library_versions second_call = library.library_versions expect(first_call.object_id).to eq(second_call.object_id) end end end
ruby
MIT
05379203c0f7e84c6f5df9bbbd384db5ff7ac532
2026-01-04T17:46:46.862481Z
false
docmeta/rubydoc.info
https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/spec/models/github_project_spec.rb
spec/models/github_project_spec.rb
require 'rails_helper' RSpec.describe GithubProject, type: :model do describe 'validations' do it 'validates url format' do project = GithubProject.new(url: 'https://github.com/rails/rails') expect(project).to be_valid project.url = 'https://example.com/rails/rails' expect(project).not_to be_valid expect(project.errors[:url]).to be_present project.url = 'not a url' expect(project).not_to be_valid end it 'accepts valid GitHub URLs' do valid_urls = [ 'https://github.com/rails/rails', 'https://github.com/ruby/ruby', 'https://github.com/user-name/repo.name', 'https://github.com/user_name/repo_name', 'https://github.com/123/456' ] valid_urls.each do |url| project = GithubProject.new(url: url) expect(project).to be_valid, "Expected #{url} to be valid" end end it 'validates commit format' do project = GithubProject.new(url: 'https://github.com/rails/rails', commit: 'abc123') expect(project).to be_valid project.commit = '1234567890abcdef' expect(project).to be_valid project.commit = '' expect(project).to be_valid project.commit = 'invalid commit!' expect(project).not_to be_valid expect(project.errors[:commit]).to be_present end it 'allows blank commit' do project = GithubProject.new(url: 'https://github.com/rails/rails') expect(project).to be_valid end end describe '#owner' do it 'extracts owner from URL' do project = GithubProject.new(url: 'https://github.com/rails/rails') expect(project.owner).to eq('rails') end end describe '#name' do it 'extracts name from URL' do project = GithubProject.new(url: 'https://github.com/rails/rails') expect(project.name).to eq('rails') end end describe '#path' do it 'returns path components as array' do project = GithubProject.new(url: 'https://github.com/rails/rails') expect(project.path).to eq([ 'rails', 'rails' ]) end it 'handles different URL formats' do project = GithubProject.new(url: 'https://github.com/ruby/ruby') expect(project.path).to eq([ 'ruby', 'ruby' ]) end end end
ruby
MIT
05379203c0f7e84c6f5df9bbbd384db5ff7ac532
2026-01-04T17:46:46.862481Z
false
docmeta/rubydoc.info
https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/lib/yard/templates/default/method/setup.rb
lib/yard/templates/default/method/setup.rb
def init super return unless defined? Rubydoc.config.disqus sections.push :disqus end
ruby
MIT
05379203c0f7e84c6f5df9bbbd384db5ff7ac532
2026-01-04T17:46:46.862481Z
false
docmeta/rubydoc.info
https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/lib/yard/templates/default/layout/html/setup.rb
lib/yard/templates/default/layout/html/setup.rb
def javascripts super + %w[js/rubydoc_custom.js] end
ruby
MIT
05379203c0f7e84c6f5df9bbbd384db5ff7ac532
2026-01-04T17:46:46.862481Z
false
docmeta/rubydoc.info
https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/config/application.rb
config/application.rb
require_relative "boot" require "rails" # Pick the frameworks you want: require "active_model/railtie" require "active_job/railtie" require "active_record/railtie" # require "active_storage/engine" require "action_controller/railtie" # require "action_mailer/railtie" # require "action_mailbox/engine" # require "action_text/engine" require "action_view/railtie" require "action_cable/engine" require "rails/test_unit/railtie" # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module Rubydoc class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 8.0 # Please, add to the `ignore` list any other `lib` subdirectories that do # not contain `.rb` files, or that should not be reloaded or eager loaded. # Common ones are `templates`, `generators`, or `middleware`, for example. config.autoload_lib(ignore: %w[assets tasks yard/templates]) config.autoload_once_paths << "#{root}/app/serializers" # Configuration for the application, engines, and railties goes here. # # These settings can be overridden in specific environments using the files # in config/environments, which are processed later. # # config.time_zone = "Central Time (US & Canada)" # config.eager_load_paths << Rails.root.join("extras") config.session_store :disabled config.exceptions_app = routes end end
ruby
MIT
05379203c0f7e84c6f5df9bbbd384db5ff7ac532
2026-01-04T17:46:46.862481Z
false
docmeta/rubydoc.info
https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/config/environment.rb
config/environment.rb
# Load the Rails application. require_relative "application" # Initialize the Rails application. Rails.application.initialize!
ruby
MIT
05379203c0f7e84c6f5df9bbbd384db5ff7ac532
2026-01-04T17:46:46.862481Z
false
docmeta/rubydoc.info
https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/config/puma.rb
config/puma.rb
# This configuration file will be evaluated by Puma. The top-level methods that # are invoked here are part of Puma's configuration DSL. For more information # about methods provided by the DSL, see https://puma.io/puma/Puma/DSL.html. # # Puma starts a configurable number of processes (workers) and each process # serves each request in a thread from an internal thread pool. # # You can control the number of workers using ENV["WEB_CONCURRENCY"]. You # should only set this value when you want to run 2 or more workers. The # default is already 1. # # The ideal number of threads per worker depends both on how much time the # application spends waiting for IO operations and on how much you wish to # prioritize throughput over latency. # # As a rule of thumb, increasing the number of threads will increase how much # traffic a given process can handle (throughput), but due to CRuby's # Global VM Lock (GVL) it has diminishing returns and will degrade the # response time (latency) of the application. # # The default is set to 3 threads as it's deemed a decent compromise between # throughput and latency for the average Rails application. # # Any libraries that use a connection pool or another resource pool should # be configured to provide at least as many connections as the number of # threads. This includes Active Record's `pool` parameter in `database.yml`. threads_count = ENV.fetch("RAILS_MAX_THREADS", 3) threads threads_count, threads_count # Specifies the `port` that Puma will listen on to receive requests; default is 3000. port ENV.fetch("PORT", 3000) # Allow puma to be restarted by `bin/rails restart` command. plugin :tmp_restart # Specify the PID file. Defaults to tmp/pids/server.pid in development. # In other environments, only set the PID file if requested. pidfile ENV["PIDFILE"] if ENV["PIDFILE"] plugin :solid_queue unless ENV["RAILS_ENV"] == "production"
ruby
MIT
05379203c0f7e84c6f5df9bbbd384db5ff7ac532
2026-01-04T17:46:46.862481Z
false
docmeta/rubydoc.info
https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/config/routes.rb
config/routes.rb
Rails.application.routes.draw do # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html # Reveal health status on /up that returns 200 if the app boots with no exceptions, otherwise 500. # Can be used by load balancers and uptime monitors to verify that the app is live. get "healthcheck" => "rails/health#show", as: :rails_health_check # Render dynamic PWA files from app/views/pwa/* (remember to link manifest in application.html.erb) # get "manifest" => "rails/pwa#manifest", as: :pwa_manifest # get "service-worker" => "rails/pwa#service_worker", as: :pwa_service_worker # Defines the root path route ("/") # root "posts#index" root "github#index" match "/:code", to: "errors#show", via: :all, constraints: ErrorsController.constraints get "/about", to: "about#index", as: :about get "/help", to: "help#index", as: :help get "/docs", to: redirect("/featured", status: 302) resources :stdlib, only: [ :index ] if Rubydoc.config.github_hosting.enabled post "/checkout", to: "github_webhook#create" post "/checkout/github", to: "github_webhook#create" post "/projects/update", to: "github_webhook#update" get "/github/+", to: "github#add_project", as: :add_github_project post "/github/+", to: "github#create", as: :create_github_project resources :github, only: [ :index ] do get "~:letter(/:page)", on: :collection, action: :index, as: :letter end end if Rubydoc.config.gem_hosting.enabled post "/checkout/rubygems", to: "rubygems_webhook#create" resources :featured, only: [ :index ] resources :gems, only: [ :index ] do get "~:letter(/:page)", on: :collection, action: :index, as: :letter end end %W[#{} search/ list/ static/].each do |prefix| get "#{prefix}docs/:name(/*rest)", to: "yard#featured", as: prefix.blank? ? "yard_featured" : nil, format: false get "#{prefix}stdlib/:name(/*rest)", to: "yard#stdlib", as: prefix.blank? ? "yard_stdlib" : nil, format: false get "#{prefix}gems/:name(/*rest)", to: "yard#gems", as: prefix.blank? ? "yard_gems" : nil, format: false get "#{prefix}github/:username/:project(/*rest(.:format))", to: "yard#github", as: prefix.blank? ? "yard_github" : nil, constraints: { username: /[a-z0-9_\.-]+/i, project: /[a-z0-9_\.-]+/i }, format: false end get "/js/*rest", to: redirect("/assets/js/%{rest}", status: 302), format: false get "/css/*rest", to: redirect("/assets/css/%{rest}", status: 302), format: false get "/images/*rest", to: redirect("/assets/images/%{rest}", status: 302), format: false mount MissionControl::Jobs::Engine, at: "/jobs" end
ruby
MIT
05379203c0f7e84c6f5df9bbbd384db5ff7ac532
2026-01-04T17:46:46.862481Z
false
docmeta/rubydoc.info
https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/config/importmap.rb
config/importmap.rb
# Pin npm packages by running ./bin/importmap pin "application" pin "yard" pin "@hotwired/turbo-rails", to: "turbo.min.js" pin "@hotwired/stimulus", to: "stimulus.min.js" pin "@hotwired/stimulus-loading", to: "stimulus-loading.js" pin_all_from "app/javascript/controllers", under: "controllers"
ruby
MIT
05379203c0f7e84c6f5df9bbbd384db5ff7ac532
2026-01-04T17:46:46.862481Z
false
docmeta/rubydoc.info
https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/config/boot.rb
config/boot.rb
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) require "bundler/setup" # Set up gems listed in the Gemfile. require "bootsnap/setup" # Speed up boot time by caching expensive operations.
ruby
MIT
05379203c0f7e84c6f5df9bbbd384db5ff7ac532
2026-01-04T17:46:46.862481Z
false
docmeta/rubydoc.info
https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/config/initializers/content_security_policy.rb
config/initializers/content_security_policy.rb
# Be sure to restart your server when you modify this file. # Define an application-wide content security policy. # See the Securing Rails Applications Guide for more information: # https://guides.rubyonrails.org/security.html#content-security-policy-header # Rails.application.configure do # config.content_security_policy do |policy| # policy.default_src :self, :https # policy.font_src :self, :https, :data # policy.img_src :self, :https, :data # policy.object_src :none # policy.script_src :self, :https # policy.style_src :self, :https # # Specify URI for violation reports # # policy.report_uri "/csp-violation-report-endpoint" # end # # # Generate session nonces for permitted importmap, inline scripts, and inline styles. # config.content_security_policy_nonce_generator = ->(request) { request.session.id.to_s } # config.content_security_policy_nonce_directives = %w(script-src style-src) # # # Report violations without enforcing the policy. # # config.content_security_policy_report_only = true # end
ruby
MIT
05379203c0f7e84c6f5df9bbbd384db5ff7ac532
2026-01-04T17:46:46.862481Z
false
docmeta/rubydoc.info
https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/config/initializers/filter_parameter_logging.rb
config/initializers/filter_parameter_logging.rb
# Be sure to restart your server when you modify this file. # Configure parameters to be partially matched (e.g. passw matches password) and filtered from the log file. # Use this to limit dissemination of sensitive information. # See the ActiveSupport::ParameterFilter documentation for supported notations and behaviors. Rails.application.config.filter_parameters += [ :passw, :email, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn, :cvv, :cvc ]
ruby
MIT
05379203c0f7e84c6f5df9bbbd384db5ff7ac532
2026-01-04T17:46:46.862481Z
false
docmeta/rubydoc.info
https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/config/initializers/rubydoc.rb
config/initializers/rubydoc.rb
# Configuration module Rubydoc def self.config; @config; end def self.config=(config) @config = JSON.parse({ name: "RubyDoc.info", description: "Documenting RubyGems, Stdlib, and GitHub Projects", integrations: { rubygems: Rails.application.credentials.rubydoc&.rubygems_api_key, cloudflare_token: Rails.application.credentials.rubydoc&.cloudflare_token, cloudflare_zones: Rails.application.credentials.rubydoc&.cloudflare_zones }, gem_hosting: { source: "https://rubygems.org", enabled: true }, github_hosting: { enabled: true }, libraries: { featured: {}, disallowed_projects: [], disallowed_gems: [], whitelisted_projects: [], whitelisted_gems: [] }, sponsors: {} }.deeper_merge(config).to_json, object_class: ActiveSupport::OrderedOptions) end Rails.application.config.after_initialize do begin Rubydoc.config = Rails.application.config_for(:rubydoc) rescue RuntimeError Rails.logger.warn("Failed to load RubyDoc configuration. Using default values.") Rubydoc.config = {} end end def self.storage_path Rails.env.test? ? Rails.root.join("tmp", "storage", "test") : Rails.root.join("storage") end end # Serializers Rails.application.config.active_job.custom_serializers << LibraryVersionSerializer # Load YARD and copy templates to storage YARD::Server::Adapter.setup YARD::Templates::Engine.register_template_path(Rails.root.join("lib", "yard", "templates")) # Static files Rails.application.config.after_initialize do YARDCopyAssetsJob.perform_now if Rails.env.development? end # Extensions Rails.application.config.to_prepare do module YARD module Server class LibraryVersion include DisallowedLibrary include GemLibrary include GithubLibrary include StdlibLibrary include FeaturedLibrary attr_accessor :platform def source_yardoc_file File.join(source_path, Registry::DEFAULT_YARDOC_FILE) end end end module CLI class 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 def support_rdoc_document_file!(file = ".document") IO.read(File.join(File.dirname(options_file), file)).gsub(/^[ \t]*#.+/m, "").split(/\s+/) rescue Errno::ENOENT [] end def add_extra_files(*files) files.map! { |f| f.include?("*") ? Dir.glob(File.join(File.dirname(options_file), f)) : f }.flatten! files.each do |file| file = File.join(File.dirname(options_file), file) unless file[0] == "/" if File.file?(file) fname = file.gsub(File.dirname(options_file) + "/", "") options[:files] << CodeObjects::ExtraFileObject.new(fname) end end end end end class Verifier def call(object) return true if object.is_a?(CodeObjects::Proxy) @object = object __execute ? true : false rescue NoMethodError modify_nilclass @object = object retval = __execute ? true : false unmodify_nilclass retval end end end end YARD::I18n::Locale.default = nil
ruby
MIT
05379203c0f7e84c6f5df9bbbd384db5ff7ac532
2026-01-04T17:46:46.862481Z
false
docmeta/rubydoc.info
https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/config/initializers/skylight.rb
config/initializers/skylight.rb
require "skylight" if Rails.application.credentials.rubydoc&.skylight_token Rails.application.config.skylight.logger = ActiveSupport::Logger.new(STDOUT) Rails.application.config.skylight.environments << "development" Rails.application.config.skylight.probes << "active_job" view_paths = Rails.application.config.paths["app/views"] view_paths = view_paths.respond_to?(:existent) ? view_paths.existent : view_paths.select { |f| File.exist?(f) } config = { authentication: Rails.application.credentials.rubydoc&.skylight_token, logger: Rails.application.config.skylight.logger, environments: Rails.application.config.skylight.environments, env: Rails.env.to_s, root: Rails.root, "daemon.sockdir_path": Rails.application.config.paths["tmp"].first, "normalizers.render.view_paths": view_paths + [ Rails.root.to_s ], log_level: Rails.application.config.log_level, deploy: { git_sha: Rails.env.development? ? `git rev-parse HEAD`.strip : ENV["GIT_SHA"] } } Skylight.start!(config) Rails.application.middleware.insert(0, Skylight::Middleware, config: config) Rails.logger.info "[Skylight] started with config" end
ruby
MIT
05379203c0f7e84c6f5df9bbbd384db5ff7ac532
2026-01-04T17:46:46.862481Z
false
docmeta/rubydoc.info
https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/config/initializers/mini_profiler.rb
config/initializers/mini_profiler.rb
if defined? Rack::MiniProfiler Rack::MiniProfiler.config.position = "bottom-right" end
ruby
MIT
05379203c0f7e84c6f5df9bbbd384db5ff7ac532
2026-01-04T17:46:46.862481Z
false
docmeta/rubydoc.info
https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/config/initializers/queue_jobs.rb
config/initializers/queue_jobs.rb
SolidQueue.on_start do UpdateRemoteGemsListJob.clear_lock_file # Queue a few jobs on start [ UpdateRemoteGemsListJob, RegisterLibrariesJob, ReapGenerateDocsJob ].each do |job_class| if SolidQueue::Job.where(class_name: job_class.name, finished_at: nil).none? Rails.logger.info "[initializer/queue_jobs] Queueing #{job_class.name} job on start..." job_class.perform_later end end end
ruby
MIT
05379203c0f7e84c6f5df9bbbd384db5ff7ac532
2026-01-04T17:46:46.862481Z
false
docmeta/rubydoc.info
https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/config/initializers/inflections.rb
config/initializers/inflections.rb
# Be sure to restart your server when you modify this file. # Add new inflection rules using the following format. Inflections # are locale specific, and you may define rules for as many different # locales as you wish. All of these examples are active by default: # ActiveSupport::Inflector.inflections(:en) do |inflect| # inflect.plural /^(ox)$/i, "\\1en" # inflect.singular /^(ox)en/i, "\\1" # inflect.irregular "person", "people" # inflect.uncountable %w( fish sheep ) # end # These inflection rules are supported but not enabled by default: # ActiveSupport::Inflector.inflections(:en) do |inflect| # inflect.acronym "RESTful" # end # ActiveSupport::Inflector.inflections(:en) do |inflect| inflect.acronym "YARD" inflect.acronym "URL" end
ruby
MIT
05379203c0f7e84c6f5df9bbbd384db5ff7ac532
2026-01-04T17:46:46.862481Z
false
docmeta/rubydoc.info
https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/config/initializers/assets.rb
config/initializers/assets.rb
# Be sure to restart your server when you modify this file. # Version of your assets, change this if you want to expire all your assets. Rails.application.config.assets.version = "1.0" # Add additional assets to the asset load path. # Rails.application.config.assets.paths << Emoji.images_path
ruby
MIT
05379203c0f7e84c6f5df9bbbd384db5ff7ac532
2026-01-04T17:46:46.862481Z
false
docmeta/rubydoc.info
https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/config/environments/test.rb
config/environments/test.rb
# The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # While tests run files are not watched, reloading is not necessary. config.enable_reloading = false # Eager loading loads your entire application. When running a single test locally, # this is usually not necessary, and can slow down your test suite. However, it's # recommended that you enable it in continuous integration systems to ensure eager # loading is working properly before deploying your code. config.eager_load = ENV["CI"].present? # Configure public file server for tests with cache-control for performance. config.public_file_server.headers = { "cache-control" => "public, max-age=3600" } # Show full error reports. config.consider_all_requests_local = true config.cache_store = :null_store # Render exception templates for rescuable exceptions and raise for other exceptions. config.action_dispatch.show_exceptions = :rescuable # Disable request forgery protection in test environment. config.action_controller.allow_forgery_protection = false # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the # ActionMailer::Base.deliveries array. # config.action_mailer.delivery_method = :test # Set host to be used by links generated in mailer templates. # config.action_mailer.default_url_options = { host: "example.com" } # Print deprecation notices to the stderr. config.active_support.deprecation = :stderr # Raises error for missing translations. # config.i18n.raise_on_missing_translations = true # Annotate rendered view with file names. # config.action_view.annotate_rendered_view_with_filenames = true # Raise error when a before_action's only/except options reference missing actions. config.action_controller.raise_on_missing_callback_actions = true end
ruby
MIT
05379203c0f7e84c6f5df9bbbd384db5ff7ac532
2026-01-04T17:46:46.862481Z
false
docmeta/rubydoc.info
https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/config/environments/development.rb
config/environments/development.rb
require "active_support/core_ext/integer/time" Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Make code changes take effect immediately without server restart. config.enable_reloading = true # Do not eager load code on boot. config.eager_load = false # Show full error reports. config.consider_all_requests_local = true # Enable server timing. config.server_timing = true # Enable/disable Action Controller caching. By default Action Controller caching is disabled. # Run rails dev:cache to toggle Action Controller caching. if Rails.root.join("tmp/caching-dev.txt").exist? config.action_controller.perform_caching = true config.action_controller.enable_fragment_cache_logging = true config.public_file_server.headers = { "cache-control" => "public, max-age=#{2.days.to_i}" } else config.action_controller.perform_caching = false end # Change to :null_store to avoid any caching. config.cache_store = :solid_cache_store # Don't care if the mailer can't send. # config.action_mailer.raise_delivery_errors = false # Make template changes take effect immediately. # config.action_mailer.perform_caching = false # Set localhost to be used by links generated in mailer templates. # config.action_mailer.default_url_options = { host: "localhost", port: 3000 } # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Highlight code that triggered database queries in logs. config.active_record.verbose_query_logs = true # Append comments with runtime information tags to SQL queries in logs. config.active_record.query_log_tags_enabled = true # Highlight code that enqueued background job in logs. config.active_job.verbose_enqueue_logs = true # Raises error for missing translations. # config.i18n.raise_on_missing_translations = true # Annotate rendered view with file names. config.action_view.annotate_rendered_view_with_filenames = true # Use Solid Queue in Development. config.active_job.queue_adapter = :solid_queue config.solid_queue.logger = ActiveSupport::Logger.new(STDOUT) config.mission_control.jobs.http_basic_auth_enabled = false # Uncomment if you wish to allow Action Cable access from any origin. # config.action_cable.disable_request_forgery_protection = true # Raise error when a before_action's only/except options reference missing actions. config.action_controller.raise_on_missing_callback_actions = true # Apply autocorrection by RuboCop to files generated by `bin/rails generate`. # config.generators.apply_rubocop_autocorrect_after_generate! end
ruby
MIT
05379203c0f7e84c6f5df9bbbd384db5ff7ac532
2026-01-04T17:46:46.862481Z
false
docmeta/rubydoc.info
https://github.com/docmeta/rubydoc.info/blob/05379203c0f7e84c6f5df9bbbd384db5ff7ac532/config/environments/production.rb
config/environments/production.rb
require "active_support/core_ext/integer/time" Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.enable_reloading = false # Eager load code on boot for better performance and memory savings (ignored by Rake tasks). config.eager_load = true # Full error reports are disabled. config.consider_all_requests_local = false # Turn on fragment caching in view templates. config.action_controller.perform_caching = true # Cache assets for far-future expiry since they are all digest stamped. config.public_file_server.headers = { "cache-control" => "public, max-age=#{1.year.to_i}" } # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.asset_host = "http://assets.example.com" # Assume all access to the app is happening through a SSL-terminating reverse proxy. config.assume_ssl = true # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. config.force_ssl = true # Skip http-to-https redirect for the default health check endpoint. # config.ssl_options = { redirect: { exclude: ->(request) { request.path == "/up" } } } # Log to STDOUT with the current request id as a default log tag. config.log_tags = [ :request_id ] config.logger = ActiveSupport::TaggedLogging.logger(STDOUT) # Change to "debug" to log everything (including potentially personally-identifiable information!) config.log_level = ENV.fetch("RAILS_LOG_LEVEL", "info") # Prevent health checks from clogging up the logs. config.silence_healthcheck_path = "/healthcheck" # Don't log any deprecations. config.active_support.report_deprecations = false # Replace the default in-process memory cache store with a durable alternative. config.cache_store = :solid_cache_store # Replace the default in-process and non-durable queuing backend for Active Job. config.active_job.queue_adapter = :solid_queue # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Set host to be used by links generated in mailer templates. # config.action_mailer.default_url_options = { host: "example.com" } # Specify outgoing SMTP server. Remember to add smtp/* credentials via rails credentials:edit. # config.action_mailer.smtp_settings = { # user_name: Rails.application.credentials.dig(:smtp, :user_name), # password: Rails.application.credentials.dig(:smtp, :password), # address: "smtp.example.com", # port: 587, # authentication: :plain # } # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false # Only use :id for inspections in production. config.active_record.attributes_for_inspect = [ :id ] # Enable DNS rebinding protection and other `Host` header attacks. # config.hosts = [ # "example.com", # Allow requests from example.com # /.*\.example\.com/ # Allow requests from subdomains like `www.example.com` # ] # # Skip DNS rebinding protection for the default health check endpoint. # config.host_authorization = { exclude: ->(request) { request.path == "/up" } } end
ruby
MIT
05379203c0f7e84c6f5df9bbbd384db5ff7ac532
2026-01-04T17:46:46.862481Z
false
bratta/fikus
https://github.com/bratta/fikus/blob/8d6b0789eb932eb0b7a37ceea56d892d14810405/app/app.rb
app/app.rb
class Fikus < Padrino::Application register Padrino::Mailer register Padrino::Helpers ## # Application configuration options # # set :raise_errors, true # Show exceptions (default for development) # set :public, "foo/bar" # Location for static assets (default root/public) # set :reload, false # Reload application files (default in development) # set :default_builder, "foo" # Set a custom form builder (default 'StandardFormBuilder') # set :locale_path, "bar" # Set path for I18n translations (defaults to app/locale/) # enable :sessions # Disabled by default # disable :flash # Disables rack-flash (enabled by default if sessions) # layout :my_layout # Layout can be in views/layouts/foo.ext or views/foo.ext (default :application) # ## # You can configure for a specified environment like: # # configure :development do # set :foo, :bar # disable :asset_stamp # no asset timestamping for dev # end # ## # You can manage errors like: # # error 404 do # render 'errors/404' # end # end
ruby
MIT
8d6b0789eb932eb0b7a37ceea56d892d14810405
2026-01-04T17:46:47.220136Z
false
bratta/fikus
https://github.com/bratta/fikus/blob/8d6b0789eb932eb0b7a37ceea56d892d14810405/app/helpers/fikus_helpers.rb
app/helpers/fikus_helpers.rb
Fikus.helpers do include FikusPageHelpers end
ruby
MIT
8d6b0789eb932eb0b7a37ceea56d892d14810405
2026-01-04T17:46:47.220136Z
false
bratta/fikus
https://github.com/bratta/fikus/blob/8d6b0789eb932eb0b7a37ceea56d892d14810405/app/controllers/main.rb
app/controllers/main.rb
Fikus.controller do get :index do render_page('') end get :index, :with => :page_name do requested_page = (params[:page_name] == nil) ? '' : params[:page_name] render_page(requested_page) end end
ruby
MIT
8d6b0789eb932eb0b7a37ceea56d892d14810405
2026-01-04T17:46:47.220136Z
false
bratta/fikus
https://github.com/bratta/fikus/blob/8d6b0789eb932eb0b7a37ceea56d892d14810405/app/models/account.rb
app/models/account.rb
require 'digest/sha1' class Account include MongoMapper::Document attr_accessor :password # Keys key :name, String key :surname, String key :email, String key :crypted_password, String key :salt, String key :role, String # Validations validates_presence_of :email, :role validates_presence_of :password, :if => :password_required validates_presence_of :password_confirmation, :if => :password_required validates_length_of :password, :within => 4..40, :if => :password_required validates_confirmation_of :password, :if => :password_required validates_length_of :email, :within => 3..100 validates_uniqueness_of :email, :case_sensitive => false validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i validates_format_of :role, :with => /[A-Za-z]/ # Callbacks before_save :generate_password ## # This method is for authentication purpose # def self.authenticate(email, password) account = first(:email => email) if email.present? account && account.password_clean == password ? account : nil end ## # This method is used to retrieve the original password. # def password_clean crypted_password.decrypt(salt) end private def generate_password return if password.blank? self.salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{email}--") if new_record? self.crypted_password = password.encrypt(self.salt) end def password_required crypted_password.blank? || !password.blank? end end
ruby
MIT
8d6b0789eb932eb0b7a37ceea56d892d14810405
2026-01-04T17:46:47.220136Z
false
bratta/fikus
https://github.com/bratta/fikus/blob/8d6b0789eb932eb0b7a37ceea56d892d14810405/app/models/page.rb
app/models/page.rb
class Page include MongoMapper::Document key :title, String, :required => true key :path, String key :body, String, :required => true key :layout, String, :default => 'application.haml' key :weight, Integer, :numeric => true, :default => 0 timestamps! belongs_to :site validates_uniqueness_of :path, :scope => :site_id def self.all_by_weight(domain) Page.all(:site_id => Site.get_site(domain).id.to_s, :order => 'weight asc') end def self.find_by_site_and_path(domain, path) Page.first(:site_id => Site.get_site(domain).id.to_s, :path => path) end end
ruby
MIT
8d6b0789eb932eb0b7a37ceea56d892d14810405
2026-01-04T17:46:47.220136Z
false
bratta/fikus
https://github.com/bratta/fikus/blob/8d6b0789eb932eb0b7a37ceea56d892d14810405/app/models/site.rb
app/models/site.rb
class Site include MongoMapper::Document key :name, String key :domain, String key :tagline, String timestamps! has_many :pages def self.get_site(domain) match = nil Site.all.each do |site| match = site if domain && domain.match(site.domain) end match end end
ruby
MIT
8d6b0789eb932eb0b7a37ceea56d892d14810405
2026-01-04T17:46:47.220136Z
false
bratta/fikus
https://github.com/bratta/fikus/blob/8d6b0789eb932eb0b7a37ceea56d892d14810405/deploy/after_symlink.rb
deploy/after_symlink.rb
# Deploy hook helper methods for shared config files on the Engine Yard AppCloud # NOTE: You need to have these customized files put in place with Chef # Along with any other customized files you need. ['database.rb', 'fikus.yml'].each do |cfg_file| cfg_file_path = "#{shared_path}/config/#{cfg_file}" if File.exist?(cfg_file_path) run "ln -nsf #{cfg_file_path} #{release_path}/config/#{cfg_file}" end end
ruby
MIT
8d6b0789eb932eb0b7a37ceea56d892d14810405
2026-01-04T17:46:47.220136Z
false
bratta/fikus
https://github.com/bratta/fikus/blob/8d6b0789eb932eb0b7a37ceea56d892d14810405/db/seeds.rb
db/seeds.rb
# Seed add you the ability to populate your db. # We provide you a basic shell for interaction with the end user. # So try some code like below: # # name = shell.ask("What's your name?") # shell.say name # #email = shell.ask "Which email do you want use for loggin into admin?" #password = shell.ask "Tell me the password to use:" # Let's set up some sane defaults so we don't have to ask email = "admin@domain.com" password = "fikus" site_name = 'Fikus' site_domain = '.*' site_tagline = 'The Simple Ruby CMS' shell.say "" site = Site.create(:name => site_name, :domain => site_domain, :tagline => site_tagline) page = Page.create(:title => 'Fikus', :weight => 0, :path => '', :body => 'Hello, world!', :site_id => site.id.to_s) account = Account.create(:email => email, :name => "Foo", :surname => "Bar", :password => password, :password_confirmation => password, :role => "admin") if site.valid? shell.say "=================================================================" shell.say "Initial site successfully created. Please edit before going live:" shell.say "=================================================================" shell.say " Name: #{site_name}" shell.say " Domain: #{site_domain}" shell.say " Tagline: #{site_tagline}" else shell.say "Sorry but some thing went worng!" shell.say "" site.errors.full_messages.each { |m| shell.say " - #{m}" } end if account.valid? shell.say "=================================================================" shell.say "Account has been successfully created, now you can login with:" shell.say "=================================================================" shell.say " Email: #{email}" shell.say " password: #{password}" shell.say "=================================================================" else shell.say "Sorry but some thing went worng!" shell.say "" account.errors.full_messages.each { |m| shell.say " - #{m}" } end shell.say ""
ruby
MIT
8d6b0789eb932eb0b7a37ceea56d892d14810405
2026-01-04T17:46:47.220136Z
false
bratta/fikus
https://github.com/bratta/fikus/blob/8d6b0789eb932eb0b7a37ceea56d892d14810405/admin/app.rb
admin/app.rb
class Admin < Padrino::Application register Padrino::Mailer register Padrino::Helpers register Padrino::Admin::AccessControl ## # Application configuration options # # set :raise_errors, true # Show exceptions (default for development) # set :public, "foo/bar" # Location for static assets (default root/public) # set :reload, false # Reload application files (default in development) # set :default_builder, "foo" # Set a custom form builder (default 'StandardFormBuilder') # set :locale_path, "bar" # Set path for I18n translations (default your_app/locales) # enable :sessions # Disabled by default # disable :flash # Disables rack-flash (enabled by default if sessions) # layout :my_layout # Layout can be in views/layouts/foo.ext or views/foo.ext (default :application) # set :login_page, "/admin/sessions/new" disable :store_location access_control.roles_for :any do |role| role.protect "/" role.allow "/sessions" end access_control.roles_for :admin do |role| role.project_module :sites, "/sites" role.project_module :pages, "/pages" role.project_module :accounts, "/accounts" end end
ruby
MIT
8d6b0789eb932eb0b7a37ceea56d892d14810405
2026-01-04T17:46:47.220136Z
false
bratta/fikus
https://github.com/bratta/fikus/blob/8d6b0789eb932eb0b7a37ceea56d892d14810405/admin/helpers/admin_helpers.rb
admin/helpers/admin_helpers.rb
Admin.helpers do include FikusPageHelpers end
ruby
MIT
8d6b0789eb932eb0b7a37ceea56d892d14810405
2026-01-04T17:46:47.220136Z
false
bratta/fikus
https://github.com/bratta/fikus/blob/8d6b0789eb932eb0b7a37ceea56d892d14810405/admin/controllers/sessions.rb
admin/controllers/sessions.rb
Admin.controllers :sessions do get :new do render "/sessions/new", nil, :layout => false end post :create do if account = Account.authenticate(params[:email], params[:password]) set_current_account(account) redirect url(:base, :index) else flash[:warning] = "Login or password wrong." redirect url(:sessions, :new) end end get :destroy do set_current_account(nil) redirect url(:sessions, :new) end end
ruby
MIT
8d6b0789eb932eb0b7a37ceea56d892d14810405
2026-01-04T17:46:47.220136Z
false
bratta/fikus
https://github.com/bratta/fikus/blob/8d6b0789eb932eb0b7a37ceea56d892d14810405/admin/controllers/accounts.rb
admin/controllers/accounts.rb
Admin.controllers :accounts do get :index do @accounts = Account.all render 'accounts/index' end get :new do @account = Account.new render 'accounts/new' end post :create do @account = Account.new(params[:account]) if @account.save flash[:notice] = 'Account was successfully created.' redirect url(:accounts, :edit, :id => @account.id) else render 'accounts/new' end end get :edit, :with => :id do @account = Account.find(params[:id]) render 'accounts/edit' end put :update, :with => :id do @account = Account.find(params[:id]) if @account.update_attributes(params[:account]) flash[:notice] = 'Account was successfully updated.' redirect url(:accounts, :edit, :id => @account.id) else render 'accounts/edit' end end delete :destroy, :with => :id do account = Account.find(params[:id]) if account != current_account && account.destroy flash[:notice] = 'Account was successfully destroyed.' else flash[:error] = 'Impossible destroy Account!' end redirect url(:accounts, :index) end end
ruby
MIT
8d6b0789eb932eb0b7a37ceea56d892d14810405
2026-01-04T17:46:47.220136Z
false
bratta/fikus
https://github.com/bratta/fikus/blob/8d6b0789eb932eb0b7a37ceea56d892d14810405/admin/controllers/sites.rb
admin/controllers/sites.rb
Admin.controllers :sites do get :index do @sites = Site.all render 'sites/index' end get :new do @site = Site.new render 'sites/new' end post :create do @site = Site.new(params[:site]) if @site.save flash[:notice] = 'Site was successfully created.' redirect url(:sites, :edit, :id => @site.id) else render 'sites/new' end end get :edit, :with => :id do @site = Site.find(params[:id]) render 'sites/edit' end put :update, :with => :id do @site = Site.find(params[:id]) if @site.update_attributes(params[:site]) flash[:notice] = 'Site was successfully updated.' redirect url(:sites, :edit, :id => @site.id) else render 'sites/edit' end end delete :destroy, :with => :id do site = Site.find(params[:id]) if site.destroy flash[:notice] = 'Site was successfully destroyed.' else flash[:error] = 'Impossible destroy Site!' end redirect url(:sites, :index) end end
ruby
MIT
8d6b0789eb932eb0b7a37ceea56d892d14810405
2026-01-04T17:46:47.220136Z
false
bratta/fikus
https://github.com/bratta/fikus/blob/8d6b0789eb932eb0b7a37ceea56d892d14810405/admin/controllers/base.rb
admin/controllers/base.rb
Admin.controllers :base do get :index, :map => "/" do render "base/index" end end
ruby
MIT
8d6b0789eb932eb0b7a37ceea56d892d14810405
2026-01-04T17:46:47.220136Z
false
bratta/fikus
https://github.com/bratta/fikus/blob/8d6b0789eb932eb0b7a37ceea56d892d14810405/admin/controllers/pages.rb
admin/controllers/pages.rb
Admin.controllers :pages do get :index do @pages = Page.all render 'pages/index' end get :new do @page = Page.new render 'pages/new' end post :create do @page = Page.new(params[:page]) if @page.save flash[:notice] = 'Page was successfully created.' redirect url(:pages, :edit, :id => @page.id) else render 'pages/new' end end get :edit, :with => :id do @page = Page.find(params[:id]) render 'pages/edit' end put :update, :with => :id do @page = Page.find(params[:id]) if @page.update_attributes(params[:page]) sweep_all_cache if FikusConfig.cache_strategy == 'filesystem' flash[:notice] = 'Page was successfully updated.' redirect url(:pages, :edit, :id => @page.id) else render 'pages/edit' end end delete :destroy, :with => :id do page = Page.find(params[:id]) sweep_cache(page.path) if page if page.destroy flash[:notice] = 'Page was successfully destroyed.' else flash[:error] = 'Impossible destroy Page!' end redirect url(:pages, :index) end end
ruby
MIT
8d6b0789eb932eb0b7a37ceea56d892d14810405
2026-01-04T17:46:47.220136Z
false
bratta/fikus
https://github.com/bratta/fikus/blob/8d6b0789eb932eb0b7a37ceea56d892d14810405/chef/fikus/recipes/default.rb
chef/fikus/recipes/default.rb
# # Cookbook Name:: fikus # Recipe:: default # # Copy customized config files into place # for your fikus website if ['solo', 'app', 'app_master'].include?(node[:instance_role]) node[:applications].each do |app_name,data| mongodb_master = 'localhost' node[:utility_instances].each do |util_instance| if util_instance[:name].match(/mongodb_master/) mongodb_master = util_instance[:hostname] end end user = node[:users].first remote_file "/data/#{app_name}/shared/config/fikus.yml" do owner node[:owner_name] group node[:owner_name] mode 0755 source "fikus.yml" backup false action :create end template "/data/#{app_name}/shared/config/database.rb" do source "database.erb" owner node[:owner_name] group node[:owner_name] mode 0755 variables({ :database => "#{app_name}_#{node[:environment][:framework_env]}", :hostname => mongodb_master, :username => user[:username], :password => user[:password] }) end end end
ruby
MIT
8d6b0789eb932eb0b7a37ceea56d892d14810405
2026-01-04T17:46:47.220136Z
false
bratta/fikus
https://github.com/bratta/fikus/blob/8d6b0789eb932eb0b7a37ceea56d892d14810405/config/fikus.rb
config/fikus.rb
# This loads the site config file for your Fikus installation # Customize fikus.yml to your tastes, and enjoy the power of a # stupid simple content management system powered by love! config = YAML.load_file(File.join(Padrino.root, "config", "fikus.yml")) ::FikusConfig = OpenStruct.new(config[Padrino.env]) case FikusConfig.cache_strategy when 'filesystem' FikusConfig.cacher = FikusCacher::FileSystemCacher.new when 'varnish' FikusConfig.cacher = FikusCacher::VarnishCacher.new else FikusConfig.cacher = FikusCacher::FikusCacher.new end
ruby
MIT
8d6b0789eb932eb0b7a37ceea56d892d14810405
2026-01-04T17:46:47.220136Z
false
bratta/fikus
https://github.com/bratta/fikus/blob/8d6b0789eb932eb0b7a37ceea56d892d14810405/config/apps.rb
config/apps.rb
## # This file mounts each app in the Padrino project to a specified sub-uri. # You can mount additional applications using any of these commands below: # # Padrino.mount("blog").to('/blog') # Padrino.mount("blog", :app_class => "BlogApp").to('/blog') # Padrino.mount("blog", :app_file => "path/to/blog/app.rb").to('/blog') # # You can also map apps to a specified host: # # Padrino.mount("Admin").host("admin.example.org") # Padrino.mount("WebSite").host(/.*\.?example.org/) # Padrino.mount("Foo").to("/foo").host("bar.example.org") # # Note 1: Mounted apps (by default) should be placed into the project root at '/app_name'. # Note 2: If you use the host matching remember to respect the order of the rules. # # By default, this file mounts the parimary app which was generated with this project. # However, the mounted app can be modified as needed: # # Padrino.mount(:app_file => "path/to/file", :app_class => "Blog").to('/') # # Mounts the core application for this project Padrino.mount("Fikus").to('/') Padrino.mount("Admin").to("/admin")
ruby
MIT
8d6b0789eb932eb0b7a37ceea56d892d14810405
2026-01-04T17:46:47.220136Z
false
bratta/fikus
https://github.com/bratta/fikus/blob/8d6b0789eb932eb0b7a37ceea56d892d14810405/config/boot.rb
config/boot.rb
# Defines our constants PADRINO_ENV = ENV["PADRINO_ENV"] ||= ENV["RACK_ENV"] ||= "development" unless defined?(PADRINO_ENV) PADRINO_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..')) unless defined?(PADRINO_ROOT) begin # Require the preresolved locked set of gems. require File.expand_path('../../.bundle/environment', __FILE__) rescue LoadError # Fallback on doing the resolve at runtime. require 'rubygems' require 'bundler' Bundler.setup require 'fileutils' require 'ostruct' require 'uri' end Bundler.require(:default, PADRINO_ENV.to_sym) puts "=> Located #{Padrino.bundle} Gemfile for #{Padrino.env}" Padrino.custom_dependencies("#{Padrino.root}/config/fikus.rb") Padrino::Logger::Config[:staging] = { :log_level => :warn, :stream => :to_file } Padrino.load!
ruby
MIT
8d6b0789eb932eb0b7a37ceea56d892d14810405
2026-01-04T17:46:47.220136Z
false
bratta/fikus
https://github.com/bratta/fikus/blob/8d6b0789eb932eb0b7a37ceea56d892d14810405/config/database.rb
config/database.rb
if ENV['MONGOHQ_URL'] uri = URI.parse(ENV['MONGOHQ_URL']) MongoMapper.connection = Mongo::Connection.from_uri(ENV['MONGOHQ_URL'], :logger => logger) MongoMapper.database = uri.path.gsub(/^\//, '') else MongoMapper.connection = Mongo::Connection.new('localhost', nil, :logger => logger) MongoMapper.database = "fikus_#{Padrino.env}" end
ruby
MIT
8d6b0789eb932eb0b7a37ceea56d892d14810405
2026-01-04T17:46:47.220136Z
false
bratta/fikus
https://github.com/bratta/fikus/blob/8d6b0789eb932eb0b7a37ceea56d892d14810405/shared/lib/page_helpers.rb
shared/lib/page_helpers.rb
module FikusPageHelpers def current_site site = Site.get_site(request.host) end def all_layouts Dir.entries(File.join(Padrino.root, "app", "views", "layouts")).select {|x| x =~ /\.haml$/} end def get_valid_layout(layout_to_use) full_layout_path = File.join(Padrino.root, "app", "views", "layouts", layout_to_use) (File.exist?("#{full_layout_path}")) ? "layouts/#{layout_to_use.gsub(/\.haml$/,'')}".to_sym : :'layouts/application' end def markdown(text) markdown = RDiscount.new(text, :smart) markdown.to_html end def render_page(path_name) @page = Page.find_by_site_and_path(request.host, path_name) halt 404 if !@page FikusConfig.cacher.retrieve(@page) { render('shared/page', :layout => get_valid_layout(@page.layout)) } end end
ruby
MIT
8d6b0789eb932eb0b7a37ceea56d892d14810405
2026-01-04T17:46:47.220136Z
false
bratta/fikus
https://github.com/bratta/fikus/blob/8d6b0789eb932eb0b7a37ceea56d892d14810405/shared/lib/cacher.rb
shared/lib/cacher.rb
module FikusCacher # By default, don't perform any caching. class FikusCacher def cache(page) return true end def sweep(options={}) return true end # Return false if no caching was performed, else return cached contents def retrieve(page) yield end def get_valid_layout(layout_to_use) full_layout_path = File.join(Padrino.root, "app", "views", "layouts", layout_to_use) (File.exist?("#{full_layout_path}")) ? "layouts/#{layout_to_use.gsub(/\.haml$/,'')}".to_sym : :'layouts/application' end end class FileSystemCacher < FikusCacher def cache(page) cache_file = cache_filename(page.id.to_s) if !File.exist?(cache_file) output = yield File.open(cache_file, 'w') { |f| f.write(output) } end output end def sweep(options) if (!options[:page]) FileUtils.rm_rf(File.join(Padrino.root, "app", "cache", "*")) else FileUtils.rm(cache_filename(options[:page].id.to_s)) end end def retrieve(page) cache_file = cache_filename(page.id.to_s) max_age = FikusConfig.max_cache_time now = Time.now if File.file?(cache_file) (current_age = (now - File.mtime(cache_file)).to_i / 60) return File.read(cache_file) if (current_age <= max_age) else self.cache(page) { yield } end end def cache_filename(page_id) cache_path = File.join(Padrino.root, "app", "cache") FileUtils.mkdir_p(cache_path) if !File.directory?(cache_path) cache_file = File.join(cache_path, "#{page_id}.html") end end class VarnishCacher < FikusCacher def retrieve(page) response.headers['Cache-Control'] = "public, max-age=#{FikusConfig.max_cache_time}" yield end end end
ruby
MIT
8d6b0789eb932eb0b7a37ceea56d892d14810405
2026-01-04T17:46:47.220136Z
false
seamusabshere/lock_and_cache
https://github.com/seamusabshere/lock_and_cache/blob/8626eaa73be1904705de89ad916ed782053f8294/benchmarks/allowed_in_keys.rb
benchmarks/allowed_in_keys.rb
require 'set' require 'date' require 'benchmark/ips' ALLOWED_IN_KEYS = [ ::String, ::Symbol, ::Numeric, ::TrueClass, ::FalseClass, ::NilClass, ::Integer, ::Float, ::Date, ::DateTime, ::Time, ].to_set parts = RUBY_VERSION.split('.').map(&:to_i) unless parts[0] >= 2 and parts[1] >= 4 ALLOWED_IN_KEYS << ::Fixnum ALLOWED_IN_KEYS << ::Bignum end EXAMPLES = [ 'hi', :there, 123, 123.54, 1e99, 123456789 ** 2, 1e999, true, false, nil, Date.new(2015,1,1), Time.now, DateTime.now, Mutex, Mutex.new, Benchmark, { hi: :world }, [[]], Fixnum, Struct, Struct.new(:a), Struct.new(:a).new(123) ] EXAMPLES.each do |example| puts "#{example} -> #{example.class}" end puts [ Date.new(2015,1,1), Time.now, DateTime.now, ].each do |x| puts x.to_s end puts EXAMPLES.each do |example| a = ALLOWED_IN_KEYS.any? { |thing| example.is_a?(thing) } b = ALLOWED_IN_KEYS.include? example.class unless a == b raise "#{example.inspect}: #{a.inspect} vs #{b.inspect}" end end Benchmark.ips do |x| x.report("any") do example = EXAMPLES.sample y = ALLOWED_IN_KEYS.any? { |thing| example.is_a?(thing) } a = 1 y end x.report("include") do example = EXAMPLES.sample y = ALLOWED_IN_KEYS.include? example.class a = 1 y end end
ruby
MIT
8626eaa73be1904705de89ad916ed782053f8294
2026-01-04T17:46:54.372075Z
false
seamusabshere/lock_and_cache
https://github.com/seamusabshere/lock_and_cache/blob/8626eaa73be1904705de89ad916ed782053f8294/spec/lock_and_cache_spec.rb
spec/lock_and_cache_spec.rb
require 'spec_helper' class Foo include LockAndCache def initialize(id) @id = id @count = 0 @count_exp = 0 @click_single_hash_arg_as_options = 0 @click_last_hash_as_options = 0 end def click lock_and_cache do @count += 1 end end def cached_rand lock_and_cache do rand end end def click_null lock_and_cache do nil end end def click_exp lock_and_cache(expires: 1) do @count_exp += 1 end end # foo will be treated as option, so this is cacheable def click_single_hash_arg_as_options lock_and_cache(foo: rand, expires: 1) do @click_single_hash_arg_as_options += 1 end end # foo will be treated as part of cache key, so this is uncacheable def click_last_hash_as_options lock_and_cache({foo: rand}, expires: 1) do @click_last_hash_as_options += 1 end end def lock_and_cache_key @id end end class FooId include LockAndCache def click lock_and_cache do nil end end def id @id ||= rand end end class FooClass class << self include LockAndCache def click lock_and_cache do nil end end def id raise "called id" end end end require 'set' $clicking = Set.new class Bar include LockAndCache def initialize(id) @id = id @count = 0 @mutex = Mutex.new end def unsafe_click @mutex.synchronize do # puts "clicking bar #{@id} - #{$clicking.to_a} - #{$clicking.include?(@id)} - #{@id == $clicking.to_a[0]}" raise "somebody already clicking Bar #{@id}" if $clicking.include?(@id) $clicking << @id end sleep 1 @count += 1 $clicking.delete @id @count end def click lock_and_cache do unsafe_click end end def slow_click lock_and_cache do sleep 1 end end def lock_and_cache_key @id end end class Sleeper include LockAndCache def initialize @id = SecureRandom.hex end def poke lock_and_cache heartbeat_expires: 2 do sleep end end def lock_and_cache_key @id end end describe LockAndCache do before do LockAndCache.flush_locks LockAndCache.flush_cache end it 'has a version number' do expect(LockAndCache::VERSION).not_to be nil end describe "caching" do let(:foo) { Foo.new(rand.to_s) } it "works" do expect(foo.click).to eq(1) expect(foo.click).to eq(1) end it "can be cleared" do expect(foo.click).to eq(1) foo.lock_and_cache_clear :click expect(foo.click).to eq(2) end it "can be expired" do expect(foo.click_exp).to eq(1) expect(foo.click_exp).to eq(1) sleep 1.5 expect(foo.click_exp).to eq(2) end it "can cache null" do expect(foo.click_null).to eq(nil) expect(foo.click_null).to eq(nil) end it "treats single hash arg as options" do expect(foo.click_single_hash_arg_as_options).to eq(1) expect(foo.click_single_hash_arg_as_options).to eq(1) sleep 1.1 expect(foo.click_single_hash_arg_as_options).to eq(2) end it "treats last hash as options" do expect(foo.click_last_hash_as_options).to eq(1) expect(foo.click_last_hash_as_options).to eq(2) # it's uncacheable to prove we're not using as part of options expect(foo.click_last_hash_as_options).to eq(3) end it "calls #lock_and_cache_key" do expect(foo).to receive(:lock_and_cache_key) foo.click end it "calls #lock_and_cache_key to differentiate" do a = Foo.new 1 b = Foo.new 2 expect(a.cached_rand).not_to eq(b.cached_rand) end end describe 'self-identification in context mode' do it "calls #id for non-class" do foo_id = FooId.new expect(foo_id).to receive(:id) foo_id.click end it "calls class name for non-class" do foo_id = FooId.new expect(FooId).to receive(:name) foo_id.click end it "uses class name for class" do expect(FooClass).to receive(:name) expect(FooClass).not_to receive(:id) FooClass.click end end describe "locking" do let(:bar) { Bar.new(rand.to_s) } it "it blows up normally (simple thread)" do a = Thread.new do bar.unsafe_click end b = Thread.new do bar.unsafe_click end expect do a.join b.join end.to raise_error(/somebody/) end it "it blows up (pre-existing thread pool, more reliable)" do pool = Thread.pool 2 Thread::Pool.abort_on_exception = true expect do pool.process do bar.unsafe_click end pool.process do bar.unsafe_click end pool.shutdown end.to raise_error(/somebody/) end it "doesn't blow up if you lock it (simple thread)" do a = Thread.new do bar.click end b = Thread.new do bar.click end a.join b.join end it "doesn't blow up if you lock it (pre-existing thread pool, more reliable)" do pool = Thread.pool 2 Thread::Pool.abort_on_exception = true pool.process do bar.click end pool.process do bar.click end pool.shutdown end it "can set a wait time" do pool = Thread.pool 2 Thread::Pool.abort_on_exception = true begin old_max = LockAndCache.max_lock_wait LockAndCache.max_lock_wait = 0.5 expect do pool.process do bar.slow_click end pool.process do bar.slow_click end pool.shutdown end.to raise_error(LockAndCache::TimeoutWaitingForLock) ensure LockAndCache.max_lock_wait = old_max end end it 'unlocks if a process dies' do child = nil begin sleeper = Sleeper.new child = fork do sleeper.poke end sleep 0.1 expect(sleeper.lock_and_cache_locked?(:poke)).to eq(true) # the other process has it Process.kill 'KILL', child expect(sleeper.lock_and_cache_locked?(:poke)).to eq(true) # the other (dead) process still has it sleep 2 expect(sleeper.lock_and_cache_locked?(:poke)).to eq(false) # but now it should be cleared because no heartbeat ensure Process.kill('KILL', child) rescue Errno::ESRCH end end it "pays attention to heartbeats" do child = nil begin sleeper = Sleeper.new child = fork do sleeper.poke end sleep 0.1 expect(sleeper.lock_and_cache_locked?(:poke)).to eq(true) # the other process has it sleep 2 expect(sleeper.lock_and_cache_locked?(:poke)).to eq(true) # the other process still has it sleep 2 expect(sleeper.lock_and_cache_locked?(:poke)).to eq(true) # the other process still has it sleep 2 expect(sleeper.lock_and_cache_locked?(:poke)).to eq(true) # the other process still has it ensure Process.kill('TERM', child) rescue Errno::ESRCH end end end describe 'standalone' do it 'works like you expect' do count = 0 expect(LockAndCache.lock_and_cache('hello') { count += 1 }).to eq(1) expect(count).to eq(1) expect(LockAndCache.lock_and_cache('hello') { count += 1 }).to eq(1) expect(count).to eq(1) end it 'really caches' do expect(LockAndCache.lock_and_cache('hello') { :red }).to eq(:red) expect(LockAndCache.lock_and_cache('hello') { raise(Exception.new("stop")) }).to eq(:red) end it 'caches errors (briefly)' do count = 0 expect { LockAndCache.lock_and_cache('hello') { count += 1; raise("stop") } }.to raise_error(/stop/) expect(count).to eq(1) expect { LockAndCache.lock_and_cache('hello') { count += 1; raise("no no not me") } }.to raise_error(/LockAndCache.*stop/) expect(count).to eq(1) sleep 1 expect { LockAndCache.lock_and_cache('hello') { count += 1; raise("retrying") } }.to raise_error(/retrying/) expect(count).to eq(2) end it "can be queried for cached?" do expect(LockAndCache.cached?('hello')).to be_falsy LockAndCache.lock_and_cache('hello') { nil } expect(LockAndCache.cached?('hello')).to be_truthy end it 'allows expiry' do count = 0 expect(LockAndCache.lock_and_cache('hello', expires: 1) { count += 1 }).to eq(1) expect(count).to eq(1) expect(LockAndCache.lock_and_cache('hello') { count += 1 }).to eq(1) expect(count).to eq(1) sleep 1.1 expect(LockAndCache.lock_and_cache('hello') { count += 1 }).to eq(2) expect(count).to eq(2) end it "allows float expiry" do expect{LockAndCache.lock_and_cache('hello', expires: 1.5) {}}.not_to raise_error end it 'can be nested' do expect(LockAndCache.lock_and_cache('hello') do LockAndCache.lock_and_cache('world') do LockAndCache.lock_and_cache('privyet') do 123 end end end).to eq(123) end it "requires a key" do expect do LockAndCache.lock_and_cache do raise "this won't happen" end end.to raise_error(/need/) end it 'allows checking locks' do expect(LockAndCache.locked?(:sleeper)).to be_falsey t = Thread.new do LockAndCache.lock_and_cache(:sleeper) { sleep 1 } end sleep 0.2 expect(LockAndCache.locked?(:sleeper)).to be_truthy t.join end it 'allows clearing' do count = 0 expect(LockAndCache.lock_and_cache('hello') { count += 1 }).to eq(1) expect(count).to eq(1) LockAndCache.clear('hello') expect(LockAndCache.lock_and_cache('hello') { count += 1 }).to eq(2) expect(count).to eq(2) end it 'allows clearing (complex keys)' do count = 0 expect(LockAndCache.lock_and_cache('hello', {world: 1}, expires: 100) { count += 1 }).to eq(1) expect(count).to eq(1) LockAndCache.clear('hello', world: 1) expect(LockAndCache.lock_and_cache('hello', {world: 1}, expires: 100) { count += 1 }).to eq(2) expect(count).to eq(2) end it 'allows multi-part keys' do count = 0 expect(LockAndCache.lock_and_cache(['hello', 1, { target: 'world' }]) { count += 1 }).to eq(1) expect(count).to eq(1) expect(LockAndCache.lock_and_cache(['hello', 1, { target: 'world' }]) { count += 1 }).to eq(1) expect(count).to eq(1) end it 'treats a single hash arg as a cache key (not as options)' do count = 0 LockAndCache.lock_and_cache(hello: 'world', expires: 100) { count += 1 } expect(count).to eq(1) LockAndCache.lock_and_cache(hello: 'world', expires: 100) { count += 1 } expect(count).to eq(1) LockAndCache.lock_and_cache(hello: 'world', expires: 200) { count += 1 } # expires is being treated as part of cache key expect(count).to eq(2) end it "correctly identifies options hash" do count = 0 LockAndCache.lock_and_cache({ hello: 'world' }, expires: 1, ignored: rand) { count += 1 } expect(count).to eq(1) LockAndCache.lock_and_cache({ hello: 'world' }, expires: 1, ignored: rand) { count += 1 } # expires is not being treated as part of cache key expect(count).to eq(1) sleep 1.1 LockAndCache.lock_and_cache({ hello: 'world' }) { count += 1 } expect(count).to eq(2) end end describe "shorter expiry for null results" do it "optionally caches null for less time" do count = 0 LockAndCache.lock_and_cache('hello', nil_expires: 1, expires: 2) { count += 1; nil } expect(count).to eq(1) LockAndCache.lock_and_cache('hello', nil_expires: 1, expires: 2) { count += 1; nil } expect(count).to eq(1) sleep 1.1 # this is enough to expire LockAndCache.lock_and_cache('hello', nil_expires: 1, expires: 2) { count += 1; nil } expect(count).to eq(2) end it "normally caches null for the same amount of time" do count = 0 expect(LockAndCache.lock_and_cache('hello', expires: 1) { count += 1; nil }).to be_nil expect(count).to eq(1) expect(LockAndCache.lock_and_cache('hello', expires: 1) { count += 1; nil }).to be_nil expect(count).to eq(1) sleep 1.1 expect(LockAndCache.lock_and_cache('hello', expires: 1) { count += 1; nil }).to be_nil expect(count).to eq(2) end it "caches non-null for normal time" do count = 0 LockAndCache.lock_and_cache('hello', nil_expires: 1, expires: 2) { count += 1; true } expect(count).to eq(1) LockAndCache.lock_and_cache('hello', nil_expires: 1, expires: 2) { count += 1; true } expect(count).to eq(1) sleep 1.1 LockAndCache.lock_and_cache('hello', nil_expires: 1, expires: 2) { count += 1; true } expect(count).to eq(1) sleep 1 LockAndCache.lock_and_cache('hello', nil_expires: 1, expires: 2) { count += 1; true } expect(count).to eq(2) end end end
ruby
MIT
8626eaa73be1904705de89ad916ed782053f8294
2026-01-04T17:46:54.372075Z
false
seamusabshere/lock_and_cache
https://github.com/seamusabshere/lock_and_cache/blob/8626eaa73be1904705de89ad916ed782053f8294/spec/spec_helper.rb
spec/spec_helper.rb
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'lock_and_cache' require 'timeout' require 'redis' LockAndCache.lock_storage = Redis.new db: 3 LockAndCache.cache_storage = Redis.new db: 4 require 'thread/pool' require 'pry'
ruby
MIT
8626eaa73be1904705de89ad916ed782053f8294
2026-01-04T17:46:54.372075Z
false
seamusabshere/lock_and_cache
https://github.com/seamusabshere/lock_and_cache/blob/8626eaa73be1904705de89ad916ed782053f8294/spec/lock_and_cache/key_spec.rb
spec/lock_and_cache/key_spec.rb
require 'spec_helper' class KeyTestId def id 'id' end end class KeyTestLockAndCacheKey def lock_and_cache_key 'lock_and_cache_key' end end class KeyTest1 def lock_and_cache_key KeyTestLockAndCacheKey.new end end describe LockAndCache::Key do describe 'parts' do it "has a known issue differentiating between {a: 1} and [[:a, 1]]" do expect(described_class.new(a: 1).send(:parts)).to eq(described_class.new([[:a, 1]]).send(:parts)) end now = Time.now today = Date.today { [1] => [1], ['you'] => ['you'], [['you']] => [['you']], [['you'], "person"] => [['you'], "person"], [['you'], {:silly=>:person}] => [['you'], [[:silly, :person]] ], [now] => [now.to_s], [[now]] => [[now.to_s]], [today] => [today.to_s], [[today]] => [[today.to_s]], { hi: 'you' } => [[:hi, 'you']], { hi: 123 } => [[:hi, 123]], { hi: 123.0 } => [[:hi, 123.0]], { hi: now } => [[:hi, now.to_s]], { hi: today } => [[:hi, today.to_s]], [KeyTestId.new] => ['id'], [[KeyTestId.new]] => [['id']], { a: KeyTestId.new } => [[:a, "id"]], [{ a: KeyTestId.new }] => [[[:a, "id"]]], [[{ a: KeyTestId.new }]] => [[ [[:a, "id"]] ]], [[{ a: [ KeyTestId.new ] }]] => [[[[:a, ["id"]]]]], [[{ a: { b: KeyTestId.new } }]] => [[ [[ :a, [[:b, "id"]] ]] ]], [[{ a: { b: [ KeyTestId.new ] } }]] => [[ [[ :a, [[:b, ["id"]]] ]] ]], [KeyTestLockAndCacheKey.new] => ['lock_and_cache_key'], [[KeyTestLockAndCacheKey.new]] => [['lock_and_cache_key']], { a: KeyTestLockAndCacheKey.new } => [[:a, "lock_and_cache_key"]], [{ a: KeyTestLockAndCacheKey.new }] => [[[:a, "lock_and_cache_key"]]], [[{ a: KeyTestLockAndCacheKey.new }]] => [[ [[:a, "lock_and_cache_key"]] ]], [[{ a: [ KeyTestLockAndCacheKey.new ] }]] => [[[[:a, ["lock_and_cache_key"]]]]], [[{ a: { b: KeyTestLockAndCacheKey.new } }]] => [[ [[ :a, [[:b, "lock_and_cache_key"]] ]] ]], [[{ a: { b: [ KeyTestLockAndCacheKey.new ] } }]] => [[ [[ :a, [[:b, ["lock_and_cache_key"]]] ]] ]], [[{ a: { b: [ KeyTest1.new ] } }]] => [[ [[ :a, [[:b, ["lock_and_cache_key"]]] ]] ]], }.each do |i, o| it "turns #{i} into #{o}" do expect(described_class.new(i).send(:parts)).to eq(o) end end end end
ruby
MIT
8626eaa73be1904705de89ad916ed782053f8294
2026-01-04T17:46:54.372075Z
false
seamusabshere/lock_and_cache
https://github.com/seamusabshere/lock_and_cache/blob/8626eaa73be1904705de89ad916ed782053f8294/lib/lock_and_cache.rb
lib/lock_and_cache.rb
require 'logger' require 'timeout' require 'digest/sha1' require 'base64' require 'redis' require 'active_support' require 'active_support/core_ext' require_relative 'lock_and_cache/version' require_relative 'lock_and_cache/action' require_relative 'lock_and_cache/key' # Lock and cache using redis! # # Most caching libraries don't do locking, meaning that >1 process can be calculating a cached value at the same time. Since you presumably cache things because they cost CPU, database reads, or money, doesn't it make sense to lock while caching? module LockAndCache DEFAULT_MAX_LOCK_WAIT = 60 * 60 * 24 # 1 day in seconds DEFAULT_HEARTBEAT_EXPIRES = 32 # 32 seconds class TimeoutWaitingForLock < StandardError; end # @param redis_connection [Redis] A redis connection to be used for lock storage def LockAndCache.lock_storage=(redis_connection) raise "only redis for now" unless redis_connection.class.to_s == 'Redis' @lock_storage = redis_connection end # @return [Redis] The redis connection used for lock and cached value storage def LockAndCache.lock_storage @lock_storage end # @param redis_connection [Redis] A redis connection to be used for cached value storage def LockAndCache.cache_storage=(redis_connection) raise "only redis for now" unless redis_connection.class.to_s == 'Redis' @cache_storage = redis_connection end # @return [Redis] The redis connection used for cached value storage def LockAndCache.cache_storage @cache_storage end # @param logger [Logger] A logger. def LockAndCache.logger=(logger) @logger = logger end # @return [Logger] The logger. def LockAndCache.logger @logger end # Flush LockAndCache's cached value storage. # # @note If you are sharing a redis database, it will clear it... # # @note If you want to clear a single key, try `LockAndCache.clear(key)` (standalone mode) or `#lock_and_cache_clear(method_id, *key_parts)` in context mode. def LockAndCache.flush_cache cache_storage.flushdb end # Flush LockAndCache's lock storage. # # @note If you are sharing a redis database, it will clear it... # # @note If you want to clear a single key, try `LockAndCache.clear(key)` (standalone mode) or `#lock_and_cache_clear(method_id, *key_parts)` in context mode. def LockAndCache.flush_locks lock_storage.flushdb end # Lock and cache based on a key. # # @param key_parts [*] Parts that should be used to construct a key. # # @note Standalone mode. See also "context mode," where you mix LockAndCache into a class and call it from within its methods. # # @note A single hash arg is treated as a cache key, e.g. `LockAndCache.lock_and_cache(foo: :bar, expires: 100)` will be treated as a cache key of `foo: :bar, expires: 100` (which is probably wrong!!!). Try `LockAndCache.lock_and_cache({ foo: :bar }, expires: 100)` instead. This is the opposite of context mode. def LockAndCache.lock_and_cache(*key_parts_and_options, &blk) options = (key_parts_and_options.last.is_a?(Hash) && key_parts_and_options.length > 1) ? key_parts_and_options.pop : {} raise "need a cache key" unless key_parts_and_options.length > 0 key = LockAndCache::Key.new key_parts_and_options action = LockAndCache::Action.new key, options, blk action.perform end # Clear a single key # # @note Standalone mode. See also "context mode," where you mix LockAndCache into a class and call it from within its methods. def LockAndCache.clear(*key_parts) key = LockAndCache::Key.new key_parts key.clear end # Check if a key is locked # # @note Standalone mode. See also "context mode," where you mix LockAndCache into a class and call it from within its methods. def LockAndCache.locked?(*key_parts) key = LockAndCache::Key.new key_parts key.locked? end # Check if a key is cached already # # @note Standalone mode. See also "context mode," where you mix LockAndCache into a class and call it from within its methods. def LockAndCache.cached?(*key_parts) key = LockAndCache::Key.new key_parts key.cached? end # @param seconds [Numeric] Maximum wait time to get a lock # # @note Can be overridden by putting `max_lock_wait:` in your call to `#lock_and_cache` def LockAndCache.max_lock_wait=(seconds) @max_lock_wait = seconds.to_f end # @private def LockAndCache.max_lock_wait @max_lock_wait || DEFAULT_MAX_LOCK_WAIT end # @param seconds [Numeric] How often a process has to heartbeat in order to keep a lock # # @note Can be overridden by putting `heartbeat_expires:` in your call to `#lock_and_cache` def LockAndCache.heartbeat_expires=(seconds) memo = seconds.to_f raise "heartbeat_expires must be greater than 2 seconds" unless memo >= 2 @heartbeat_expires = memo end # @private def LockAndCache.heartbeat_expires @heartbeat_expires || DEFAULT_HEARTBEAT_EXPIRES end # Check if a method is locked on an object. # # @note Subject mode - this is expected to be called on an object whose class has LockAndCache mixed in. See also standalone mode. def lock_and_cache_locked?(method_id, *key_parts) key = LockAndCache::Key.new key_parts, context: self, method_id: method_id key.locked? end # Clear a lock and cache given exactly the method and exactly the same arguments # # @note Subject mode - this is expected to be called on an object whose class has LockAndCache mixed in. See also standalone mode. def lock_and_cache_clear(method_id, *key_parts) key = LockAndCache::Key.new key_parts, context: self, method_id: method_id key.clear end # Lock and cache a method given key parts. # # The cache key will automatically include the class name of the object calling it (the context!) and the name of the method it is called from. # # @param key_parts_and_options [*] Parts that you want to include in the lock and cache key. If the last element is a Hash, it will be treated as options. # # @return The cached value (possibly newly calculated). # # @note Subject mode - this is expected to be called on an object whose class has LockAndCache mixed in. See also standalone mode. # # @note A single hash arg is treated as an options hash, e.g. `lock_and_cache(expires: 100)` will be treated as options `expires: 100`. This is the opposite of standalone mode. def lock_and_cache(*key_parts_and_options, &blk) options = key_parts_and_options.last.is_a?(Hash) ? key_parts_and_options.pop : {} key = LockAndCache::Key.new key_parts_and_options, context: self, caller: caller action = LockAndCache::Action.new key, options, blk action.perform end end logger = Logger.new $stderr logger.level = (ENV['LOCK_AND_CACHE_DEBUG'] == 'true') ? Logger::DEBUG : Logger::INFO LockAndCache.logger = logger
ruby
MIT
8626eaa73be1904705de89ad916ed782053f8294
2026-01-04T17:46:54.372075Z
false
seamusabshere/lock_and_cache
https://github.com/seamusabshere/lock_and_cache/blob/8626eaa73be1904705de89ad916ed782053f8294/lib/lock_and_cache/version.rb
lib/lock_and_cache/version.rb
module LockAndCache VERSION = '6.0.1' end
ruby
MIT
8626eaa73be1904705de89ad916ed782053f8294
2026-01-04T17:46:54.372075Z
false
seamusabshere/lock_and_cache
https://github.com/seamusabshere/lock_and_cache/blob/8626eaa73be1904705de89ad916ed782053f8294/lib/lock_and_cache/key.rb
lib/lock_and_cache/key.rb
require 'date' module LockAndCache # @private class Key class << self # @private # # Extract the method id from a method's caller array. def extract_method_id_from_caller(kaller) kaller[0] =~ METHOD_NAME_IN_CALLER raise "couldn't get method_id from #{kaller[0]}" unless $1 $1.to_sym end # @private # # Get a context object's class name, which is its own name if it's an object. def extract_class_name(context) (context.class == ::Class) ? context.name : context.class.name end # @private # # Recursively extract id from obj. Calls #lock_and_cache_key if available, otherwise #id def extract_obj_id(obj) klass = obj.class if ALLOWED_IN_KEYS.include?(klass) obj elsif DATE.include?(klass) obj.to_s elsif obj.respond_to?(:lock_and_cache_key) extract_obj_id obj.lock_and_cache_key elsif obj.respond_to?(:id) extract_obj_id obj.id elsif obj.respond_to?(:map) obj.map { |objj| extract_obj_id objj } else raise "#{obj.inspect} must respond to #lock_and_cache_key or #id" end end end ALLOWED_IN_KEYS = [ ::String, ::Symbol, ::Numeric, ::TrueClass, ::FalseClass, ::NilClass, ::Integer, ::Float, ].to_set parts = ::RUBY_VERSION.split('.').map(&:to_i) unless parts[0] >= 2 and parts[1] >= 4 ALLOWED_IN_KEYS << ::Fixnum ALLOWED_IN_KEYS << ::Bignum end DATE = [ ::Date, ::DateTime, ::Time, ].to_set METHOD_NAME_IN_CALLER = /in `([^']+)'/ attr_reader :context attr_reader :method_id def initialize(parts, options = {}) @_parts = parts @context = options[:context] @method_id = if options.has_key?(:method_id) options[:method_id] elsif options.has_key?(:caller) Key.extract_method_id_from_caller options[:caller] elsif context raise "supposed to call context with method_id or caller" end end # A (non-cryptographic) digest of the key parts for use as the cache key def digest @digest ||= ::Digest::SHA1.hexdigest ::Marshal.dump(key) end # A (non-cryptographic) digest of the key parts for use as the lock key def lock_digest @lock_digest ||= 'lock/' + digest end # A human-readable representation of the key parts def key @key ||= if context [class_name, context_id, method_id, parts].compact else parts end end def locked? LockAndCache.lock_storage.exists? lock_digest end def cached? LockAndCache.cache_storage.exists? digest end def clear LockAndCache.logger.debug { "[lock_and_cache] clear #{debug} #{Base64.encode64(digest).strip} #{Digest::SHA1.hexdigest digest}" } LockAndCache.cache_storage.del digest LockAndCache.lock_storage.del lock_digest end alias debug key def context_id return @context_id if defined?(@context_id) @context_id = if context.class == ::Class nil else Key.extract_obj_id context end end def class_name @class_name ||= Key.extract_class_name context end # An array of the parts we use for the key def parts @parts ||= Key.extract_obj_id @_parts end end end
ruby
MIT
8626eaa73be1904705de89ad916ed782053f8294
2026-01-04T17:46:54.372075Z
false
seamusabshere/lock_and_cache
https://github.com/seamusabshere/lock_and_cache/blob/8626eaa73be1904705de89ad916ed782053f8294/lib/lock_and_cache/action.rb
lib/lock_and_cache/action.rb
module LockAndCache # @private class Action ERROR_MAGIC_KEY = :lock_and_cache_error attr_reader :key attr_reader :options attr_reader :blk def initialize(key, options, blk) raise "need a block" unless blk @key = key @options = options.stringify_keys @blk = blk end def expires return @expires if defined?(@expires) @expires = options.has_key?('expires') ? options['expires'].to_f.round : nil end def nil_expires return @nil_expires if defined?(@nil_expires) @nil_expires = options.has_key?('nil_expires') ? options['nil_expires'].to_f.round : nil end def digest @digest ||= key.digest end def lock_digest @lock_digest ||= key.lock_digest end def lock_storage @lock_storage ||= LockAndCache.lock_storage or raise("must set LockAndCache.lock_storage=[Redis]") end def cache_storage @cache_storage ||= LockAndCache.cache_storage or raise("must set LockAndCache.cache_storage=[Redis]") end def load_existing(existing) v = ::Marshal.load(existing) if v.is_a?(::Hash) and (founderr = v[ERROR_MAGIC_KEY]) raise "Another LockAndCache process raised #{founderr}" else v end end def perform max_lock_wait = options.fetch 'max_lock_wait', LockAndCache.max_lock_wait heartbeat_expires = options.fetch('heartbeat_expires', LockAndCache.heartbeat_expires).to_f.ceil raise "heartbeat_expires must be >= 2 seconds" unless heartbeat_expires >= 2 heartbeat_frequency = (heartbeat_expires / 2).ceil LockAndCache.logger.debug { "[lock_and_cache] A1 #{key.debug} #{Base64.encode64(digest).strip} #{Digest::SHA1.hexdigest digest}" } if cache_storage.exists?(digest) and (existing = cache_storage.get(digest)).is_a?(String) return load_existing(existing) end LockAndCache.logger.debug { "[lock_and_cache] B1 #{key.debug} #{Base64.encode64(digest).strip} #{Digest::SHA1.hexdigest digest}" } retval = nil lock_secret = SecureRandom.hex 16 acquired = false begin Timeout.timeout(max_lock_wait, TimeoutWaitingForLock) do until lock_storage.set(lock_digest, lock_secret, nx: true, ex: heartbeat_expires) LockAndCache.logger.debug { "[lock_and_cache] C1 #{key.debug} #{Base64.encode64(digest).strip} #{Digest::SHA1.hexdigest digest}" } sleep rand end acquired = true end LockAndCache.logger.debug { "[lock_and_cache] D1 #{key.debug} #{Base64.encode64(digest).strip} #{Digest::SHA1.hexdigest digest}" } if cache_storage.exists?(digest) and (existing = cache_storage.get(digest)).is_a?(String) LockAndCache.logger.debug { "[lock_and_cache] E1 #{key.debug} #{Base64.encode64(digest).strip} #{Digest::SHA1.hexdigest digest}" } retval = load_existing existing end unless retval LockAndCache.logger.debug { "[lock_and_cache] F1 #{key.debug} #{Base64.encode64(digest).strip} #{Digest::SHA1.hexdigest digest}" } done = false begin lock_extender = Thread.new do loop do LockAndCache.logger.debug { "[lock_and_cache] heartbeat1 #{key.debug} #{Base64.encode64(digest).strip} #{Digest::SHA1.hexdigest digest}" } break if done sleep heartbeat_frequency break if done LockAndCache.logger.debug { "[lock_and_cache] heartbeat2 #{key.debug} #{Base64.encode64(digest).strip} #{Digest::SHA1.hexdigest digest}" } # FIXME use lua to check the value raise "unexpectedly lost lock for #{key.debug}" unless lock_storage.get(lock_digest) == lock_secret lock_storage.set lock_digest, lock_secret, xx: true, ex: heartbeat_expires end end begin retval = blk.call retval.nil? ? set_nil : set_non_nil(retval) rescue set_error $! raise end ensure done = true lock_extender.join if lock_extender.status.nil? end end ensure lock_storage.del lock_digest if acquired end retval end def set_error(exception) cache_storage.set digest, ::Marshal.dump(ERROR_MAGIC_KEY => exception.message), ex: 1 end NIL = Marshal.dump nil def set_nil if nil_expires cache_storage.set digest, NIL, ex: nil_expires elsif expires cache_storage.set digest, NIL, ex: expires else cache_storage.set digest, NIL end end def set_non_nil(retval) raise "expected not null #{retval.inspect}" if retval.nil? if expires cache_storage.set digest, ::Marshal.dump(retval), ex: expires else cache_storage.set digest, ::Marshal.dump(retval) end end end end
ruby
MIT
8626eaa73be1904705de89ad916ed782053f8294
2026-01-04T17:46:54.372075Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/helpers/slack_helper.rb
app/helpers/slack_helper.rb
module SlackHelper end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/helpers/escalation_series_helper.rb
app/helpers/escalation_series_helper.rb
module EscalationSeriesHelper end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/helpers/sessions_helper.rb
app/helpers/sessions_helper.rb
module SessionsHelper end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/helpers/comments_helper.rb
app/helpers/comments_helper.rb
module CommentsHelper end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/helpers/incidents_helper.rb
app/helpers/incidents_helper.rb
module IncidentsHelper end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/helpers/users_helper.rb
app/helpers/users_helper.rb
module UsersHelper end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/helpers/maintenances_helper.rb
app/helpers/maintenances_helper.rb
module MaintenancesHelper end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/helpers/notifier_providers_helper.rb
app/helpers/notifier_providers_helper.rb
module NotifierProvidersHelper end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/helpers/application_helper.rb
app/helpers/application_helper.rb
module ApplicationHelper end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/helpers/incident_events_helper.rb
app/helpers/incident_events_helper.rb
module IncidentEventsHelper end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/helpers/notifiers_helper.rb
app/helpers/notifiers_helper.rb
module NotifiersHelper end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/helpers/escalations_helper.rb
app/helpers/escalations_helper.rb
module EscalationsHelper end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/helpers/topics_helper.rb
app/helpers/topics_helper.rb
module TopicsHelper end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/helpers/home_helper.rb
app/helpers/home_helper.rb
module HomeHelper end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/controllers/topics_controller.rb
app/controllers/topics_controller.rb
class TopicsController < ApplicationController before_action :set_topic, only: [:show, :edit, :update, :destroy, :mailgun, :mackerel, :alertmanager, :slack] skip_before_action :login_required, only: [:mailgun, :mackerel, :alertmanager, :slack], raise: false # GET /topics # GET /topics.json def index @topics = Topic.all end # GET /topics/1 # GET /topics/1.json def show end # GET /topics/new def new @topic = Topic.new end # GET /topics/1/edit def edit end # POST /topics # POST /topics.json def create @topic = Topic.new(topic_params) respond_to do |format| if @topic.save format.html { redirect_to @topic, notice: 'Topic was successfully created.' } format.json { render :show, status: :created, location: @topic } else format.html { render :new } format.json { render json: @topic.errors, status: :unprocessable_entity } end end end # PATCH/PUT /topics/1 # PATCH/PUT /topics/1.json def update respond_to do |format| if @topic.update(topic_params) format.html { redirect_to @topic, notice: 'Topic was successfully updated.' } format.json { render :show, status: :ok, location: @topic } else format.html { render :edit } format.json { render json: @topic.errors, status: :unprocessable_entity } end end end # DELETE /topics/1 # DELETE /topics/1.json def destroy @topic.destroy respond_to do |format| format.html { redirect_to topics_url, notice: 'Topic was successfully destroyed.' } format.json { head :no_content } end end # POST /topics/1/mailgun def mailgun unless @topic.enabled Rails.logger.info "Incident creation is skipped because the topic is disabled." render json: {}, status: 200 return end # http://documentation.mailgun.com/user_manual.html#routes subject = params[:subject] description = params['body-plain'] if @topic.in_maintenance?(subject, description) Rails.logger.info "Incident creation is skipped because the topic is in maintenance." render json: {}, status: 200 return end @topic.incidents.create!( subject: subject, description: description, ) render json: {}, status: 200 end # POST /topics/1/mackerel def mackerel data = JSON.parse(request.body.read) return render json: {}, status: 200 if data.dig('alert', 'status') == 'ok' || data.dig('alertGroup', 'status') == 'OK' unless @topic.enabled Rails.logger.info "Incident creation is skipped because the topic is disabled." render json: {}, status: 200 return end if data['event'] == 'alertGroup' then subject = "[#{data['alertGroup']['status']}] #{data['alertGroupSetting']['name']}" else name = data.key?('host') ? data['host']['name'] : data['alert']['monitorName'] subject = "[#{data['alert']['status']}] #{name}" end description = JSON.pretty_generate(data) if @topic.in_maintenance?(subject, description) Rails.logger.info "Incident creation is skipped because the topic is in maintenance" render json: {}, status: 200 return end @topic.incidents.create!( subject: subject, description: description, ) render json: {}, status: 200 end # POST /topics/1/alertmanager def alertmanager data = JSON.parse(request.body.read) unless @topic.enabled Rails.logger.info "Incident creation is skipped because the topic is disabled." render json: {}, status: 200 return end subject = "[#{data['commonLabels']['severity']}] #{data['commonLabels']['alertname']}: #{data['commonAnnotations']['summary']}" description = JSON.pretty_generate(data) if @topic.in_maintenance?(subject, description) Rails.logger.info "Incident creation is skipped because the topic is in maintenance" render json: {}, status: 200 return end @topic.incidents.create!( subject: subject, description: description, ) render json: {}, status: 200 end def slack unless @topic.enabled Rails.logger.info "Incident creation is skipped because the topic is disabled." render json: {}, status: 200 return end subject = "escalation from slack,channel name:#{params['channel_name']} #{params['text']}" description = "channel:#{params['channel_name']} user:#{params['user_name']} #{params['text']}" if @topic.in_maintenance?(subject, description) Rails.logger.info "Incident creation is skipped because the topic is in maintenance." render json: {}, status: 200 return end @topic.incidents.create!( subject: subject, description: description, ) render json: {text: 'accept your page'}, status: 200 end private # Use callbacks to share common setup or constraints between actions. def set_topic @topic = Topic.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def topic_params params.require(:topic).permit(:name, :kind, :escalation_series_id, :enabled) end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/controllers/home_controller.rb
app/controllers/home_controller.rb
class HomeController < ApplicationController def index redirect_to incidents_path end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/controllers/incidents_controller.rb
app/controllers/incidents_controller.rb
class IncidentsController < ApplicationController before_action :set_incidents, only: [:index, :bulk_acknowledge, :bulk_resolve] before_action :set_incident, only: [:show, :edit, :update, :destroy, :acknowledge, :resolve] before_action :ensure_hash, only: [:acknowledge, :resolve] skip_before_action :login_required, only: [:acknowledge, :resolve], raise: false # GET /incidents # GET /incidents.json def index @page = (params[:page] || 1).to_i @incidents = @incidents.order('id DESC').page(@page).per(25) end # GET /incidents/1 # GET /incidents/1.json def show end # GET /incidents/new def new @incident = Incident.new end # GET /incidents/1/edit def edit end # POST /incidents # POST /incidents.json def create @incident = Incident.new(incident_params) respond_to do |format| if @incident.save format.html { redirect_to @incident, notice: 'Incident was successfully created.' } format.json { render :show, status: :created, location: @incident } else format.html { render :new } format.json { render json: @incident.errors, status: :unprocessable_entity } end end end # PATCH/PUT /incidents/1 # PATCH/PUT /incidents/1.json def update respond_to do |format| if @incident.update(incident_params) format.html { redirect_to @incident, notice: 'Incident was successfully updated.' } format.json { render :show, status: :ok, location: @incident } else format.html { render :edit } format.json { render json: @incident.errors, status: :unprocessable_entity } end end end def bulk_acknowledge @incidents.opened.update_all(status: Incident.statuses[:acknowledged]) respond_to do |format| format.html { redirect_to incidents_url, notice: 'Incidents were successfully acknowledged.' } format.json { head :no_content } end end def bulk_resolve @incidents.update_all(status: Incident.statuses[:resolved]) respond_to do |format| format.html { redirect_to incidents_url, notice: 'Incidents were successfully resolved.' } format.json { head :no_content } end end # DELETE /incidents/1 # DELETE /incidents/1.json def destroy @incident.destroy respond_to do |format| format.html { redirect_to incidents_url, notice: 'Incident was successfully destroyed.' } format.json { head :no_content } end end def acknowledge @incident.acknowledge! respond_to do |format| if current_user format.html { redirect_to incidents_url, notice: 'Incident was successfully acknowledged.' } else format.html { render text: "Acknowledged" } end format.json { render json: {status: 'ok'} } end end def resolve @incident.resolve! respond_to do |format| if current_user format.html { redirect_to incidents_url, notice: 'Incident was successfully resolved.' } else format.html { render text: "Resolved" } end format.json { render json: {status: 'ok'} } end end private # Use callbacks to share common setup or constraints between actions. def set_incident @incident = Incident.find(params[:id]) end def set_incidents set_visible_statuses set_visible_topic @incidents = Incident.all if @visible_statuses @incidents = @incidents.where(status: @visible_statuses) end if @visible_topic @incidents = @incidents.where(topic: @visible_topic) end end def set_visible_statuses @visible_statuses = session[:incidents_statuses] # for transition from rev 0a2dd42 or earlier @visible_statuses = nil if @visible_statuses.try(:empty?) if params[:statuses] if params[:statuses] == '' @visible_statuses = nil # all else @visible_statuses = params[:statuses].split(',').map(&:to_i) end session[:incidents_statuses] = @visible_statuses end end def set_visible_topic @visible_topic = session[:incidents_topic] # for transition from rev 0a2dd42 or earlier @visible_topic = nil if @visible_topic == 'all' if params[:topic] if params[:topic] == 'all' @visible_topic = nil # all else @visible_topic = params[:topic].to_i end session[:incidents_topic] = @visible_topic end end # Never trust parameters from the scary internet, only allow the white list through. def incident_params params.require(:incident).permit(:subject, :description, :topic_id, :occured_at) end def ensure_hash unless params[:hash] == @incident.confirmation_hash render text: "Wrong hash", status: 403 end end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/controllers/users_controller.rb
app/controllers/users_controller.rb
class UsersController < ApplicationController before_action :set_user, only: [:show, :edit, :update, :destroy, :activation, :deactivation] # GET /users # GET /users.json def index @users = User.all end # GET /users/1 # GET /users/1.json def show end # GET /users/new def new @user = User.new end # GET /users/1/edit def edit end # POST /users # POST /users.json def create @user = User.new(user_params) respond_to do |format| if @user.save format.html { redirect_to @user, notice: 'User was successfully created.' } format.json { render :show, status: :created, location: @user } else format.html { render :new } format.json { render json: @user.errors, status: :unprocessable_entity } end end end # PATCH/PUT /users/1 # PATCH/PUT /users/1.json def update respond_to do |format| if @user.update(user_params) format.html { redirect_to @user, notice: 'User was successfully updated.' } format.json { render :show, status: :ok, location: @user } else format.html { render :edit } format.json { render json: @user.errors, status: :unprocessable_entity } end end end # DELETE /users/1 # DELETE /users/1.json def destroy @user.destroy respond_to do |format| format.html { redirect_to users_url, notice: 'User was successfully destroyed.' } format.json { head :no_content } end end # PATCH/PUT /users/1/activation def activation @user.update!(active: true) respond_to do |format| format.html { redirect_to users_url, notice: 'User was successfully activated.' } end end # PATCH/PUT /users/1/deactivation def deactivation @user.update!(active: false) respond_to do |format| format.html { redirect_to users_url, notice: 'User was successfully deactivated.' } end end private # Use callbacks to share common setup or constraints between actions. def set_user @user = User.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def user_params params.require(:user).permit(:name) end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/controllers/slack_controller.rb
app/controllers/slack_controller.rb
class SlackController < ApplicationController skip_before_action :login_required, only: [:interactive], raise: false def interactive verify! message = payload['original_message'] message['attachments'][0].delete('actions') user = payload['user']['name'] text = '' payload['actions'].each do |a| case a['value'] when 'acknowledge' incident.acknowledge! text = ":white_check_mark: @#{user} acknowledged" when 'resolve' incident.resolve! text = ":white_check_mark: @#{user} resolved" end end message['attachments'][0]['fields'] = [{ 'title' => text, 'value' => '', 'short' => false, }] render json: message end private def payload JSON.parse(params[:payload]) end private def verify! verified = false Notifier.preload(:provider).find_each do |n| settings = n.provider.settings.merge(n.settings) token = settings['verification_token'] if n.provider.slack? && settings['enable_buttons'] && payload['token'] == token verified = true break end end unless verified raise 'token verification failed' end end private def incident_id payload['callback_id'].match(/\Aincident\.(\d+)\z/)[1].to_i end private def incident Incident.find(incident_id) end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/controllers/comments_controller.rb
app/controllers/comments_controller.rb
class CommentsController < ApplicationController before_action :set_comment, only: [:show, :edit, :update, :destroy] before_action :set_incident # GET /comments # GET /comments.json def index @comments = Comment.where(incident: @incident) end # GET /comments/1 # GET /comments/1.json def show end # GET /comments/new def new @comment = Comment.new end # GET /comments/1/edit def edit end # POST /comments # POST /comments.json def create p comment_params @comment = Comment.new(comment_params) respond_to do |format| if @comment.save format.html { redirect_to [@incident, @comment], notice: 'Comment was successfully created.' } format.json { render :show, status: :created, location: [@incident, @comment] } else format.html { render :new } format.json { render json: @comment.errors, status: :unprocessable_entity } end end end # PATCH/PUT /comments/1 # PATCH/PUT /comments/1.json def update respond_to do |format| if @comment.update(comment_params) format.html { redirect_to [@incident, @comment], notice: 'Comment was successfully updated.' } format.json { render :show, status: :ok, location: [@incident, @comment] } else format.html { render :edit } format.json { render json: @comment.errors, status: :unprocessable_entity } end end end # DELETE /comments/1 # DELETE /comments/1.json def destroy @comment.destroy respond_to do |format| format.html { redirect_to incident_comments_url, notice: 'Comment was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_comment @comment = Comment.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def comment_params params.require(:comment).permit(:incident_id, :user_id, :comment) end def set_incident @incident = Incident.find(params[:incident_id]) end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/controllers/maintenances_controller.rb
app/controllers/maintenances_controller.rb
class MaintenancesController < ApplicationController before_action :set_maintenance, only: [:show, :edit, :update, :destroy] # GET /maintenances # GET /maintenances.json def index @maintenances = Maintenance.not_expired end # GET /maintenances/1 # GET /maintenances/1.json def show end # GET /maintenances/new def new now = Time.now @maintenance = Maintenance.new( start_time: now, end_time: now + 60*60 ) end # GET /maintenances/1/edit def edit end # POST /maintenances # POST /maintenances.json def create @maintenance = Maintenance.new(maintenance_params) respond_to do |format| if @maintenance.save format.html { redirect_to @maintenance, notice: 'Maintenance was successfully created.' } format.json { render :show, status: :created, location: @maintenance } else format.html { render :new } format.json { render json: @maintenance.errors, status: :unprocessable_entity } end end end # PATCH/PUT /maintenances/1 # PATCH/PUT /maintenances/1.json def update respond_to do |format| if @maintenance.update(maintenance_params) format.html { redirect_to @maintenance, notice: 'Maintenance was successfully updated.' } format.json { render :show, status: :ok, location: @maintenance } else format.html { render :edit } format.json { render json: @maintenance.errors, status: :unprocessable_entity } end end end # DELETE /maintenances/1 # DELETE /maintenances/1.json def destroy @maintenance.destroy respond_to do |format| format.html { redirect_to maintenances_url, notice: 'Maintenance was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_maintenance @maintenance = Maintenance.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def maintenance_params params.require(:maintenance).permit(:topic_id, :start_time, :end_time, :filter) end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/controllers/escalation_series_controller.rb
app/controllers/escalation_series_controller.rb
class EscalationSeriesController < ApplicationController before_action :set_escalation_series, only: [:show, :edit, :update, :destroy, :update_escalations] # GET /escalation_series # GET /escalation_series.json def index @escalation_series = EscalationSeries.all end # GET /escalation_series/1 # GET /escalation_series/1.json def show end # GET /escalation_series/new def new @escalation_series = EscalationSeries.new end # GET /escalation_series/1/edit def edit end # POST /escalation_series # POST /escalation_series.json def create @escalation_series = EscalationSeries.new(escalation_series_params) respond_to do |format| if @escalation_series.save format.html { redirect_to @escalation_series, notice: 'Escalation series was successfully created.' } format.json { render :show, status: :created, location: @escalation_series } else format.html { render :new } format.json { render json: @escalation_series.errors, status: :unprocessable_entity } end end end # PATCH/PUT /escalation_series/1 # PATCH/PUT /escalation_series/1.json def update respond_to do |format| if @escalation_series.update(escalation_series_params) format.html { redirect_to @escalation_series, notice: 'Escalation series was successfully updated.' } format.json { render :show, status: :ok, location: @escalation_series } else format.html { render :edit } format.json { render json: @escalation_series.errors, status: :unprocessable_entity } end end end # DELETE /escalation_series/1 # DELETE /escalation_series/1.json def destroy @escalation_series.destroy respond_to do |format| format.html { redirect_to escalation_series_index_url, notice: 'Escalation series was successfully destroyed.' } format.json { head :no_content } end end def update_escalations @escalation_series.update_escalations! end private # Use callbacks to share common setup or constraints between actions. def set_escalation_series @escalation_series = EscalationSeries.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def escalation_series_params params.require(:escalation_series).permit(:name, :settings).tap do |v| v[:settings] = YAML.load(v[:settings]) end end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/controllers/notifiers_controller.rb
app/controllers/notifiers_controller.rb
class NotifiersController < ApplicationController before_action :set_notifier, only: [:show, :edit, :update, :destroy] # GET /notifiers # GET /notifiers.json def index @notifiers = Notifier.all end # GET /notifiers/1 # GET /notifiers/1.json def show end # GET /notifiers/new def new @notifier = Notifier.new end # GET /notifiers/1/edit def edit end # POST /notifiers # POST /notifiers.json def create @notifier = Notifier.new(notifier_params) respond_to do |format| if @notifier.save format.html { redirect_to @notifier, notice: 'Notifier was successfully created.' } format.json { render :show, status: :created, location: @notifier } else format.html { render :new } format.json { render json: @notifier.errors, status: :unprocessable_entity } end end end # PATCH/PUT /notifiers/1 # PATCH/PUT /notifiers/1.json def update respond_to do |format| if @notifier.update(notifier_params) format.html { redirect_to @notifier, notice: 'Notifier was successfully updated.' } format.json { render :show, status: :ok, location: @notifier } else format.html { render :edit } format.json { render json: @notifier.errors, status: :unprocessable_entity } end end end # DELETE /notifiers/1 # DELETE /notifiers/1.json def destroy @notifier.destroy respond_to do |format| format.html { redirect_to notifiers_url, notice: 'Notifier was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_notifier @notifier = Notifier.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def notifier_params params.require(:notifier).permit(:user_id, :kind, :settings, :notify_after_sec, :provider_id, :topic_id, :enabled).tap do |v| v[:settings] = YAML.load(v[:settings]) end end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/controllers/escalations_controller.rb
app/controllers/escalations_controller.rb
class EscalationsController < ApplicationController before_action :set_escalation, only: [:show, :edit, :update, :destroy] # GET /escalations # GET /escalations.json def index @escalations = Escalation.all.order('escalate_after_sec') end # GET /escalations/1 # GET /escalations/1.json def show end # GET /escalations/new def new @escalation = Escalation.new end # GET /escalations/1/edit def edit end # POST /escalations # POST /escalations.json def create @escalation = Escalation.new(escalation_params) respond_to do |format| if @escalation.save format.html { redirect_to @escalation, notice: 'Escalation was successfully created.' } format.json { render :show, status: :created, location: @escalation } else format.html { render :new } format.json { render json: @escalation.errors, status: :unprocessable_entity } end end end # PATCH/PUT /escalations/1 # PATCH/PUT /escalations/1.json def update respond_to do |format| if @escalation.update(escalation_params) format.html { redirect_to @escalation, notice: 'Escalation was successfully updated.' } format.json { render :show, status: :ok, location: @escalation } else format.html { render :edit } format.json { render json: @escalation.errors, status: :unprocessable_entity } end end end # DELETE /escalations/1 # DELETE /escalations/1.json def destroy @escalation.destroy respond_to do |format| format.html { redirect_to escalations_url, notice: 'Escalation was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_escalation @escalation = Escalation.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def escalation_params params.require(:escalation).permit(:escalate_to_id, :escalate_after_sec, :escalation_series_id) end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/controllers/incident_events_controller.rb
app/controllers/incident_events_controller.rb
require 'securerandom' class IncidentEventsController < ApplicationController skip_before_action :login_required, only: [:twilio], raise: false def twilio @event = IncidentEvent.find(params[:id]) language = ENV['TWILIO_LANGUAGE'] || 'en-US' resp = nil if params[:Digits] case params[:Digits] when '1' @event.incident.acknowledge! rescue nil when '2' @event.incident.resolve! rescue nil end resp = Twilio::TwiML::VoiceResponse.new do |r| r.say message: @event.incident.status, voice: 'alice', language: language r.hangup end else resp = Twilio::TwiML::VoiceResponse.new do |r| r.gather timeout: 10, numDigits: 1 do |g| g.say message: "This is Waker alert.", voice: 'alice', language: language g.say message: @event.incident.subject, voice: 'alice', language: language g.say message: "To acknowledge, press 1.", voice: 'alice', language: language g.say message: "To resolve, press 2.", voice: 'alice', language: language end end end render xml: resp.to_s end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/controllers/notifier_providers_controller.rb
app/controllers/notifier_providers_controller.rb
class NotifierProvidersController < ApplicationController before_action :set_notifier_provider, only: [:show, :edit, :update, :destroy] # GET /notifier_providers # GET /notifier_providers.json def index @notifier_providers = NotifierProvider.all end # GET /notifier_providers/1 # GET /notifier_providers/1.json def show end # GET /notifier_providers/new def new @notifier_provider = NotifierProvider.new end # GET /notifier_providers/1/edit def edit end # POST /notifier_providers # POST /notifier_providers.json def create @notifier_provider = NotifierProvider.new(notifier_provider_params) respond_to do |format| if @notifier_provider.save format.html { redirect_to @notifier_provider, notice: 'Notifier provider was successfully created.' } format.json { render :show, status: :created, location: @notifier_provider } else format.html { render :new } format.json { render json: @notifier_provider.errors, status: :unprocessable_entity } end end end # PATCH/PUT /notifier_providers/1 # PATCH/PUT /notifier_providers/1.json def update respond_to do |format| if @notifier_provider.update(notifier_provider_params) format.html { redirect_to @notifier_provider, notice: 'Notifier provider was successfully updated.' } format.json { render :show, status: :ok, location: @notifier_provider } else format.html { render :edit } format.json { render json: @notifier_provider.errors, status: :unprocessable_entity } end end end # DELETE /notifier_providers/1 # DELETE /notifier_providers/1.json def destroy @notifier_provider.destroy respond_to do |format| format.html { redirect_to notifier_providers_url, notice: 'Notifier provider was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_notifier_provider @notifier_provider = NotifierProvider.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def notifier_provider_params params.require(:notifier_provider).permit(:name, :kind, :settings).tap do |v| v[:settings] = YAML.load(v[:settings]) end end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/controllers/sessions_controller.rb
app/controllers/sessions_controller.rb
class SessionsController < ApplicationController skip_before_action :login_required, only: [:create] def create @user = User.find_or_create_from_auth_hash(auth_hash) @user.update_credentials_from_auth_hash(auth_hash) self.current_user = @user redirect_to '/' end private def auth_hash request.env['omniauth.auth'] end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/controllers/application_controller.rb
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :null_session helper_method :current_user if ENV["GOOGLE_CLIENT_ID"] before_action :login_required end def login_required unless current_user session[:user_id] = nil redirect_to '/auth/google_oauth2_with_calendar' return end unless current_user.active render text: "You are not activated yet. Please ask administrator to activate you" return end end private def current_user=(user) session[:user_id] = user.id end def current_user if user_id = session[:user_id] User.find(user_id) elsif login_token = request.headers['X-Login-Token'] User.find_by(login_token: login_token) end end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/models/maintenance.rb
app/models/maintenance.rb
class Maintenance < ApplicationRecord scope :active, -> { t = Time.now; where('start_time <= ? AND ? <= end_time', t, t) } scope :not_expired, -> { where('? <= end_time', Time.now) } scope :expired, -> { where('end_time < ?', Time.now) } belongs_to :topic def filter_regexp Regexp.new(filter) end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/models/topic.rb
app/models/topic.rb
class Topic < ApplicationRecord enum kind: [:api] belongs_to :escalation_series has_many :incidents validates :name, presence: true validates :kind, presence: true validates :escalation_series, presence: true def in_maintenance?(*bodies) maints = Maintenance.active.where(topic: self) maints.any? do |m| if m.filter.blank? true else r = m.filter_regexp bodies.any? do |body| !!r.match(body) end end end end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/models/incident_event.rb
app/models/incident_event.rb
class IncidentEvent < ApplicationRecord belongs_to :incident enum kind: [:opened, :acknowledged, :resolved, :escalated, :commented, :notified] validates :incident, presence: true validates :kind, presence: true serialize :info, JSON after_create :notify after_initialize :set_defaults def set_defaults self.info ||= {} end def notify return if self.notified? Notifier.all.each do |notifier| next if notifier.topic && self.incident.topic != notifier.topic notifier.notify(self) end end def escalated_to self.info['escalated_to'] && User.find(self.info['escalated_to']['id']) end def escalation self.info['escalation'] && Escalation.find(self.info['escalation']['id']) end def notifier self.info['notifier'] && Notifier.find(self.info['notifier']['id']) end def event self.info['event'] && IncidentEvent.find(self.info['event']['id']) end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/models/comment.rb
app/models/comment.rb
class Comment < ApplicationRecord belongs_to :incident belongs_to :user validates :incident, presence: true validates :user, presence: true validates :comment, presence: true end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/models/notification_worker.rb
app/models/notification_worker.rb
class NotificationWorker include Sidekiq::Worker def self.enqueue(event:, notifier:) Rails.logger.info "Enqueue NotificationWorker job" self.perform_in(notifier.notify_after_sec, event.id, notifier.id) end def perform(event_id, notifier_id) event = IncidentEvent.find(event_id) notifier = Notifier.find(notifier_id) if notifier.enabled notifier.notify_immediately(event) end end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/models/escalation_update_worker.rb
app/models/escalation_update_worker.rb
class EscalationUpdateWorker include Sidekiq::Worker def perform EscalationSeries.all.each do |series| handle_series(series) end rescue => err Rails.logger.error "#{err.class}: #{err}\n#{err.backtrace.join("\n")}" end private def handle_series(series) series.update_escalations! end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/models/application_record.rb
app/models/application_record.rb
# Base ApplicationRecord Class class ApplicationRecord < ActiveRecord::Base self.abstract_class = true end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/models/escalation_worker.rb
app/models/escalation_worker.rb
class EscalationWorker include Sidekiq::Worker def self.enqueue(incident, escalation) Rails.logger.info "Enqueue EscalaionWorker job" self.perform_in(escalation.escalate_after_sec, incident.id, escalation.id) end def perform(incident_id, escalation_id) incident = Incident.find(incident_id) escalation = Escalation.find(escalation_id) if incident.opened? incident.events.create( kind: :escalated, info: { escalation: escalation, escalated_to: escalation.escalate_to, }, ) end end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false
ryotarai/waker
https://github.com/ryotarai/waker/blob/24b15020a03659b61257cc33b905e962bcbe4637/app/models/notifier_provider.rb
app/models/notifier_provider.rb
class NotifierProvider < ApplicationRecord serialize :settings, JSON enum kind: [:mailgun, :file, :rails_logger, :hipchat, :twilio, :slack, :datadog, :sns] validates :name, presence: true after_initialize :set_defaults def set_defaults self.settings ||= {} end def concrete_class self.class.const_get("#{kind.to_s.camelize}ConcreteProvider") end def notify(event:, notifier:) concrete_class.new(provider: self, notifier: notifier, event: event).notify end class ConcreteProvider def initialize(provider:, notifier:, event:) @provider = provider @notifier = notifier @event = event end def notify if skip? Rails.logger.info "Notification skipped." else if target_events.include?(kind_of_event) _notify @event.incident.events.create( kind: :notified, info: {notifier: @notifier, event: @event} ) else Rails.logger.info "Notification skipped due to target events (#{target_events} doesn't include #{kind_of_event})" end end end def _notify raise NotImplementedError end def settings @provider.settings.merge(@notifier.settings) end def skip? # or_conditions = [ # { # 'only_japanese_weekday' => true, # 'not_between' => '9:30-18:30', # }, # { # 'not_japanese_weekday' => true, # } # ] return skip_due_to_or_conditions? || skip_due_to_status_of_incident? end def skip_due_to_status_of_incident? if !@event.incident.opened? && !([:acknowledged, :resolved].include?(kind_of_event)) return true end false end def skip_due_to_or_conditions? or_conditions = settings['or_conditions'] return false unless or_conditions matched = or_conditions.any? do |condition| # japanese_weekday holiday = HolidayJp.holiday?(Date.today) || Time.now.saturday? || Time.now.sunday? if holiday && condition['japanese_weekday'] next false end if !holiday && condition['not_japanese_weekday'] next false end # between skip_due_to_between_condition = %w!between not_between!.any? do |k| if s = condition[k] start_time, end_time = s.split('-') start_time = Time.parse(start_time) end_time = Time.parse(end_time) between = start_time < Time.now && Time.now < end_time if (between && k == 'not_between') || (!between && k == 'between') next true end end false end next false if skip_due_to_between_condition true end return !matched end def all_events [:escalated, :escalated_to_me, :opened, :acknowledged, :resolved, :commented] end def target_events settings['events'] && settings['events'].map {|v| v.to_sym } end def body(formats: [:text]) template_names = [kind_of_event, 'default'] template_names.each_with_index do |template_name, i| begin rendered = ApplicationController.new.render_to_string( template: "notifier_providers/#{@provider.kind}/#{template_name}", formats: formats, layout: nil, locals: {event: @event}, ) return rendered.strip rescue ActionView::MissingTemplate raise if template_names.size - 1 == i end end end def kind_of_event if @event.escalated? && @event.escalated_to == @notifier.user :escalated_to_me else @event.kind.to_sym end end end class FileConcreteProvider < ConcreteProvider def _notify end end class RailsLoggerConcreteProvider < ConcreteProvider def _notify Rails.logger.info(body) end def target_events all_events end end class HipchatConcreteProvider < ConcreteProvider def _notify case kind_of_event when :opened color = 'red' when :acknowledged, :escalated color = 'yellow' when :resolved color = 'green' else return end client = HipChat::Client.new(api_token, api_version: api_version) client[room].send('Waker', body, color: color, notify: notify?) end private def api_token settings.fetch('api_token') end def room settings.fetch('room') end def api_version case settings.fetch('api_version') when '2', 'v2' 'v2' when '1', 'v1' 'v1' else 'v2' end end def notify? !!settings['notify'] end def target_events super || [:escalated, :opened, :acknowledged, :resolved] end end class MailgunConcreteProvider < ConcreteProvider def _notify conn = Faraday.new(url: 'https://api.mailgun.net') do |faraday| faraday.request :url_encoded faraday.response :logger faraday.adapter Faraday.default_adapter end conn.basic_auth('api', api_key) response = conn.post "/v2/#{domain}/messages", { from: from, to: to, subject: "[Waker] #{@event.incident.subject}", text: body, html: body(formats: [:html]), } Rails.logger.info "response status: #{response.status}" Rails.logger.info JSON.parse(response.body) end private def api_key settings.fetch('api_key') end def domain from.split('@').last end def from settings.fetch('from') end def to settings.fetch('to') end def target_events super || [:escalated_to_me] end end class TwilioConcreteProvider < ConcreteProvider def _notify options = {} options[:user] = basic_auth_user if basic_auth_user options[:password] = basic_auth_password if basic_auth_password url = Rails.application.routes.url_helpers.twilio_incident_event_url( @event, options ) Twilio::REST::Client.new(account_sid, auth_token).calls.create( from: from, to: to, url: url, ) end def account_sid settings.fetch('account_sid') end def auth_token settings.fetch('auth_token') end def from settings.fetch('from') end def to settings.fetch('to') end def target_events super || [:escalated_to_me] end def basic_auth_user ENV['BASIC_AUTH_USER'] end def basic_auth_password ENV['BASIC_AUTH_PASSWORD'] end end class SlackConcreteProvider < ConcreteProvider def _notify fields = [] acknowledge_url = Rails.application.routes.url_helpers.acknowledge_incident_url(@event.incident, hash: @event.incident.confirmation_hash) resolve_url = Rails.application.routes.url_helpers.resolve_incident_url(@event.incident, hash: @event.incident.confirmation_hash) comment_url = Rails.application.routes.url_helpers.new_incident_comment_url(@event.incident) actions = [] case kind_of_event when :opened color = 'danger' title = 'New incident opened' if buttons_enabled? action_links = "<#{comment_url}|Comment>" actions = [:acknowledge, :resolve] else action_links = "<#{acknowledge_url}|Acknowledge> or <#{resolve_url}|Resolve> | <#{comment_url}|Comment>" end when :acknowledged color = 'warning' title = 'Incident acknowledged' if buttons_enabled? action_links = "<#{comment_url}|Comment>" actions = [:resolve] else action_links = "<#{resolve_url}|Resolve> | <#{comment_url}|Comment>" end when :escalated color = 'warning' title = "Incident escalated to #{@event.escalated_to.name}" if buttons_enabled? action_links = "<#{comment_url}|Comment>" actions = [:acknowledge, :resolve] else action_links = "<#{acknowledge_url}|Acknowledge> or <#{resolve_url}|Resolve> | <#{comment_url}|Comment>" end when :resolved color = 'good' title = 'Incident resolved' action_links = "<#{comment_url}|Comment>" end text = @event.incident.subject if action_links text += " (#{action_links})" end action_types = { acknowledge: { "name" => "response", "text" => "Acknowledge", "type" => "button", "value" => "acknowledge", }, resolve: { "name" => "response", "text" => "Resolve", "type" => "button", "value" => "resolve", "style" => "primary", }, } attachments = [{ "fallback" => "[#{kind_of_event.to_s.capitalize}] #{@event.incident.subject}", "color" => color, "title" => title, "text" => text, "fields" => fields, "callback_id" => "incident.#{@event.incident.id}", "actions" => actions.map {|t| action_types[t] }, }] payload = {'attachments' => attachments} if channel payload['channel'] = channel end url = URI.parse(webhook_url) conn = Faraday.new(url: "#{url.scheme}://#{url.host}") do |faraday| faraday.adapter Faraday.default_adapter end conn.post do |req| req.url url.path req.headers['Content-Type'] = 'application/json' req.body = payload.to_json end end private def webhook_url settings.fetch('webhook_url') end def channel settings['channel'] end def buttons_enabled? settings['enable_buttons'] end def target_events [:escalated, :opened, :acknowledged, :resolved] end end class DatadogConcreteProvider < ConcreteProvider def _notify dog = Dogapi::Client.new(api_key, app_key) res = dog.emit_event(Dogapi::Event.new( @event.incident.description, { msg_title: @event.incident.subject, alert_type: alert_type, tags: tags, source_type_name: source_type_name, } )) Rails.logger.info res end private def api_key settings.fetch('api_key') end def app_key settings.fetch('app_key') end def alert_type settings['alert_type'] || 'error' end def tags settings['tags'] || 'waker' end def source_type_name settings['source_type_name'] || 'waker' end def target_events [:opened] end end class SnsConcreteProvider < ConcreteProvider def _notify aws_config = {} aws_config[:region] = region if region aws_config[:access_key_id] = access_key_id if access_key_id aws_config[:secret_access_key] = secret_access_key if secret_access_key sns = Aws::SNS::Client.new(aws_config) res = sns.publish( topic_arn: topic_arn, message: @event.incident.description, subject: @event.incident.subject, message_attributes: { 'kind_of_event' => { data_type: 'String', string_value: kind_of_event.to_s, } } ) Rails.logger.info res end private def topic_arn settings.fetch('topic_arn') end def region settings['region'] end def access_key_id settings['access_key_id'] end def secret_access_key settings['secret_access_key'] end def target_events all_events end end end
ruby
MIT
24b15020a03659b61257cc33b905e962bcbe4637
2026-01-04T17:46:55.259411Z
false