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
openjournals/theoj
https://github.com/openjournals/theoj/blob/73c6acccc0aefe64b0030c818f405b25b7e7b589/spec/models/provider/test_provider_spec.rb
spec/models/provider/test_provider_spec.rb
require_relative 'shared_provider_specs' require "rails_helper" describe Provider::TestProvider do def stub_document; end def stub_document_without_version; end def stub_document_not_found allow(described_class).to receive(:get_attributes).and_raise(Provider::Error::DocumentNotFound) end def document_id '123-9' end def document_id_without_version '123' end def version 9 end def expected_attributes { provider_type: :test, provider_id: "123", version: 9, authors: "author list", document_location: "https://example.com/document/123-9.pdf", title: "title", summary: "summary" } end it_should_behave_like 'All providers' end
ruby
MIT
73c6acccc0aefe64b0030c818f405b25b7e7b589
2026-01-04T17:49:58.613320Z
false
openjournals/theoj
https://github.com/openjournals/theoj/blob/73c6acccc0aefe64b0030c818f405b25b7e7b589/spec/lib/extensions/string_spec.rb
spec/lib/extensions/string_spec.rb
require "rails_helper" describe String do describe "#a_or_an" do it "should return a result" do expect( 'elephant'.a_or_an ).to eq('an') expect( 'cat'.a_or_an ).to eq('a') end it "should be case insensitive" do expect( 'Elephant'.a_or_an ).to eq('an') expect( 'Cat'.a_or_an ).to eq('a') end it "should return '' for empty strings" do expect( ''.a_or_an).to eq('') end it "should handle non-alpha characters" do expect( '0'.a_or_an).to eq('a') expect( '~'.a_or_an).to eq('a') end end end
ruby
MIT
73c6acccc0aefe64b0030c818f405b25b7e7b589
2026-01-04T17:49:58.613320Z
false
openjournals/theoj
https://github.com/openjournals/theoj/blob/73c6acccc0aefe64b0030c818f405b25b7e7b589/spec/mailers/application_mailer_spec.rb
spec/mailers/application_mailer_spec.rb
require "rails_helper" RSpec.describe ApplicationMailer, type: :mailer do class TestMailer < ApplicationMailer def test(user) mail to:user, subject:'A Subject' do |format| format.text { render plain: "[Inserted Text]", layout:'mailer' } format.html { render html: "[Inserted HTML]" , layout:'mailer' } end end end let(:user) { create(:user, name:'Joe Smith', email:'jsmith@example.com') } let(:mail) { TestMailer.test(user) } it "sets the from and to addresses" do expect(mail.header[:from].value).to eq('"The OJ Team" <robot@theoj.org>') expect(mail.header[:to ].value).to eq(['"Joe Smith" <jsmith@example.com>']) end it "prefixes the subject" do expect(mail.subject).to eq('[TheOJ] A Subject') content = mail.parts[1].body.encoded expect(content).to match(/<title>\[TheOJ\] A Subject<\/title>/) end it "renders the body in text" do expect( mail.parts[0].content_type ).to match(Mime::TEXT) content = mail.parts[0].body.encoded expect(content).to start_with("Hi Joe Smith,\r\n") expect(content).to include("[Inserted Text]") end it "renders the body in html" do expect( mail.parts[1].content_type ).to match(Mime::HTML) content = mail.parts[1].body.encoded expect(content).to match(/<body>\s*<p>Hi Joe Smith,<\/p>/) expect(content).to include("[Inserted HTML]") end it "handles user's without an email address" do user.email = nil expect( mail.message). to be_a(ActionMailer::Base::NullMail) end end
ruby
MIT
73c6acccc0aefe64b0030c818f405b25b7e7b589
2026-01-04T17:49:58.613320Z
false
openjournals/theoj
https://github.com/openjournals/theoj/blob/73c6acccc0aefe64b0030c818f405b25b7e7b589/spec/mailers/notification_mailer_spec.rb
spec/mailers/notification_mailer_spec.rb
require "rails_helper" RSpec.describe NotificationMailer, type: :mailer do describe "notification" do let(:user) { create(:user, name:'Joe Smith', email:'jsmith@example.com') } let(:paper) { create(:paper, title:'A Paper Title', arxiv_id:'1234.5678v9') } let(:mail) { NotificationMailer.notification(user, paper, 'Here is the content', 'The Subject' ) } it "renders the headers" do expect(mail.subject).to end_with('A Paper Title - The Subject') end it "renders the body" do content = mail.body.parts.map(&:to_s).map(&:strip).join("\n\n").gsub("\r","") expect(content).to eq( fixture_text('notification_mailer/notification') ) end it "contains a link to the paper" do expect(mail.body.encoded).to include( '<a href="http://test.host/review/arxiv:1234.5678v9"') end end end
ruby
MIT
73c6acccc0aefe64b0030c818f405b25b7e7b589
2026-01-04T17:49:58.613320Z
false
openjournals/theoj
https://github.com/openjournals/theoj/blob/73c6acccc0aefe64b0030c818f405b25b7e7b589/spec/mailers/previews/notification_mailer_preview.rb
spec/mailers/previews/notification_mailer_preview.rb
# Preview all emails at http://localhost:3000/rails/mailers/notification_mailer class NotificationMailerPreview < ActionMailer::Preview # Preview this email at http://localhost:3000/rails/mailers/notification_mailer/test def notification NotificationMailer.notification(User.first, Paper.first, 'This is a test e-mail.', 'Test') end end
ruby
MIT
73c6acccc0aefe64b0030c818f405b25b7e7b589
2026-01-04T17:49:58.613320Z
false
openjournals/theoj
https://github.com/openjournals/theoj/blob/73c6acccc0aefe64b0030c818f405b25b7e7b589/lib/settings.rb
lib/settings.rb
Settings = ActiveSupport::OrderedOptions.new begin yaml = File.join(ENV['HOME'], '.rails.settings.yml') if File.exist?(yaml) require "erb" all_settings = YAML.load(ERB.new(IO.read(yaml)).result) || {} env_settings = all_settings[Rails.env] Settings.deep_merge!(env_settings.deep_symbolize_keys) if env_settings end yaml = File.join(Rails.root, 'config', 'settings.yml') if File.exist?(yaml) require "erb" all_settings = YAML.load(ERB.new(IO.read(yaml)).result) || {} env_settings = all_settings[Rails.env] Settings.deep_merge!(env_settings.deep_symbolize_keys) if env_settings end Settings.deep_merge!(Rails.application.secrets) end
ruby
MIT
73c6acccc0aefe64b0030c818f405b25b7e7b589
2026-01-04T17:49:58.613320Z
false
openjournals/theoj
https://github.com/openjournals/theoj/blob/73c6acccc0aefe64b0030c818f405b25b7e7b589/lib/extensions/string.rb
lib/extensions/string.rb
class String def a_or_an self.length==0 ? '' : self[0].downcase.in?(%w{a e i o u }) ? 'an' : 'a' end end
ruby
MIT
73c6acccc0aefe64b0030c818f405b25b7e7b589
2026-01-04T17:49:58.613320Z
false
openjournals/theoj
https://github.com/openjournals/theoj/blob/73c6acccc0aefe64b0030c818f405b25b7e7b589/lib/extensions/firebase.rb
lib/extensions/firebase.rb
require 'firebase' module Firebase # This needs to be synchronized with the polymer code for Oj.utils.clean_firebase_key # Added ~ since we use it as an escape, Also '/' but we don't worry about that INVALID_CHARS = '~.$#[]' INVALID_CHARS_REGEX = /[#{Regexp.escape(INVALID_CHARS)}]/ def self.clean_key(key) key.to_s.gsub(INVALID_CHARS_REGEX) { |c| "~#{c.ord.to_s(16)}" } end end
ruby
MIT
73c6acccc0aefe64b0030c818f405b25b7e7b589
2026-01-04T17:49:58.613320Z
false
openjournals/theoj
https://github.com/openjournals/theoj/blob/73c6acccc0aefe64b0030c818f405b25b7e7b589/config/application.rb
config/application.rb
require File.expand_path('../boot', __FILE__) require 'rails/all' require 'securerandom' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(:default, Rails.env) module Theoj class Application < Rails::Application # Load everything in lib/core-ext Dir[Rails.root.join("lib/extensions/**/*.rb")].each {|f| require f} require File.join(Rails.root, 'lib/settings') # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de config.sass.preferred_syntax = :sass Rails.application.config.assets.precompile.push( "webcomponentsjs/webcomponents.js" ) Rails.application.config.assets.precompile.push( "pdf.worker.js" ) config.i18n.enforce_available_locales = true config.active_record.raise_in_transactional_callbacks = true config.generators do |g| g.test_framework :rspec g.integration_tool :rspec end Rails.configuration.action_mailer.default_options = { from: '"The OJ Team" <robot@theoj.org>' } Rails.configuration.action_mailer.smtp_settings = Settings.smtp_settings if Settings.smtp_settings end end
ruby
MIT
73c6acccc0aefe64b0030c818f405b25b7e7b589
2026-01-04T17:49:58.613320Z
false
openjournals/theoj
https://github.com/openjournals/theoj/blob/73c6acccc0aefe64b0030c818f405b25b7e7b589/config/environment.rb
config/environment.rb
# Load the Rails application. require File.expand_path('../application', __FILE__) # Initialize the Rails application. Theoj::Application.initialize!
ruby
MIT
73c6acccc0aefe64b0030c818f405b25b7e7b589
2026-01-04T17:49:58.613320Z
false
openjournals/theoj
https://github.com/openjournals/theoj/blob/73c6acccc0aefe64b0030c818f405b25b7e7b589/config/routes.rb
config/routes.rb
Theoj::Application.routes.draw do namespace :api, format: 'json' do namespace :v1 do resources :papers, only:[:index, :show, :create, :destroy], param: :identifier, identifier: /[^\/]+/ do collection do get :recent get :as_author get :as_collaborator get :as_reviewer get :as_editor get :search end member do get :preview post action:'create' put :check_for_update get :versions get :state put :transition post :complete match :public, via:[:post, :delete] end resources :assignments, only:[:index, :create, :destroy] resources :annotations, only:[:index, :create] do collection do get :all end member do # Change status put :unresolve put :dispute put :resolve end end end resource :user, only: [:show, :update] do collection do get :lookup end end end end get '/sessions/new', to: 'sessions#new', as: 'new_session' get '/auth/:provider/callback', to: 'sessions#create' get '/auth/failure', to: 'sessions#failure' get '/signout', to: 'sessions#destroy' # TODO: actually hook this up get '/home', to: 'home#temp_home' resources :papers, only: [], param: :identifier, identifier: /[^\/]+/ do member do # Add custom review badge URL for now get 'badge', action: 'badge' end end scope 'feed', controller:'feed' do get 'arxiv(.:format)', action: 'arxiv', defaults: { format:'xml' } end #@todo Remove this alias once we have updated Arxiv get '/papers/arxiv(.:format)', to: 'feed#arxiv', defaults: { format:'xml' } scope 'admin', controller:'admin' do get '', action: 'index' get 'overview', action: 'index' end ################################################################## # Make all other routes get the SPA page ###################################################### # Routes that require authentication with_options to: 'home#index_with_auth' do get '/submit' get '/review' get '/submitted' get '/editing' get '/settings' end if Rails.env.development? get '/*path', to: 'home#index', constraints: { path: /(?!rails).*/ } else get '/*path', to: 'home#index' end root to: 'home#index' # Helpers for Polymer and External Routes scope controller:'none', action:'none' do get 'review/:identifier', as: 'paper_review' get '/:uid', host: 'orcid.org', only_path: false, as: 'orcid_account' end end
ruby
MIT
73c6acccc0aefe64b0030c818f405b25b7e7b589
2026-01-04T17:49:58.613320Z
false
openjournals/theoj
https://github.com/openjournals/theoj/blob/73c6acccc0aefe64b0030c818f405b25b7e7b589/config/unicorn.rb
config/unicorn.rb
worker_processes 3 timeout 30 preload_app true before_fork do |server, worker| Signal.trap 'TERM' do puts 'Unicorn master intercepting TERM and sending myself QUIT instead' Process.kill 'QUIT', Process.pid end defined?(ActiveRecord::Base) and ActiveRecord::Base.connection.disconnect! end after_fork do |server, worker| Signal.trap 'TERM' do puts 'Unicorn worker intercepting TERM and doing nothing. Wait for master to sent QUIT' end defined?(ActiveRecord::Base) and ActiveRecord::Base.establish_connection end
ruby
MIT
73c6acccc0aefe64b0030c818f405b25b7e7b589
2026-01-04T17:49:58.613320Z
false
openjournals/theoj
https://github.com/openjournals/theoj/blob/73c6acccc0aefe64b0030c818f405b25b7e7b589/config/boot.rb
config/boot.rb
# Set up gems listed in the Gemfile. ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
ruby
MIT
73c6acccc0aefe64b0030c818f405b25b7e7b589
2026-01-04T17:49:58.613320Z
false
openjournals/theoj
https://github.com/openjournals/theoj/blob/73c6acccc0aefe64b0030c818f405b25b7e7b589/config/initializers/filter_parameter_logging.rb
config/initializers/filter_parameter_logging.rb
# Be sure to restart your server when you modify this file. # Configure sensitive parameters which will be filtered from the log file. Rails.application.config.filter_parameters += [:password]
ruby
MIT
73c6acccc0aefe64b0030c818f405b25b7e7b589
2026-01-04T17:49:58.613320Z
false
openjournals/theoj
https://github.com/openjournals/theoj/blob/73c6acccc0aefe64b0030c818f405b25b7e7b589/config/initializers/bower_rails.rb
config/initializers/bower_rails.rb
BowerRails.configure do |bower_rails| # Tell bower-rails what path should be considered as root. Defaults to Dir.pwd # bower_rails.root_path = Dir.pwd # Invokes rake bower:install before precompilation. Defaults to false # bower_rails.install_before_precompile = true # Invokes rake bower:resolve before precompilation. Defaults to false # bower_rails.resolve_before_precompile = true # Invokes rake bower:clean before precompilation. Defaults to false # bower_rails.clean_before_precompile = true # Invokes rake bower:install:deployment instead rake bower:install. Defaults to false # bower_rails.use_bower_install_deployment = true end
ruby
MIT
73c6acccc0aefe64b0030c818f405b25b7e7b589
2026-01-04T17:49:58.613320Z
false
openjournals/theoj
https://github.com/openjournals/theoj/blob/73c6acccc0aefe64b0030c818f405b25b7e7b589/config/initializers/version.rb
config/initializers/version.rb
TheOJVersion = "0.1"
ruby
MIT
73c6acccc0aefe64b0030c818f405b25b7e7b589
2026-01-04T17:49:58.613320Z
false
openjournals/theoj
https://github.com/openjournals/theoj/blob/73c6acccc0aefe64b0030c818f405b25b7e7b589/config/initializers/emcee.rb
config/initializers/emcee.rb
# Remove Emcee compressor because it doesn't always work # For example `var regex= /\/*abc;` is compressed with unintended consequences Theoj::Application.assets.unregister_bundle_processor "text/html", :html_compressor
ruby
MIT
73c6acccc0aefe64b0030c818f405b25b7e7b589
2026-01-04T17:49:58.613320Z
false
openjournals/theoj
https://github.com/openjournals/theoj/blob/73c6acccc0aefe64b0030c818f405b25b7e7b589/config/initializers/session_store.rb
config/initializers/session_store.rb
# Be sure to restart your server when you modify this file. Theoj::Application.config.session_store :cookie_store, key: '_theoj_session', expire_after: 2.weeks, http_only: true
ruby
MIT
73c6acccc0aefe64b0030c818f405b25b7e7b589
2026-01-04T17:49:58.613320Z
false
openjournals/theoj
https://github.com/openjournals/theoj/blob/73c6acccc0aefe64b0030c818f405b25b7e7b589/config/initializers/wrap_parameters.rb
config/initializers/wrap_parameters.rb
# Be sure to restart your server when you modify this file. # This file contains settings for ActionController::ParamsWrapper which # is enabled by default. # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. ActiveSupport.on_load(:action_controller) do wrap_parameters format: [:json] if respond_to?(:wrap_parameters) end # To enable root element in JSON for ActiveRecord objects. # ActiveSupport.on_load(:active_record) do # self.include_root_in_json = true # end
ruby
MIT
73c6acccc0aefe64b0030c818f405b25b7e7b589
2026-01-04T17:49:58.613320Z
false
openjournals/theoj
https://github.com/openjournals/theoj/blob/73c6acccc0aefe64b0030c818f405b25b7e7b589/config/initializers/serializer.rb
config/initializers/serializer.rb
# Disable for all serializers (except ArraySerializer) ActiveModel::Serializer.root = false # Disable for ArraySerializer ActiveModel::ArraySerializer.root = false
ruby
MIT
73c6acccc0aefe64b0030c818f405b25b7e7b589
2026-01-04T17:49:58.613320Z
false
openjournals/theoj
https://github.com/openjournals/theoj/blob/73c6acccc0aefe64b0030c818f405b25b7e7b589/config/initializers/omniauth.rb
config/initializers/omniauth.rb
require 'omniauth-orcid' Rails.application.config.middleware.use OmniAuth::Builder do environment = defined?(Rails) ? Rails.env : ENV["RACK_ENV"] path = File.join(Rails.root, "config", "orcid.yml") settings = YAML.load(ERB.new(File.new(path).read).result)[environment] # Make parameters available elsewhere in the app Rails.configuration.orcid = settings # Initialize the OAuth connection provider :orcid, settings['client_id'], settings['client_secret'], :authorize_params => { :scope => '/authenticate' }, :client_options => { :site => settings['site'], :authorize_url => settings['authorize_url'], :token_url => settings['token_url'] } end
ruby
MIT
73c6acccc0aefe64b0030c818f405b25b7e7b589
2026-01-04T17:49:58.613320Z
false
openjournals/theoj
https://github.com/openjournals/theoj/blob/73c6acccc0aefe64b0030c818f405b25b7e7b589/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
ruby
MIT
73c6acccc0aefe64b0030c818f405b25b7e7b589
2026-01-04T17:49:58.613320Z
false
openjournals/theoj
https://github.com/openjournals/theoj/blob/73c6acccc0aefe64b0030c818f405b25b7e7b589/config/initializers/firebase.rb
config/initializers/firebase.rb
firebase_prefix = ENV['FIREBASE_PREFIX'] || Rails.env firebase_prefix += '/' unless firebase_prefix.ends_with?('/') Rails.configuration.firebase_uri_prefix = "https://theoj.firebaseio.com/#{firebase_prefix}" FirebaseClient = Firebase::Client.new( Rails.configuration.firebase_uri_prefix )
ruby
MIT
73c6acccc0aefe64b0030c818f405b25b7e7b589
2026-01-04T17:49:58.613320Z
false
openjournals/theoj
https://github.com/openjournals/theoj/blob/73c6acccc0aefe64b0030c818f405b25b7e7b589/config/initializers/backtrace_silencers.rb
config/initializers/backtrace_silencers.rb
# Be sure to restart your server when you modify this file. # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. # Rails.backtrace_cleaner.remove_silencers!
ruby
MIT
73c6acccc0aefe64b0030c818f405b25b7e7b589
2026-01-04T17:49:58.613320Z
false
openjournals/theoj
https://github.com/openjournals/theoj/blob/73c6acccc0aefe64b0030c818f405b25b7e7b589/config/initializers/mime_types.rb
config/initializers/mime_types.rb
# Be sure to restart your server when you modify this file. # Add new mime types for use in respond_to blocks: # Mime::Type.register "text/richtext", :rtf # Mime::Type.register_alias "text/html", :iphone
ruby
MIT
73c6acccc0aefe64b0030c818f405b25b7e7b589
2026-01-04T17:49:58.613320Z
false
openjournals/theoj
https://github.com/openjournals/theoj/blob/73c6acccc0aefe64b0030c818f405b25b7e7b589/config/initializers/streaming_proxy.rb
config/initializers/streaming_proxy.rb
require 'rack/streaming_proxy' Theoj::Application.configure do # Will be inserted at the end of the middleware stack by default. config.middleware.use Rack::StreamingProxy::Proxy do |request| # Inside the request block, return the full URI to redirect the request to, # or nil/false if the request should continue on down the middleware stack. if request.path.start_with?('/proxy') request.params["url"] end end end
ruby
MIT
73c6acccc0aefe64b0030c818f405b25b7e7b589
2026-01-04T17:49:58.613320Z
false
openjournals/theoj
https://github.com/openjournals/theoj/blob/73c6acccc0aefe64b0030c818f405b25b7e7b589/config/environments/test.rb
config/environments/test.rb
Theoj::Application.configure do # Settings specified here will take precedence over those in config/application.rb. # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! config.cache_classes = true # Do not eager load code on boot. This avoids loading your whole application # just for the purpose of running a single test. If you are using a tool that # preloads Rails for running tests, you may have to set it to true. config.eager_load = false # Configure static asset server for tests with Cache-Control for performance. config.serve_static_files = true config.static_cache_control = "public, max-age=3600" # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Raise exceptions instead of rendering exception templates. config.action_dispatch.show_exceptions = false # Disable request forgery protection in test environment. config.action_controller.allow_forgery_protection = false # 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 # Print deprecation notices to the stderr. config.active_support.deprecation = :stderr config.action_mailer.default_url_options = { host:'test.host' } end
ruby
MIT
73c6acccc0aefe64b0030c818f405b25b7e7b589
2026-01-04T17:49:58.613320Z
false
openjournals/theoj
https://github.com/openjournals/theoj/blob/73c6acccc0aefe64b0030c818f405b25b7e7b589/config/environments/development.rb
config/environments/development.rb
Theoj::Application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = true config.action_mailer.perform_deliveries = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true config.action_mailer.default_url_options = { host:'dev.theoj.org' } end
ruby
MIT
73c6acccc0aefe64b0030c818f405b25b7e7b589
2026-01-04T17:49:58.613320Z
false
openjournals/theoj
https://github.com/openjournals/theoj/blob/73c6acccc0aefe64b0030c818f405b25b7e7b589/config/environments/production.rb
config/environments/production.rb
Theoj::Application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both thread web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Enable Rack::Cache to put a simple HTTP cache in front of your application # Add `rack-cache` to your Gemfile before enabling this. # For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid. # config.action_dispatch.rack_cache = true # Disable Rails's static asset server (Apache or nginx will already do this). config.serve_static_files = false # Compress JavaScripts and CSS. config.assets.js_compressor = :uglifier # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = true # Generate digests for assets URLs. config.assets.digest = true # Version of your assets, change this if you want to expire all your assets. config.assets.version = '1.0' # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Set to :debug to see everything in the log. config.log_level = :info # Prepend all log lines with the following tags. # config.log_tags = [ :subdomain, :uuid ] # Use a different logger for distributed setups. # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) # Use a different cache store in production. # config.cache_store = :mem_cache_store # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = "http://assets.example.com" # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in app/assets folder are already added. # config.assets.precompile += %w( search.js ) # 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 # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation can not be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Disable automatic flushing of the log to improve performance. # config.autoflush_log = false # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new config.action_mailer.smtp_settings = { user_name: ENV["SENDGRID_USERNAME"], password: ENV["SENDGRID_PASSWORD"], address: 'smtp.sendgrid.net', domain: 'theoj.org', port: 587, authentication: :plain, enable_starttls_auto: true } config.action_mailer.default_url_options = { host:'beta.theoj.org' } end
ruby
MIT
73c6acccc0aefe64b0030c818f405b25b7e7b589
2026-01-04T17:49:58.613320Z
false
mattvperry/mumble-ruby
https://github.com/mattvperry/mumble-ruby/blob/b323822cb238579e393b5135d52d0eb61d25bf02/lib/mumble-ruby.rb
lib/mumble-ruby.rb
require 'opus-ruby' require 'active_support/inflector' require 'mumble-ruby/version' require 'mumble-ruby/thread_tools' require 'mumble-ruby/messages' require 'mumble-ruby/connection' require 'mumble-ruby/model' require 'mumble-ruby/user' require 'mumble-ruby/channel' require 'mumble-ruby/client' require 'mumble-ruby/audio_player' require 'mumble-ruby/packet_data_stream' require 'mumble-ruby/img_reader' require 'mumble-ruby/cert_manager' require 'mumble-ruby/audio_recorder' require 'hashie' module Mumble DEFAULTS = { sample_rate: 48000, bitrate: 32000, ssl_cert_opts: { cert_dir: File.expand_path("./"), country_code: "US", organization: "github.com", organization_unit: "Engineering" } } def self.configuration @configuration ||= Hashie::Mash.new(DEFAULTS) end def self.configure yield(configuration) if block_given? end Thread.abort_on_exception = true end
ruby
MIT
b323822cb238579e393b5135d52d0eb61d25bf02
2026-01-04T17:50:56.417802Z
false
mattvperry/mumble-ruby
https://github.com/mattvperry/mumble-ruby/blob/b323822cb238579e393b5135d52d0eb61d25bf02/lib/mumble-ruby/version.rb
lib/mumble-ruby/version.rb
module Mumble VERSION = "1.1.3" end
ruby
MIT
b323822cb238579e393b5135d52d0eb61d25bf02
2026-01-04T17:50:56.417802Z
false
mattvperry/mumble-ruby
https://github.com/mattvperry/mumble-ruby/blob/b323822cb238579e393b5135d52d0eb61d25bf02/lib/mumble-ruby/channel.rb
lib/mumble-ruby/channel.rb
module Mumble class Channel < Model attribute :channel_id do self.data.fetch('channel_id', 0) end attribute :name attribute :parent_id do self.data['parent'] end attribute :links do self.data.fetch('links', []) end def parent client.channels[parent_id] end def children client.channels.values.select do |channel| channel.parent_id == channel_id end end def linked_channels links.map do |channel_id| client.channels[channel_id] end end def users client.users.values.select do |user| user.channel_id == channel_id end end def join client.join_channel(self) end def send_text(string) client.text_channel(self, string) end def send_image(file) client.text_channel_img(self, file) end end end
ruby
MIT
b323822cb238579e393b5135d52d0eb61d25bf02
2026-01-04T17:50:56.417802Z
false
mattvperry/mumble-ruby
https://github.com/mattvperry/mumble-ruby/blob/b323822cb238579e393b5135d52d0eb61d25bf02/lib/mumble-ruby/packet_data_stream.rb
lib/mumble-ruby/packet_data_stream.rb
module Mumble class PacketDataStream def initialize(data=nil) @data = data || 0.chr * 1024 @data = @data.split '' @pos = 0 @ok = true @capacity = @data.size end def valid @ok end def size @pos end def left @capacity - @pos end def append(val) if @pos < @capacity @data[@pos] = val.chr skip else @ok = false end end def append_block(data) len = data.size if len < left @data[@pos, len] = data.split('') skip len else @ok = false end end def get_block(len) if len < left ret = @data[@pos, len] skip len else @ok = false ret = [] end ret end def get_next if @pos < @capacity ret = @data[@pos].ord skip else ret = 0 @ok = false end ret end def rewind @pos = 0 end def skip(len=1) len < left ? @pos += len : @ok = false end def put_int(int) if !(int & 0x8000000000000000).zero? && (~int < 0x100000000) int = ~int puts int if int <= 0x3 # Shortcase for -1 to -4 append(0xFC | int) else append(0xF8) end end if int < 0x80 # Need top bit clear append(int) elsif int < 0x4000 # Need top two bits clear append((int >> 8) | 0x80) append(int & 0xFF) elsif int < 0x200000 # Need top three bits clear append((int >> 16) | 0xC0) append((int >> 8) & 0xFF) append(int & 0xFF) elsif int < 0x10000000 # Need top four bits clear append((int >> 24) | 0xE0) append((int >> 16) & 0xFF) append((int >> 8) & 0xFF) append(int & 0xFF) elsif int < 0x100000000 # It's a full 32-bit integer. append(0xF0) append((int >> 24) & 0xFF) append((int >> 16) & 0xFF) append((int >> 8) & 0xFF) append(int & 0xFF) else # It's a 64-bit value. append(0xF4) append((int >> 56) & 0xFF) append((int >> 48) & 0xFF) append((int >> 40) & 0xFF) append((int >> 32) & 0xFF) append((int >> 24) & 0xFF) append((int >> 16) & 0xFF) append((int >> 8) & 0xFF) append(int & 0xFF) end end def get_int v = get_next int = 0 if (v & 0x80) == 0x00 int = v & 0x7F elsif (v & 0xC0) == 0x80 int = (v & 0x3F) << 8 | get_next elsif (v & 0xF0) == 0xF0 x = v & 0xFC if x == 0xF0 int = get_next << 24 | get_next << 16 | get_next << 8 | get_next elsif x == 0xF4 int = get_next << 56 | get_next << 48 | get_next << 40 | get_next << 32 | get_next << 24 | get_next << 16 | get_next << 8 | get_next elsif x == 0xF8 int = get_int int = ~int elsif x == 0xFC int = v & 0x03 int = ~int else @ok = false int = 0 end elsif (v & 0xF0) == 0xE0 int = (v & 0x0F) << 24 | get_next << 16 | get_next << 8 | get_next elsif (v & 0xE0) == 0xC0 int = (v & 0x1F) << 16 | get_next << 8 | get_next end return int end end end
ruby
MIT
b323822cb238579e393b5135d52d0eb61d25bf02
2026-01-04T17:50:56.417802Z
false
mattvperry/mumble-ruby
https://github.com/mattvperry/mumble-ruby/blob/b323822cb238579e393b5135d52d0eb61d25bf02/lib/mumble-ruby/img_reader.rb
lib/mumble-ruby/img_reader.rb
require 'base64' module Mumble class UnsupportedImgFormat < StandardError def initialize super "Image format must be one of the following: #{ImgReader::FORMATS}" end end class ImgTooLarge < StandardError def initialize super "Image must be smaller than 128 kB" end end class ImgReader class << self FORMATS = %w(png jpg jpeg svg) def msg_from_file(file) @@file = file @@ext = File.extname(@@file)[1..-1] validate_file data = File.read @@file "<img src='data:image/#{@@ext};base64,#{Base64.encode64(data)}'/>" end private def validate_file raise LoadError.new("#{@@file} not found") unless File.exists? @@file raise UnsupportedImgFormat unless FORMATS.include? @@ext raise ImgTooLarge unless File.size(@@file) <= 128 * 1024 end end end end
ruby
MIT
b323822cb238579e393b5135d52d0eb61d25bf02
2026-01-04T17:50:56.417802Z
false
mattvperry/mumble-ruby
https://github.com/mattvperry/mumble-ruby/blob/b323822cb238579e393b5135d52d0eb61d25bf02/lib/mumble-ruby/audio_recorder.rb
lib/mumble-ruby/audio_recorder.rb
require 'wavefile' require 'thread' module Mumble class AudioRecorder include ThreadTools def initialize(client, sample_rate) @client = client @wav_format = WaveFile::Format.new(:mono, :pcm_16, sample_rate) @pds = PacketDataStream.new @pds_lock = Mutex.new @decoders = Hash.new do |h, k| h[k] = Opus::Decoder.new sample_rate, sample_rate / 100, 1 end @queues = Hash.new do |h, k| h[k] = Queue.new end end def recording? @recording ||= false end def start(file) unless recording? @file = WaveFile::Writer.new(file, @wav_format) @callback = @client.on_udp_tunnel { |msg| process_udp_tunnel msg } spawn_thread :write_audio @recording = true end end def stop if recording? @client.remove_callback :udp_tunnel, @callback kill_threads @decoders.values.each &:destroy @decoders.clear @queues.clear @file.close @recording = false end end private def process_udp_tunnel(message) @pds_lock.synchronize do @pds.rewind @pds.append_block message.packet[1..-1] @pds.rewind source = @pds.get_int seq = @pds.get_int len = @pds.get_int opus = @pds.get_block len @queues[source] << @decoders[source].decode(opus.join) end end # TODO: Better audio stream merge with normalization def write_audio pcms = @queues.values .reject { |q| q.empty? } # Remove empty queues .map { |q| q.pop.unpack 's*' } # Grab the top element of each queue and expand head, *tail = pcms if head samples = head.zip(*tail) .map { |pcms| pcms.reduce(:+) / pcms.size } # Average together all the columns of the matrix (merge audio streams) .flatten # Flatten the resulting 1d matrix @file.write WaveFile::Buffer.new(samples, @wav_format) end end end end
ruby
MIT
b323822cb238579e393b5135d52d0eb61d25bf02
2026-01-04T17:50:56.417802Z
false
mattvperry/mumble-ruby
https://github.com/mattvperry/mumble-ruby/blob/b323822cb238579e393b5135d52d0eb61d25bf02/lib/mumble-ruby/thread_tools.rb
lib/mumble-ruby/thread_tools.rb
module Mumble module ThreadTools class DuplicateThread < StandardError; end protected def spawn_thread(sym) raise DuplicateThread if threads.has_key? sym threads[sym] = Thread.new { loop { send sym } } end def spawn_threads(*symbols) symbols.map { |sym| spawn_thread sym } end def kill_threads threads.values.map(&:kill) threads.clear end def threads @threads ||= {} end end end
ruby
MIT
b323822cb238579e393b5135d52d0eb61d25bf02
2026-01-04T17:50:56.417802Z
false
mattvperry/mumble-ruby
https://github.com/mattvperry/mumble-ruby/blob/b323822cb238579e393b5135d52d0eb61d25bf02/lib/mumble-ruby/audio_player.rb
lib/mumble-ruby/audio_player.rb
require 'wavefile' module Mumble class AudioPlayer include ThreadTools COMPRESSED_SIZE = 960 def initialize(type, connection, sample_rate, bitrate) @packet_header = (type << 5).chr @conn = connection @pds = PacketDataStream.new @queue = Queue.new @wav_format = WaveFile::Format.new :mono, :pcm_16, sample_rate create_encoder sample_rate, bitrate end def volume @volume ||= 100 end def volume=(volume) @volume = volume end def playing? @playing ||= false end def play_file(file) unless playing? @file = WaveFile::Reader.new(file, @wav_format) Thread.new { bounded_produce } @playing = true end end def stream_named_pipe(pipe) unless playing? @file = File.open(pipe, 'rb') spawn_threads :produce, :consume @playing = true end end def stop if playing? kill_threads @encoder.reset @file.close unless @file.closed? @playing = false end end private def create_encoder(sample_rate, bitrate) @encoder = Opus::Encoder.new sample_rate, sample_rate / 100, 1 @encoder.vbr_rate = 0 # CBR @encoder.bitrate = bitrate end def change_volume(pcm_data) pcm_data.unpack('s*').map { |s| s * (volume / 100.0) }.pack('s*') end def bounded_produce frame_count = 0 start_time = Time.now.to_f @file.each_buffer(@encoder.frame_size) do |buffer| encode_sample buffer.samples.pack('s*') consume frame_count += 1 wait_time = start_time - Time.now.to_f + frame_count * 0.01 sleep(wait_time) if wait_time > 0 end stop end def produce encode_sample @file.read(@encoder.frame_size * 2) end def encode_sample(sample) pcm_data = change_volume sample @queue << @encoder.encode(pcm_data, COMPRESSED_SIZE) end def consume @seq ||= 0 @seq %= 1000000 # Keep sequence number reasonable for long runs @pds.rewind @seq += 1 @pds.put_int @seq frame = @queue.pop @pds.put_int frame.size @pds.append_block frame size = @pds.size @pds.rewind data = [@packet_header, @pds.get_block(size)].flatten.join @conn.send_udp_packet data end end end
ruby
MIT
b323822cb238579e393b5135d52d0eb61d25bf02
2026-01-04T17:50:56.417802Z
false
mattvperry/mumble-ruby
https://github.com/mattvperry/mumble-ruby/blob/b323822cb238579e393b5135d52d0eb61d25bf02/lib/mumble-ruby/connection.rb
lib/mumble-ruby/connection.rb
require 'socket' require 'openssl' require 'thread' module Mumble class Connection def initialize(host, port, cert_manager) @host = host @port = port @cert_manager = cert_manager @write_lock = Mutex.new end def connect context = OpenSSL::SSL::SSLContext.new(:TLSv1) context.verify_mode = OpenSSL::SSL::VERIFY_NONE [:key, :cert].each { |s| context.send("#{s}=", @cert_manager.send(s)) } tcp_sock = TCPSocket.new @host, @port @sock = OpenSSL::SSL::SSLSocket.new tcp_sock, context @sock.connect end def disconnect @sock.close end def read_message header = read_data 6 type, len = header.unpack Messages::HEADER_FORMAT data = read_data len if type == message_type(:udp_tunnel) # UDP Packet -- No Protobuf message = message_class(:udp_tunnel).new message.packet = data else message = message_raw type, data end message end def send_udp_packet(packet) header = [message_type(:udp_tunnel), packet.length].pack Messages::HEADER_FORMAT send_data(header + packet) end def send_message(sym, attrs) type, klass = message(sym) message = klass.new attrs.each { |k, v| message.send("#{k}=", v) } serial = message.serialize_to_string header = [type, serial.size].pack Messages::HEADER_FORMAT send_data(header + serial) end private def send_data(data) @write_lock.synchronize do @sock.write data end end def read_data(len) @sock.read len end def message(obj) return message_type(obj), message_class(obj) end def message_type(obj) if obj.is_a? Protobuf::Message obj = obj.class.to_s.demodulize.underscore.to_sym end Messages.sym_to_type(obj) end def message_class(obj) Messages.type_to_class(message_type(obj)) end def message_raw(type, data) Messages.raw_to_obj(type, data) end end end
ruby
MIT
b323822cb238579e393b5135d52d0eb61d25bf02
2026-01-04T17:50:56.417802Z
false
mattvperry/mumble-ruby
https://github.com/mattvperry/mumble-ruby/blob/b323822cb238579e393b5135d52d0eb61d25bf02/lib/mumble-ruby/messages.rb
lib/mumble-ruby/messages.rb
### Generated by rprotoc. DO NOT EDIT! ### <proto file: mumble.proto> require 'protobuf/message/message' require 'protobuf/message/enum' require 'protobuf/message/service' require 'protobuf/message/extend' module Mumble module Messages ::Protobuf::OPTIONS[:"optimize_for"] = :SPEED HEADER_FORMAT = "nN" @@sym_to_type = { version: 0, udp_tunnel: 1, authenticate: 2, ping: 3, reject: 4, server_sync: 5, channel_remove: 6, channel_state: 7, user_remove: 8, user_state: 9, ban_list: 10, text_message: 11, permission_denied: 12, acl: 13, query_users: 14, crypt_setup: 15, context_action_add: 16, context_action: 17, user_list: 18, voice_target: 19, permission_query: 20, codec_version: 21, user_stats: 22, request_blob: 23, server_config: 24, suggest_config: 25 } @@type_to_sym = @@sym_to_type.invert class << self def all_types return @@sym_to_type.keys end def sym_to_type(sym) @@sym_to_type[sym] end def type_to_class(type) const_get(@@type_to_sym[type].to_s.camelcase) end def raw_to_obj(type, data) message = type_to_class(type).new message.parse_from_string(data) message end end class Version < ::Protobuf::Message defined_in __FILE__ optional :uint32, :version, 1 optional :string, :release, 2 optional :string, :os, 3 optional :string, :os_version, 4 end class UdpTunnel < ::Protobuf::Message defined_in __FILE__ required :bytes, :packet, 1 end class Authenticate < ::Protobuf::Message defined_in __FILE__ optional :string, :username, 1 optional :string, :password, 2 repeated :string, :tokens, 3 repeated :int32, :celt_versions, 4 optional :bool, :opus, 5, :default => false end class Ping < ::Protobuf::Message defined_in __FILE__ optional :uint64, :timestamp, 1 optional :uint32, :good, 2 optional :uint32, :late, 3 optional :uint32, :lost, 4 optional :uint32, :resync, 5 optional :uint32, :udp_packets, 6 optional :uint32, :tcp_packets, 7 optional :float, :udp_ping_avg, 8 optional :float, :udp_ping_var, 9 optional :float, :tcp_ping_avg, 10 optional :float, :tcp_ping_var, 11 end class Reject < ::Protobuf::Message defined_in __FILE__ class RejectType < ::Protobuf::Enum defined_in __FILE__ None = value(:None, 0) WrongVersion = value(:WrongVersion, 1) InvalidUsername = value(:InvalidUsername, 2) WrongUserPW = value(:WrongUserPW, 3) WrongServerPW = value(:WrongServerPW, 4) UsernameInUse = value(:UsernameInUse, 5) ServerFull = value(:ServerFull, 6) NoCertificate = value(:NoCertificate, 7) end optional :RejectType, :type, 1 optional :string, :reason, 2 end class ServerConfig < ::Protobuf::Message defined_in __FILE__ optional :uint32, :max_bandwidth, 1 optional :string, :welcome_text, 2 optional :bool, :allow_html, 3 optional :uint32, :message_length, 4 optional :uint32, :image_message_length, 5 end class ServerSync < ::Protobuf::Message defined_in __FILE__ optional :uint32, :session, 1 optional :uint32, :max_bandwidth, 2 optional :string, :welcome_text, 3 optional :uint64, :permissions, 4 end class SuggestConfig < ::Protobuf::Message defined_in __FILE__ optional :uint32, :version, 1 optional :bool, :positional, 2 optional :bool, :push_to_talk, 3 end class ChannelRemove < ::Protobuf::Message defined_in __FILE__ required :uint32, :channel_id, 1 end class ChannelState < ::Protobuf::Message defined_in __FILE__ optional :uint32, :channel_id, 1 optional :uint32, :parent, 2 optional :string, :name, 3 repeated :uint32, :links, 4 optional :string, :description, 5 repeated :uint32, :links_add, 6 repeated :uint32, :links_remove, 7 optional :bool, :temporary, 8, :default => false optional :int32, :position, 9, :default => 0 optional :bytes, :description_hash, 10 end class UserRemove < ::Protobuf::Message defined_in __FILE__ required :uint32, :session, 1 optional :uint32, :actor, 2 optional :string, :reason, 3 optional :bool, :ban, 4 end class UserState < ::Protobuf::Message defined_in __FILE__ optional :uint32, :session, 1 optional :uint32, :actor, 2 optional :string, :name, 3 optional :uint32, :user_id, 4 optional :uint32, :channel_id, 5 optional :bool, :mute, 6 optional :bool, :deaf, 7 optional :bool, :suppress, 8 optional :bool, :self_mute, 9 optional :bool, :self_deaf, 10 optional :bytes, :texture, 11 optional :bytes, :plugin_context, 12 optional :string, :plugin_identity, 13 optional :string, :comment, 14 optional :string, :hash, 15 optional :bytes, :comment_hash, 16 optional :bytes, :texture_hash, 17 optional :bool, :priority_speaker, 18 optional :bool, :recording, 19 end class BanList < ::Protobuf::Message defined_in __FILE__ class BanEntry < ::Protobuf::Message defined_in __FILE__ required :bytes, :address, 1 required :uint32, :mask, 2 optional :string, :name, 3 optional :string, :hash, 4 optional :string, :reason, 5 optional :string, :start, 6 optional :uint32, :duration, 7 end repeated :BanEntry, :bans, 1 optional :bool, :query, 2, :default => false end class TextMessage < ::Protobuf::Message defined_in __FILE__ optional :uint32, :actor, 1 repeated :uint32, :session, 2 repeated :uint32, :channel_id, 3 repeated :uint32, :tree_id, 4 required :string, :message, 5 end class PermissionDenied < ::Protobuf::Message defined_in __FILE__ class DenyType < ::Protobuf::Enum defined_in __FILE__ Text = value(:Text, 0) Permission = value(:Permission, 1) SuperUser = value(:SuperUser, 2) ChannelName = value(:ChannelName, 3) TextTooLong = value(:TextTooLong, 4) H9K = value(:H9K, 5) TemporaryChannel = value(:TemporaryChannel, 6) MissingCertificate = value(:MissingCertificate, 7) UserName = value(:UserName, 8) ChannelFull = value(:ChannelFull, 9) NestingLimit = value(:NestingLimit, 10) end optional :uint32, :permission, 1 optional :uint32, :channel_id, 2 optional :uint32, :session, 3 optional :string, :reason, 4 optional :DenyType, :type, 5 optional :string, :name, 6 end class Acl < ::Protobuf::Message defined_in __FILE__ class ChanGroup < ::Protobuf::Message defined_in __FILE__ required :string, :name, 1 optional :bool, :inherited, 2, :default => true optional :bool, :inherit, 3, :default => true optional :bool, :inheritable, 4, :default => true repeated :uint32, :add, 5 repeated :uint32, :remove, 6 repeated :uint32, :inherited_members, 7 end class ChanACL < ::Protobuf::Message defined_in __FILE__ optional :bool, :apply_here, 1, :default => true optional :bool, :apply_subs, 2, :default => true optional :bool, :inherited, 3, :default => true optional :uint32, :user_id, 4 optional :string, :group, 5 optional :uint32, :grant, 6 optional :uint32, :deny, 7 end required :uint32, :channel_id, 1 optional :bool, :inherit_acls, 2, :default => true repeated :ChanGroup, :groups, 3 repeated :ChanACL, :acls, 4 optional :bool, :query, 5, :default => false end class QueryUsers < ::Protobuf::Message defined_in __FILE__ repeated :uint32, :ids, 1 repeated :string, :names, 2 end class CryptSetup < ::Protobuf::Message defined_in __FILE__ optional :bytes, :key, 1 optional :bytes, :client_nonce, 2 optional :bytes, :server_nonce, 3 end class ContextActionModify < ::Protobuf::Message defined_in __FILE__ class Context < ::Protobuf::Enum defined_in __FILE__ Server = value(:Server, 1) Channel = value(:Channel, 2) User = value(:User, 4) end class Operation < ::Protobuf::Enum defined_in __FILE__ Add = value(:Add, 0) Remove = value(:Remove, 1) end required :string, :action, 1 optional :string, :text, 2 optional :uint32, :context, 3 optional :Operation, :operation, 4 end class ContextAction < ::Protobuf::Message defined_in __FILE__ optional :uint32, :session, 1 optional :uint32, :channel_id, 2 required :string, :action, 3 end class UserList < ::Protobuf::Message defined_in __FILE__ class User < ::Protobuf::Message defined_in __FILE__ required :uint32, :user_id, 1 optional :string, :name, 2 end repeated :User, :users, 1 end class VoiceTarget < ::Protobuf::Message defined_in __FILE__ class Target < ::Protobuf::Message defined_in __FILE__ repeated :uint32, :session, 1 optional :uint32, :channel_id, 2 optional :string, :group, 3 optional :bool, :links, 4, :default => false optional :bool, :children, 5, :default => false end optional :uint32, :id, 1 repeated :Target, :targets, 2 end class PermissionQuery < ::Protobuf::Message defined_in __FILE__ optional :uint32, :channel_id, 1 optional :uint32, :permissions, 2 optional :bool, :flush, 3, :default => false end class CodecVersion < ::Protobuf::Message defined_in __FILE__ required :int32, :alpha, 1 required :int32, :beta, 2 required :bool, :prefer_alpha, 3, :default => true optional :bool, :opus, 4, :default => false end class UserStats < ::Protobuf::Message defined_in __FILE__ class Stats < ::Protobuf::Message defined_in __FILE__ optional :uint32, :good, 1 optional :uint32, :late, 2 optional :uint32, :lost, 3 optional :uint32, :resync, 4 end optional :uint32, :session, 1 optional :bool, :stats_only, 2, :default => false repeated :bytes, :certificates, 3 optional :Stats, :from_client, 4 optional :Stats, :from_server, 5 optional :uint32, :udp_packets, 6 optional :uint32, :tcp_packets, 7 optional :float, :udp_ping_avg, 8 optional :float, :udp_ping_var, 9 optional :float, :tcp_ping_avg, 10 optional :float, :tcp_ping_var, 11 optional :Version, :version, 12 repeated :int32, :celt_versions, 13 optional :bytes, :address, 14 optional :uint32, :bandwidth, 15 optional :uint32, :onlinesecs, 16 optional :uint32, :idlesecs, 17 optional :bool, :strong_certificate, 18, :default => false optional :bool, :opus, 19, :default => false end class RequestBlob < ::Protobuf::Message defined_in __FILE__ repeated :uint32, :session_texture, 1 repeated :uint32, :session_comment, 2 repeated :uint32, :channel_description, 3 end end end
ruby
MIT
b323822cb238579e393b5135d52d0eb61d25bf02
2026-01-04T17:50:56.417802Z
false
mattvperry/mumble-ruby
https://github.com/mattvperry/mumble-ruby/blob/b323822cb238579e393b5135d52d0eb61d25bf02/lib/mumble-ruby/client.rb
lib/mumble-ruby/client.rb
require 'hashie' module Mumble class ChannelNotFound < StandardError; end class UserNotFound < StandardError; end class NoSupportedCodec < StandardError; end class Client include ThreadTools attr_reader :users, :channels CODEC_OPUS = 4 def initialize(host, port=64738, username="RubyClient", password="") @users, @channels = {}, {} @callbacks = Hash.new { |h, k| h[k] = [] } @config = Mumble.configuration.dup.tap do |c| c.host = host c.port = port c.username = username c.password = password end yield(@config) if block_given? end def connect @conn = Connection.new @config.host, @config.port, cert_manager @conn.connect init_callbacks version_exchange authenticate spawn_threads :read, :ping connected? # just to get a nice return value end def disconnect kill_threads @conn.disconnect @connected = false end def connected? @connected ||= false end def cert_manager @cert_manager ||= CertManager.new @config.username, @config.ssl_cert_opts end def recorder raise NoSupportedCodec unless @codec @recorder ||= AudioRecorder.new self, @config.sample_rate end def player raise NoSupportedCodec unless @codec @audio_streamer ||= AudioPlayer.new @codec, @conn, @config.sample_rate, @config.bitrate end def me users[@session] end def set_comment(comment="") send_user_state(comment: comment) end def join_channel(channel) id = channel_id channel send_user_state(session: @session, channel_id: id) channels[id] end def move_user(user, channel) cid = channel_id channel uid = user_session user send_user_state(session: uid, channel_id: cid) channels[cid] end def text_user(user, string) session = user_session user send_text_message(session: [user_session(user)], message: string) users[session] end def text_user_img(user, file) text_user(user, ImgReader.msg_from_file(file)) end def text_channel(channel, string) id = channel_id channel send_text_message(channel_id: [id], message: string) channels[id] end def text_channel_img(channel, file) text_channel(channel, ImgReader.msg_from_file(file)) end def find_user(name) users.values.find { |u| u.name == name } end def find_channel(name) channels.values.find { |c| c.name == name } end def on_connected(&block) @callbacks[:connected] << block end def remove_callback(symbol, callback) @callbacks[symbol].delete callback end Messages.all_types.each do |msg_type| define_method "on_#{msg_type}" do |&block| @callbacks[msg_type] << block end define_method "send_#{msg_type}" do |opts| @conn.send_message(msg_type, opts) end end private def read message = @conn.read_message sym = message.class.to_s.demodulize.underscore.to_sym run_callbacks sym, Hashie::Mash.new(message.to_hash) end def ping send_ping timestamp: Time.now.to_i sleep(20) end def run_callbacks(sym, *args) @callbacks[sym].each { |c| c.call *args } end def init_callbacks on_server_sync do |message| @session = message.session @connected = true @callbacks[:connected].each { |c| c.call } end on_channel_state do |message| if channel = channels[message.channel_id] channel.update message.to_hash else channels[message.channel_id] = Channel.new(self, message.to_hash) end end on_channel_remove do |message| channels.delete(message.channel_id) end on_user_state do |message| if user = users[message.session] user.update(message.to_hash) else users[message.session] = User.new(self, message.to_hash) end end on_user_remove do |message| users.delete(message.session) end on_codec_version do |message| codec_negotiation(message) end end def version_exchange send_version({ version: encode_version(1, 2, 10), release: "mumble-ruby #{Mumble::VERSION}", os: %x{uname -s}.strip, os_version: %x{uname -v}.strip }) end def authenticate send_authenticate({ username: @config.username, password: @config.password, opus: true }) end def codec_negotiation(message) @codec = CODEC_OPUS if message.opus end def channel_id(channel) channel = find_channel(channel) if channel.is_a? String id = channel.respond_to?(:channel_id) ? channel.channel_id : channel raise ChannelNotFound unless @channels.has_key? id id end def user_session(user) user = find_user(user) if user.is_a? String id = user.respond_to?(:session) ? user.session : user raise UserNotFound unless @users.has_key? id id end def encode_version(major, minor, patch) (major << 16) | (minor << 8) | (patch & 0xFF) end end end
ruby
MIT
b323822cb238579e393b5135d52d0eb61d25bf02
2026-01-04T17:50:56.417802Z
false
mattvperry/mumble-ruby
https://github.com/mattvperry/mumble-ruby/blob/b323822cb238579e393b5135d52d0eb61d25bf02/lib/mumble-ruby/model.rb
lib/mumble-ruby/model.rb
require 'forwardable' module Mumble class Model extend ::Forwardable class << self def attribute(name, &block) attributes << name define_method(name) do if block_given? self.instance_eval(&block) else @data[name.to_s] end end end def attributes @attributes ||= [] end end def initialize(client, data) @client = client @data = data end def update(data) @data.merge!(data) end def inspect attrs = self.class.attributes.map do |attr| [attr, send(attr)].join("=") end.join(" ") %Q{#<#{self.class.name} #{attrs}>} end protected attr_reader :data, :client end end
ruby
MIT
b323822cb238579e393b5135d52d0eb61d25bf02
2026-01-04T17:50:56.417802Z
false
mattvperry/mumble-ruby
https://github.com/mattvperry/mumble-ruby/blob/b323822cb238579e393b5135d52d0eb61d25bf02/lib/mumble-ruby/cert_manager.rb
lib/mumble-ruby/cert_manager.rb
require 'openssl' require 'fileutils' module Mumble class CertManager attr_reader :key, :cert CERT_STRING = "/C=%s/O=%s/OU=%s/CN=%s" def initialize(username, opts) @cert_dir = File.join(opts[:cert_dir], "#{username.downcase}_cert") @username = username @opts = opts FileUtils.mkdir_p @cert_dir setup_key setup_cert end [:private_key, :public_key, :cert].each do |sym| define_method "#{sym}_path" do File.join(@cert_dir, "#{sym}.pem") end end private def setup_key if File.exists?(private_key_path) @key ||= OpenSSL::PKey::RSA.new File.read(private_key_path) else @key ||= OpenSSL::PKey::RSA.new 2048 File.write private_key_path, key.to_pem File.write public_key_path, key.public_key.to_pem end end def setup_cert if File.exists?(cert_path) @cert ||= OpenSSL::X509::Certificate.new File.read(cert_path) else @cert ||= OpenSSL::X509::Certificate.new subject = CERT_STRING % [@opts[:country_code], @opts[:organization], @opts[:organization_unit], @username] cert.subject = cert.issuer = OpenSSL::X509::Name.parse(subject) cert.not_before = Time.now cert.not_after = Time.new + 365 * 24 * 60 * 60 * 5 cert.public_key = key.public_key cert.serial = rand(65535) + 1 cert.version = 2 ef = OpenSSL::X509::ExtensionFactory.new ef.subject_certificate = cert ef.issuer_certificate = cert cert.add_extension(ef.create_extension("basicConstraints", "CA:TRUE", true)) cert.add_extension(ef.create_extension("keyUsage", "keyCertSign, cRLSign", true)) cert.add_extension(ef.create_extension("subjectKeyIdentifier", "hash", false)) cert.add_extension(ef.create_extension("authorityKeyIdentifier", "keyid:always", false)) cert.sign key, OpenSSL::Digest::SHA256.new File.write cert_path, cert.to_pem end end end end
ruby
MIT
b323822cb238579e393b5135d52d0eb61d25bf02
2026-01-04T17:50:56.417802Z
false
mattvperry/mumble-ruby
https://github.com/mattvperry/mumble-ruby/blob/b323822cb238579e393b5135d52d0eb61d25bf02/lib/mumble-ruby/user.rb
lib/mumble-ruby/user.rb
module Mumble class User < Model attribute :session attribute :user_id attribute :actor attribute :name attribute :channel_id attribute :hash attribute :comment attribute :mute attribute :deaf attribute :self_mute attribute :self_deaf def initialize(client, data) super(client, data) if channel_id.nil? self.update({"channel_id" => 0}) end end def current_channel client.channels[channel_id] end def send_text(string) client.text_user(self, string) end def send_image(file) client.text_user_img(self, file) end def mute(bool=true) client.send_user_state self_mute: bool end def deafen(bool=true) client.send_user_state self_deaf: bool end def muted? !!data['suppress'] || !!data['mute'] || !!self_mute end def deafened? !!data['deaf'] || !!self_deaf end def register client.send_user_state(session: session, user_id: 0) end def stats client.send_user_stats session: session end end end
ruby
MIT
b323822cb238579e393b5135d52d0eb61d25bf02
2026-01-04T17:50:56.417802Z
false
aflatter/oauth2-ruby
https://github.com/aflatter/oauth2-ruby/blob/bba05bc4fa70d80b76ded0ec79ba12b846945b54/oauth2-rails/app/models/oauth2/authorization_code_grant.rb
oauth2-rails/app/models/oauth2/authorization_code_grant.rb
class AuthorizationCodeGrant < ActiveRecord::Base set_table_name 'oauth2_authorization_code_grants' end
ruby
MIT
bba05bc4fa70d80b76ded0ec79ba12b846945b54
2026-01-04T17:51:03.115784Z
false
aflatter/oauth2-ruby
https://github.com/aflatter/oauth2-ruby/blob/bba05bc4fa70d80b76ded0ec79ba12b846945b54/oauth2-rails/rails/uninstall.rb
oauth2-rails/rails/uninstall.rb
# Uninstall hook code here
ruby
MIT
bba05bc4fa70d80b76ded0ec79ba12b846945b54
2026-01-04T17:51:03.115784Z
false
aflatter/oauth2-ruby
https://github.com/aflatter/oauth2-ruby/blob/bba05bc4fa70d80b76ded0ec79ba12b846945b54/oauth2-rails/rails/install.rb
oauth2-rails/rails/install.rb
# Install hook code here
ruby
MIT
bba05bc4fa70d80b76ded0ec79ba12b846945b54
2026-01-04T17:51:03.115784Z
false
aflatter/oauth2-ruby
https://github.com/aflatter/oauth2-ruby/blob/bba05bc4fa70d80b76ded0ec79ba12b846945b54/oauth2-rails/spec/rails_spec.rb
oauth2-rails/spec/rails_spec.rb
describe OAuth2::Rails do it "should initialize a configuration" do subject.config.should be_a(OAuth2::Rails::Config) end it "should setup its configuration" do blk = Proc.new { } subject.config.should_receive(:setup).once.and_yield(blk) subject.setup(&blk) end end
ruby
MIT
bba05bc4fa70d80b76ded0ec79ba12b846945b54
2026-01-04T17:51:03.115784Z
false
aflatter/oauth2-ruby
https://github.com/aflatter/oauth2-ruby/blob/bba05bc4fa70d80b76ded0ec79ba12b846945b54/oauth2-rails/spec/spec_helper.rb
oauth2-rails/spec/spec_helper.rb
%w{core server}.each do |component| $LOAD_PATH.unshift(File.expand_path( File.join('..', '..', "oauth2-#{component}", 'lib'), File.dirname(__FILE__) )) end require "rubygems" begin require "bundler" Bundler.setup rescue LoadError => e puts 'Bundler not found. Please install bundler with the command gem install bundler' end begin require 'rspec' require 'rspec/autorun' rescue LoadError => e puts 'RSpec not found. Please install rspec with command bundle install' end require 'oauth2/rails' Dir.glob(File.dirname(__FILE__) + "/support/**/*.rb").each do |file| require file end Rspec.configure do |config| # == Mock Framework # # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line: # # config.mock_with :mocha # config.mock_with :flexmock # config.mock_with :rr # config.mock_with :rspec end
ruby
MIT
bba05bc4fa70d80b76ded0ec79ba12b846945b54
2026-01-04T17:51:03.115784Z
false
aflatter/oauth2-ruby
https://github.com/aflatter/oauth2-ruby/blob/bba05bc4fa70d80b76ded0ec79ba12b846945b54/oauth2-rails/spec/rails/config_spec.rb
oauth2-rails/spec/rails/config_spec.rb
require 'spec_helper' require 'oauth2/rails/config' describe OAuth2::Rails::Config do it "has a default of :active_record for adapter" do subject.adapter.should == :active_record end it "allows to set adapter" do subject.adapter = :foo_bar subject.adapter.should == :foo_bar end it "has a default of true for enforce_scopes" do subject.enforce_scopes.should == true end it "allows to set enforce_scopes" do subject.enforce_scopes = false subject.enforce_scopes.should == false end it "has defaults for models" do subject.models.should == {:client => :client} end it "allows to set models" do models = {:client => :bar} subject.models = models subject.models.should == models end end
ruby
MIT
bba05bc4fa70d80b76ded0ec79ba12b846945b54
2026-01-04T17:51:03.115784Z
false
aflatter/oauth2-ruby
https://github.com/aflatter/oauth2-ruby/blob/bba05bc4fa70d80b76ded0ec79ba12b846945b54/oauth2-rails/lib/oauth2-rails.rb
oauth2-rails/lib/oauth2-rails.rb
require 'oauth2/rails'
ruby
MIT
bba05bc4fa70d80b76ded0ec79ba12b846945b54
2026-01-04T17:51:03.115784Z
false
aflatter/oauth2-ruby
https://github.com/aflatter/oauth2-ruby/blob/bba05bc4fa70d80b76ded0ec79ba12b846945b54/oauth2-rails/lib/oauth2/rails.rb
oauth2-rails/lib/oauth2/rails.rb
require 'oauth2/rails/engine' if defined?(Rails) require 'oauth2/rails/config' require 'active_support/core_ext/module' module OAuth2 module Rails class << self mattr_accessor :config self.config = Config.new def setup(&block) config.setup(&block) end end end end
ruby
MIT
bba05bc4fa70d80b76ded0ec79ba12b846945b54
2026-01-04T17:51:03.115784Z
false
aflatter/oauth2-ruby
https://github.com/aflatter/oauth2-ruby/blob/bba05bc4fa70d80b76ded0ec79ba12b846945b54/oauth2-rails/lib/oauth2/rails/config.rb
oauth2-rails/lib/oauth2/rails/config.rb
require 'active_support/core_ext/module' module OAuth2 module Rails class Config class << self # We alias this method to something shorter. alias :option :attr_accessor_with_default end option :adapter, :active_record option :enforce_scopes, true option :models, { :client => :client, :authorization_code_grant => :authorization_code_grant } def setup(&block) yield self if block_given? end end end end
ruby
MIT
bba05bc4fa70d80b76ded0ec79ba12b846945b54
2026-01-04T17:51:03.115784Z
false
aflatter/oauth2-ruby
https://github.com/aflatter/oauth2-ruby/blob/bba05bc4fa70d80b76ded0ec79ba12b846945b54/oauth2-rails/lib/oauth2/rails/engine.rb
oauth2-rails/lib/oauth2/rails/engine.rb
require 'rails' module OAuth2 module Rails class Engine < ::Rails::Engine class << self def root @root ||= File.expand_path("../../../..", __FILE__) end end generators do pattern = File.join(root, "generators", "oauth2", "*_generator.rb") Dir.glob(pattern).each { |f| require f } end %w{models controllers}.each do |dir| path = File.join(root, 'app', dir) config.load_paths << path config.load_once_paths.delete(path) end end end end
ruby
MIT
bba05bc4fa70d80b76ded0ec79ba12b846945b54
2026-01-04T17:51:03.115784Z
false
aflatter/oauth2-ruby
https://github.com/aflatter/oauth2-ruby/blob/bba05bc4fa70d80b76ded0ec79ba12b846945b54/oauth2-rails/lib/oauth2/rails/adapters/active_record.rb
oauth2-rails/lib/oauth2/rails/adapters/active_record.rb
module OAuth2 module Rails module Adapters class ActiveRecord < Base def initialize super @models = Hash.new end def create_authorization_code_grant(attributes) model(:authorization_code_grant).create( attributes.slice(:client, :user, :request_uri, :code) ) end # create_table :oauth2_authorization_code_grants do |t| # t.string :code # t.string :redirect_uri # t.integer :user_id # t.integer :client_id # end protected def constantize_model(id) OAuth2::Rails.config.models[:models][id].to_s.camelize.constantize end def model(id) @models[id] ||= constantize_model(id) end end end end end
ruby
MIT
bba05bc4fa70d80b76ded0ec79ba12b846945b54
2026-01-04T17:51:03.115784Z
false
aflatter/oauth2-ruby
https://github.com/aflatter/oauth2-ruby/blob/bba05bc4fa70d80b76ded0ec79ba12b846945b54/oauth2-rails/lib/oauth2/rails/adapters/base.rb
oauth2-rails/lib/oauth2/rails/adapters/base.rb
module OAuth2 module Rails module Adapters class Base def initialize(options) @options = options end # Must be implemented by subclasses # Returns true on success, else false. def create_authorization_code_grant(attributes) raise NotImplementedError.new end end end end end
ruby
MIT
bba05bc4fa70d80b76ded0ec79ba12b846945b54
2026-01-04T17:51:03.115784Z
false
aflatter/oauth2-ruby
https://github.com/aflatter/oauth2-ruby/blob/bba05bc4fa70d80b76ded0ec79ba12b846945b54/oauth2-server/spec/server_spec.rb
oauth2-server/spec/server_spec.rb
require 'spec_helper.rb' describe OAuth2::Server do end
ruby
MIT
bba05bc4fa70d80b76ded0ec79ba12b846945b54
2026-01-04T17:51:03.115784Z
false
aflatter/oauth2-ruby
https://github.com/aflatter/oauth2-ruby/blob/bba05bc4fa70d80b76ded0ec79ba12b846945b54/oauth2-server/spec/spec_helper.rb
oauth2-server/spec/spec_helper.rb
$LOAD_PATH.unshift(File.expand_path( File.join('..', '..', 'oauth2-core', 'lib'), File.dirname(__FILE__) )) require "rubygems" begin require "bundler" Bundler.setup rescue LoadError => e puts 'Bundler not found. Please install bundler with the command gem install bundler' end begin require 'rspec' require 'rspec/autorun' rescue LoadError => e puts 'RSpec not found. Please install rspec with command bundle install' end require 'oauth2/server' Dir.glob(File.dirname(__FILE__) + "/support/**/*.rb").each do |file| require file end Rspec.configure do |config| config.debug = true # == Mock Framework # # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line: # # config.mock_with :mocha # config.mock_with :flexmock # config.mock_with :rr # config.mock_with :rspec end
ruby
MIT
bba05bc4fa70d80b76ded0ec79ba12b846945b54
2026-01-04T17:51:03.115784Z
false
aflatter/oauth2-ruby
https://github.com/aflatter/oauth2-ruby/blob/bba05bc4fa70d80b76ded0ec79ba12b846945b54/oauth2-server/lib/oauth2/server.rb
oauth2-server/lib/oauth2/server.rb
require 'oauth2/core' module OAuth2 module Server # autoload :Flows, 'oauth2/server/flows' # autoload :Rails, 'oauth2/server/rails' # autoload :Request, 'oauth2/server/request' end end
ruby
MIT
bba05bc4fa70d80b76ded0ec79ba12b846945b54
2026-01-04T17:51:03.115784Z
false
aflatter/oauth2-ruby
https://github.com/aflatter/oauth2-ruby/blob/bba05bc4fa70d80b76ded0ec79ba12b846945b54/oauth2-core/spec/attributes_spec.rb
oauth2-core/spec/attributes_spec.rb
require 'spec_helper' require 'oauth2/attributes' describe OAuth2::Attributes do subject do klass = Class.new do include OAuth2::Attributes attributes :foo end klass.new end it "should allow to set an attribute to nil" do subject.foo = nil subject.foo.should be_nil end it "should call user defined block if it is registered" do foo = stub("some value") subject.foo { foo } subject.foo.should == foo end it "should return user defined value if defined" do foo = stub("some value") subject.foo = foo subject.foo.should == foo end it "should raise exception if no callback or value is defined" do lambda { subject.foo }.should raise_error(RuntimeError) end end
ruby
MIT
bba05bc4fa70d80b76ded0ec79ba12b846945b54
2026-01-04T17:51:03.115784Z
false
aflatter/oauth2-ruby
https://github.com/aflatter/oauth2-ruby/blob/bba05bc4fa70d80b76ded0ec79ba12b846945b54/oauth2-core/spec/spec_helper.rb
oauth2-core/spec/spec_helper.rb
require "rubygems" require "bundler" Bundler.setup require 'oauth2/core' require 'rspec' require 'rspec/autorun' Dir.glob(File.dirname(__FILE__) + "/support/**/*.rb").each do |file| require file end Rspec.configure do |config| # == Mock Framework # # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line: # # config.mock_with :mocha # config.mock_with :flexmock # config.mock_with :rr # config.mock_with :rspec end
ruby
MIT
bba05bc4fa70d80b76ded0ec79ba12b846945b54
2026-01-04T17:51:03.115784Z
false
aflatter/oauth2-ruby
https://github.com/aflatter/oauth2-ruby/blob/bba05bc4fa70d80b76ded0ec79ba12b846945b54/oauth2-core/spec/headers/authorization_spec.rb
oauth2-core/spec/headers/authorization_spec.rb
require 'spec_helper' require 'oauth2/headers/authorization' describe OAuth2::Headers::Authorization do it "should parse a real world cryptographic example" do example = <<-EOS Token token="vF9dft4qmT", nonce="s8djwd", timestamp="137131200", algorithm="hmac-sha256", signature="wOJIO9A2W5mFwDgiDvZbTSMK/PY=" EOS header = OAuth2::Headers::Authorization.parse(example) header.token.should == "vF9dft4qmT" header.nonce.should == "s8djwd" header.timestamp.should == "137131200" header.algorithm.should == "hmac-sha256" header.signature.should == "wOJIO9A2W5mFwDgiDvZbTSMK/PY=" end it "should parse a real world bearer example" do example = 'Token token="vF9dft4qmT"' header = OAuth2::Headers::Authorization.parse(example) header.token.should == "vF9dft4qmT" end it "returns attributes in order" do attributes = OAuth2::Headers::Authorization::Attributes subject.attributes.should be_a(ActiveSupport::OrderedHash) subject.attributes.keys.should == attributes end it "ignores parameters without value using the parse method" do example_with_empty_value = <<-EOS Token token="vF9dft4qmT", nonce="" EOS example_without_empty_value = <<-EOS Token token="vF9dft4qmT" EOS OAuth2::Headers::Authorization.parse(example_with_empty_value).to_s.should == OAuth2::Headers::Authorization.parse(example_without_empty_value).to_s end it "ignores parameters without value using the new method" do OAuth2::Headers::Authorization.new(:token => "vF9dft4qmT", :signature => "").to_s.should == OAuth2::Headers::Authorization.new(:token => "vF9dft4qmT").to_s end it "builds a header string" end
ruby
MIT
bba05bc4fa70d80b76ded0ec79ba12b846945b54
2026-01-04T17:51:03.115784Z
false
aflatter/oauth2-ruby
https://github.com/aflatter/oauth2-ruby/blob/bba05bc4fa70d80b76ded0ec79ba12b846945b54/oauth2-core/spec/headers/authenticate_spec.rb
oauth2-core/spec/headers/authenticate_spec.rb
require 'spec_helper' require 'oauth2/headers/authenticate' describe OAuth2::Headers::Authenticate do end
ruby
MIT
bba05bc4fa70d80b76ded0ec79ba12b846945b54
2026-01-04T17:51:03.115784Z
false
aflatter/oauth2-ruby
https://github.com/aflatter/oauth2-ruby/blob/bba05bc4fa70d80b76ded0ec79ba12b846945b54/oauth2-core/lib/oauth2/attributes.rb
oauth2-core/lib/oauth2/attributes.rb
require 'active_support/concern' require 'active_support/core_ext/class/inheritable_attributes' module OAuth2 module Attributes extend ActiveSupport::Concern included do class_inheritable_array :attribute_names self.attribute_names = Array.new end def attributes @attributes ||= Hash.new end module ClassMethods # Defines a callback for a handle. def attribute(handle) attribute_names << handle.to_sym class_eval(<<-EOS, __FILE__, __LINE__ + 1) def #{handle}(&block) @attributes ||= {} if block_given? @attributes[:#{handle}] = block return end if @attributes.key?(:#{handle}) value = @attributes[:#{handle}] value.is_a?(Proc) ? value.call : value else raise "No attribute or callback for '#{handle}' defined" end end def #{handle.to_s.gsub('?', '')}=(value) @attributes ||= {} @attributes[:#{handle}] = value end EOS end def attributes(*handles) handles.each do |handle| attribute(handle) end end end end end
ruby
MIT
bba05bc4fa70d80b76ded0ec79ba12b846945b54
2026-01-04T17:51:03.115784Z
false
aflatter/oauth2-ruby
https://github.com/aflatter/oauth2-ruby/blob/bba05bc4fa70d80b76ded0ec79ba12b846945b54/oauth2-core/lib/oauth2/core.rb
oauth2-core/lib/oauth2/core.rb
module OAuth2 autoload :Headers, 'oauth2/headers' autoload :Signature, 'oauth2/signature' end
ruby
MIT
bba05bc4fa70d80b76ded0ec79ba12b846945b54
2026-01-04T17:51:03.115784Z
false
aflatter/oauth2-ruby
https://github.com/aflatter/oauth2-ruby/blob/bba05bc4fa70d80b76ded0ec79ba12b846945b54/oauth2-core/lib/oauth2/headers.rb
oauth2-core/lib/oauth2/headers.rb
module OAuth2 module Headers autoload :Authorization, 'oauth2/headers/authorization' autoload :Authenticate, 'oauth2/headers/authenticate' end end
ruby
MIT
bba05bc4fa70d80b76ded0ec79ba12b846945b54
2026-01-04T17:51:03.115784Z
false
aflatter/oauth2-ruby
https://github.com/aflatter/oauth2-ruby/blob/bba05bc4fa70d80b76ded0ec79ba12b846945b54/oauth2-core/lib/oauth2/headers/authenticate.rb
oauth2-core/lib/oauth2/headers/authenticate.rb
require 'oauth2/attributes' module OAuth2 module Headers class Authenticate Attributes = [ :realm, :algorithms, :auth_uri, :token_uri, :error ] Attributes.each do |attribute| attr_accessor attribute end def valid? raise "Realm not set" unless realm end def to_hash Attributes.inject(Hash.new) do |hash, attribute| value = send(attribute) hash[attribute] = value unless value.nil? hash end end def to_s to_hash.collect do |key, value| name = key.to_s.gsub('_', '-') "#{name}='#{value}'" end.join(",\n ") end end end end
ruby
MIT
bba05bc4fa70d80b76ded0ec79ba12b846945b54
2026-01-04T17:51:03.115784Z
false
aflatter/oauth2-ruby
https://github.com/aflatter/oauth2-ruby/blob/bba05bc4fa70d80b76ded0ec79ba12b846945b54/oauth2-core/lib/oauth2/headers/authorization.rb
oauth2-core/lib/oauth2/headers/authorization.rb
require 'oauth2/attributes' require 'active_support/ordered_hash' module OAuth2 module Headers class Authorization def initialize(attributes = {}) attributes.each_pair do |key, value| if Attributes.include?(key.to_sym) && !value.empty? instance_variable_set("@#{key}", value) end end end # These attributes are expected to be contained in the header Attributes = [ :token, :nonce, :timestamp, :algorithm, :signature ] Attributes.each do |attribute| attr_accessor(attribute) end def validate case request_type when :bearer @errors << :bearer_request_requires_token unless token when :cryptographic %w{nonce timestamp algorithm signature}.each do |attribute| unless instance_variable_get("@#{attribute}") error = "cryptographic_request_requires_#{attribute}".to_sym @errors << error end end end @errors.blank? end def errors @errors ||= [] end def attributes hash = ActiveSupport::OrderedHash.new Attributes.each do |attribute| hash[attribute] = instance_variable_get("@#{attribute}") end hash end def to_s attrs = attributes.collect do |key, value| %{#{key}="#{value}"} if value end.compact "Token " + attrs.join(",\n ") end class << self # This method does what it is named after. Give it a String and it # returns a Hash. The header specification can be found on: # http://tools.ietf.org/html/draft-hammer-oauth2-00#section-5.1 # TODO: Verify that token is the first attribute. def parse(string) header = new string.strip! type, tuples = string[0..4], string[5..-1].split("\n") unless type == "Token" header.errors << :format_invalid return header end tuples.map! { |tuple| tuple.strip! } tuples.each do |tuple| # Parameters sent without a value MUST be treated as if they were # omitted from the request. # http://tools.ietf.org/html/draft-ietf-oauth-v2-09#page-18 unless tuple =~ /\s*(.+)="(.*)"/ header.errors << :format_invalid else key, value = $1.to_sym, $2 next if value.empty? unless Attributes.include?(key) header.errors << "unknown_attribute_#{key}".to_sym else header.send("#{key}=".to_sym, value) end end end header end end end end end
ruby
MIT
bba05bc4fa70d80b76ded0ec79ba12b846945b54
2026-01-04T17:51:03.115784Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot.rb
slack-gamebot.rb
ENV['RACK_ENV'] ||= 'development' require 'bundler/setup' Bundler.require :default, ENV.fetch('RACK_ENV', nil) Dir[File.expand_path('config/initializers', __dir__) + '/**/*.rb'].each do |file| require file end Mongoid.load! File.expand_path('config/mongoid.yml', __dir__), ENV.fetch('RACK_ENV', nil) require 'slack-gamebot/error' require 'slack-gamebot/version' require 'slack-gamebot/info' require 'slack-gamebot/models' require 'slack-gamebot/api' require 'slack-gamebot/app' require 'slack-gamebot/server' require 'slack-gamebot/service' require 'slack-gamebot/commands'
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/tasks/logger.rb
tasks/logger.rb
def logger @logger ||= begin $stdout.sync = true Logger.new(STDOUT) end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/spec_helper.rb
spec/spec_helper.rb
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..')) require 'fabrication' require 'faker' require 'hyperclient' require 'webmock/rspec' ENV['RACK_ENV'] = 'test' require 'slack-ruby-bot/rspec' require 'slack-gamebot' Dir[File.join(File.dirname(__FILE__), 'support', '**/*.rb')].each do |file| require file end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/initializers/array_spec.rb
spec/initializers/array_spec.rb
require 'spec_helper' describe Array do describe '.and' do it 'one' do expect(['foo'].and).to eq 'foo' end it 'two' do expect(%w[foo bar].and).to eq 'foo and bar' end it 'three' do expect(%w[foo bar baz].and).to eq 'foo, bar and baz' end end describe '.or' do it 'one' do expect(['foo'].or).to eq 'foo' end it 'two' do expect(%w[foo bar].or).to eq 'foo or bar' end it 'three' do expect(%w[foo bar baz].or).to eq 'foo, bar or baz' end end describe '.same?' do it 'empty' do expect([].same?).to be false end it 'one' do expect([1].same?).to be true end it 'two' do expect([1, 1].same?).to be true expect([1, 2].same?).to be false end it 'three' do expect([2, 2, 2].same?).to be true expect([1, 2, 3].same?).to be false end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/initializers/giphy_spec.rb
spec/initializers/giphy_spec.rb
require 'spec_helper' describe Giphy, :js, type: :feature do context 'with GIPHY_API_KEY' do before do ENV['GIPHY_API_KEY'] = 'key' end after do ENV.delete('GIPHY_API_KEY') end it 'returns a random gif', vcr: { cassette_name: 'giphy_random' } do expect(Giphy.random('bot')).to eq 'https://media4.giphy.com/media/QAPGorQJSoarrsjVhH/200.gif' end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/support/capybara.rb
spec/support/capybara.rb
require 'capybara/rspec' Capybara.configure do |config| config.app = Api::Middleware.instance config.server_port = 9293 config.server = :puma end module Capybara module Node class Element def client_set(value) driver.browser.execute_script("$(arguments[0]).val('#{value}');", native) end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/support/vcr.rb
spec/support/vcr.rb
require 'vcr' VCR.configure do |config| config.cassette_library_dir = 'spec/fixtures/slack' config.hook_into :webmock # config.default_cassette_options = { record: :new_episodes } config.configure_rspec_metadata! config.ignore_localhost = true end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/support/mongoid.rb
spec/support/mongoid.rb
RSpec.configure do |config| config.before :suite do Mongoid.logger.level = Logger::INFO Mongo::Logger.logger.level = Logger::INFO Mongoid::Tasks::Database.create_indexes end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/support/database_cleaner.rb
spec/support/database_cleaner.rb
require 'database_cleaner-mongoid' RSpec.configure do |config| config.before :suite do DatabaseCleaner.strategy = :deletion DatabaseCleaner.clean_with :deletion end config.after :suite do Mongoid.purge! end config.around do |example| DatabaseCleaner.cleaning do example.run end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/support/new_relic.rb
spec/support/new_relic.rb
require 'new_relic/agent' RSpec.configure do |config| config.before :suite do NewRelic::Agent.manual_start end config.after :suite do FileUtils.rm_rf File.expand_path('log/newrelic_agent.log') end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/support/stripe.rb
spec/support/stripe.rb
RSpec.shared_context 'stripe mock' do let(:stripe_helper) { StripeMock.create_test_helper } before do StripeMock.start end after do StripeMock.stop end end RSpec.configure do |config| config.before do allow(Stripe).to receive(:api_key).and_return('key') end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/support/api/endpoints/endpoint_test.rb
spec/support/api/endpoints/endpoint_test.rb
module Api module Test module EndpointTest extend ActiveSupport::Concern include Rack::Test::Methods included do let(:client) do Hyperclient.new('http://example.org/api/') do |client| client.headers = { 'Content-Type' => 'application/json', 'Accept' => 'application/json,application/hal+json' } client.connection(default: false) do |conn| conn.request :json conn.response :json conn.use Faraday::Response::RaiseError conn.use Faraday::FollowRedirects::Middleware conn.adapter Faraday::Adapter::Rack, app end end end end def app Api::Middleware.instance end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/support/api/endpoints/it_behaves_like_a_cursor_api.rb
spec/support/api/endpoints/it_behaves_like_a_cursor_api.rb
shared_examples_for 'a cursor api' do |model| let(:model_s) { model.name.underscore.to_sym } let(:model_ps) { model.name.underscore.pluralize.to_sym } context model.name do let(:cursor_params) { @cursor_params || {} } before do 12.times { Fabricate(model_s) } end it 'returns all items by default' do expect(client.send(model_ps, cursor_params).count).to eq 12 end it 'returns a first page with a cursor' do response = client.send(model_ps, cursor_params.merge(size: 2)) expect(response._links.self._url).to eq "http://example.org/api/#{model_ps}/?#{cursor_params.merge(size: 2).to_query}" expect(response._links.next._url).to start_with "http://example.org/api/#{model_ps}/?" expect(response._links.next._url).to match(/cursor=.*%3A\h*/) end it 'paginates over the entire collection' do models_ids = [] next_cursor = { size: 3 } loop do response = client.send(model_ps, next_cursor.merge(cursor_params)) models_ids.concat(response.map { |instance| instance._links.self._url.gsub("http://example.org/api/#{model_ps}/", '') }) break unless response._links[:next] next_cursor = CGI.parse(URI.parse(response._links.next._url).query).map { |a| [a[0], a[1][0]] }.to_h end expect(models_ids.uniq.count).to eq model.all.count end it 'allows skipping of results via an offset query param' do models_ids = [] next_cursor = { size: 3, offset: 3 } loop do response = client.send(model_ps, next_cursor.merge(cursor_params)) models_ids.concat(response.map { |instance| instance._links.self._url.gsub("http://example.org/api/#{model_ps}/", '') }) break unless response._links[:next] next_cursor = CGI.parse(URI.parse(response._links.next._url).query).map { |a| [a[0], a[1][0]] }.to_h end expect(models_ids.uniq.count).to eq model.all.count - 3 end context 'total count' do it "doesn't return total_count" do response = client.send(model_ps, cursor_params) expect(response).not_to respond_to(:total_count) end it 'returns total_count when total_count query string is specified' do response = client.send(model_ps, cursor_params.merge(total_count: true)) expect(response.total_count).to eq model.all.count end end it 'returns all unique ids' do instances = client.send(model_ps, cursor_params) expect(instances.map(&:id).uniq.count).to eq 12 end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/integration/update_cc_spec.rb
spec/integration/update_cc_spec.rb
require 'spec_helper' describe 'Update cc', :js, type: :feature do context 'with a stripe key' do before do ENV['STRIPE_API_PUBLISHABLE_KEY'] = 'pk_test_804U1vUeVeTxBl8znwriXskf' end after do ENV.delete 'STRIPE_API_PUBLISHABLE_KEY' end context 'a game' do let!(:game) { Fabricate(:game, name: 'pong') } context 'a team with a stripe customer ID' do let!(:team) { Fabricate(:team, game:, stripe_customer_id: 'stripe_customer_id') } it 'updates cc' do visit "/update_cc?team_id=#{team.team_id}&game=#{team.game.name}" expect(find('h3')).to have_text('PLAYPLAY.IO: UPDATE CREDIT CARD INFO') customer = double expect(Stripe::Customer).to receive(:retrieve).and_return(customer) expect(customer).to receive(:source=) expect(customer).to receive(:save) click_button 'Update Credit Card' sleep 1 stripe_iframe = all('iframe[name=stripe_checkout_app]').last Capybara.within_frame stripe_iframe do page.find_field('Email').set 'foo@bar.com' page.find_field('Card number').client_set '4012 8888 8888 1881' page.find_field('MM / YY').client_set '12/42' page.find_field('CVC').set '345' find('button[type="submit"]').click end sleep 5 expect(find_by_id('messages')).to have_text("Successfully updated team #{team.name} credit card for #{team.game.name}.\nThank you!") end end [ Faker::Lorem.word, "#{Faker::Lorem.word}'s", '💥 team', 'команда', "\"#{Faker::Lorem.word}'s\"", "#{Faker::Lorem.word}\n#{Faker::Lorem.word}", "<script>alert('xss');</script>", '<script>alert("xss");</script>' ].each do |team_name| context "team #{team_name}" do let!(:team) { Fabricate(:team, name: team_name, stripe_customer_id: 'stripe_customer_id') } it 'displays update cc page' do visit "/update_cc?team_id=#{team.team_id}&game=#{team.game.name}" expect(find('h3')).to have_text('PLAYPLAY.IO: UPDATE CREDIT CARD INFO') expect(find_by_id('messages')).to have_text("Update credit card for team #{team.name.gsub("\n", ' ')}.") end end end context 'a team without a stripe customer ID' do let!(:team) { Fabricate(:team, game:, stripe_customer_id: nil) } it 'displays error' do visit "/update_cc?team_id=#{team.team_id}&game=#{team.game.name}" expect(find('h3')).to have_text('PLAYPLAY.IO: UPDATE CREDIT CARD INFO') click_button 'Update Credit Card' sleep 1 stripe_iframe = all('iframe[name=stripe_checkout_app]').last Capybara.within_frame stripe_iframe do page.find_field('Email').set 'foo@bar.com' page.find_field('Card number').client_set '4012 8888 8888 1881' page.find_field('MM / YY').client_set '12/42' page.find_field('CVC').set '345' find('button[type="submit"]').click end sleep 5 expect(find_by_id('messages')).to have_text('Not a Subscriber') end end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/integration/subscribe_spec.rb
spec/integration/subscribe_spec.rb
require 'spec_helper' describe 'Subscribe', :js, type: :feature do let!(:game) { Fabricate(:game, name: 'pong') } context 'without team_id' do before do visit '/subscribe' end it 'requires a team' do expect(find_by_id('messages')).to have_text('Missing or invalid team ID and/or game.') find_by_id('subscribe', visible: false) end end context 'without game' do let!(:team) { Fabricate(:team) } before do visit "/subscribe?team_id=#{team.team_id}" end it 'requires a game' do expect(find_by_id('messages')).to have_text('Missing or invalid team ID and/or game.') find_by_id('subscribe', visible: false) end end context 'for a subscribed team' do let!(:team) { Fabricate(:team, game:, subscribed: true) } before do visit "/subscribe?team_id=#{team.team_id}&game=#{team.game.name}" end it 'displays an error' do expect(find_by_id('messages')).to have_text("Team #{team.name} is already subscribed to #{team.game.name}, thank you.") find_by_id('subscribe', visible: false) end end [ Faker::Lorem.word, "#{Faker::Lorem.word}'s", '💥 team', 'команда', "\"#{Faker::Lorem.word}'s\"", "#{Faker::Lorem.word}\n#{Faker::Lorem.word}", "<script>alert('xss');</script>", '<script>alert("xss");</script>' ].each do |team_name| context "team #{team_name}" do let!(:team) { Fabricate(:team, name: team_name) } it 'displays subscribe page' do visit "/subscribe?team_id=#{team.team_id}&game=#{team.game.name}" expect(find_by_id('messages')).to have_text("Subscribe team #{team.name.gsub("\n", ' ')} to #{team.game.name} for $29.99/yr.") end end end shared_examples 'subscribes' do it 'subscribes' do visit "/subscribe?team_id=#{team.team_id}&game=#{team.game.name}" expect(find_by_id('messages')).to have_text("Subscribe team #{team.name} to #{team.game.name} for $29.99/yr.") find_by_id('subscribe', visible: true) expect(Stripe::Customer).to receive(:create).and_return('id' => 'customer_id') find_by_id('subscribeButton').click sleep 1 expect_any_instance_of(Team).to receive(:inform!).with(Team::SUBSCRIBED_TEXT, 'thanks') stripe_iframe = all('iframe[name=stripe_checkout_app]').last Capybara.within_frame stripe_iframe do page.find_field('Email').set 'foo@bar.com' page.find_field('Card number').client_set '4242 4242 4242 4242' page.find_field('MM / YY').client_set '12/42' page.find_field('CVC').set '123' find('button[type="submit"]').click end sleep 5 expect(find_by_id('messages')).to have_text("Team #{team.name} successfully subscribed to #{team.game.name}.\nThank you!") find_by_id('subscribe', visible: false) team.reload expect(team.subscribed).to be true expect(team.stripe_customer_id).to eq 'customer_id' end end context 'with a stripe key' do before do ENV['STRIPE_API_PUBLISHABLE_KEY'] = 'pk_test_804U1vUeVeTxBl8znwriXskf' end after do ENV.delete 'STRIPE_API_PUBLISHABLE_KEY' end context 'a team' do let!(:team) { Fabricate(:team, game:) } it_behaves_like 'subscribes' end context 'a team with two games' do let!(:team) { Fabricate(:team, game:) } let!(:team2) { Fabricate(:team, team_id: team.team_id, game: Fabricate(:game)) } it_behaves_like 'subscribes' end context 'a second team with two games' do let!(:team2) { Fabricate(:team, game: Fabricate(:game)) } let!(:team) { Fabricate(:team, game:, team_id: team2.team_id) } it_behaves_like 'subscribes' end context 'with a coupon' do let!(:team) { Fabricate(:team, game:) } it 'applies the coupon' do coupon = double(Stripe::Coupon, id: 'coupon-id', amount_off: 1200) expect(Stripe::Coupon).to receive(:retrieve).with('coupon-id').and_return(coupon) visit "/subscribe?team_id=#{team.team_id}&game=#{team.game.name}&coupon=coupon-id" expect(find_by_id('messages')).to have_text("Subscribe team #{team.name} to #{team.game.name} for $17.99 for the first year and $29.99 thereafter with coupon coupon-id!") find_by_id('subscribe', visible: true) expect(Stripe::Customer).to receive(:create).with(hash_including(coupon: 'coupon-id')).and_return('id' => 'customer_id') expect_any_instance_of(Team).to receive(:inform!).with(Team::SUBSCRIBED_TEXT, 'thanks') find_by_id('subscribeButton').click sleep 1 stripe_iframe = all('iframe[name=stripe_checkout_app]').last Capybara.within_frame stripe_iframe do page.find_field('Email').set 'foo@bar.com' page.find_field('Card number').client_set '4242 4242 4242 4242' page.find_field('MM / YY').client_set '12/42' page.find_field('CVC').set '123' find('button[type="submit"]').click end sleep 5 expect(find_by_id('messages')).to have_text("Team #{team.name} successfully subscribed to #{team.game.name}.\nThank you!") find_by_id('subscribe', visible: false) team.reload expect(team.subscribed).to be true expect(team.stripe_customer_id).to eq 'customer_id' end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/integration/privacy_spec.rb
spec/integration/privacy_spec.rb
require 'spec_helper' describe 'privacy.html', :js, type: :feature do before do visit '/privacy' end it 'displays privacy.html page' do expect(title).to eq('PlayPlay.io - Privacy Policy') end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/integration/index_spec.rb
spec/integration/index_spec.rb
require 'spec_helper' describe 'index.html', :js, type: :feature do let!(:game) { Fabricate(:game, name: 'pong') } context 'v1' do before do visit '/?version=1' end it 'includes a link to add to slack with the client id' do expect(title).to eq('PlayPlay.io - Ping Pong Bot, Chess Bot, Pool Bot and Tic Tac Toe Bot for Slack') click_link 'Add to Slack' expect(first('a[class=add-to-slack]')['href']).to eq "https://slack.com/oauth/authorize?scope=bot&client_id=#{game.client_id}" end end context 'v2' do before do visit '/' end it 'redirects' do expect(current_url).to eq('https://gamebot2.playplay.io/') end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/integration/teams_spec.rb
spec/integration/teams_spec.rb
require 'spec_helper' describe 'Teams', :js, type: :feature do context 'oauth', vcr: { cassette_name: 'auth_test' } do before do Fabricate(:game, name: 'pong') end it 'registers a team' do allow_any_instance_of(Team).to receive(:ping!).and_return(ok: true) expect(SlackRubyBotServer::Service.instance).to receive(:start!) oauth_access = { 'bot' => { 'bot_access_token' => 'token' }, 'team_id' => 'team_id', 'team_name' => 'team_name' } allow_any_instance_of(Slack::Web::Client).to receive(:oauth_access).with(hash_including(code: 'code')).and_return(oauth_access) expect do visit '/?code=code&game=pong' expect(page.find_by_id('messages')).to have_content 'Team successfully registered!' end.to change(Team, :count).by(1) end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/models/season_spec.rb
spec/models/season_spec.rb
require 'spec_helper' describe Season do let!(:team) { Fabricate(:team) } context 'with challenges' do let!(:open_challenge) { Fabricate(:challenge) } let!(:matches) { Array.new(3) { Fabricate(:match) } } let!(:season) { Fabricate(:season, team:) } it 'archives challenges' do expect(season.challenges.count).to eq 4 end it 'cancels open challenges' do expect(open_challenge.reload.state).to eq ChallengeState::CANCELED end it 'resets users' do expect(User.all.detect { |u| u.wins != 0 || u.losses != 0 }).to be_nil end it 'saves user ranks' do expect(season.user_ranks.count).to eq 6 end it 'to_s' do expect(season.to_s).to eq "#{season.created_at.strftime('%F')}: #{season.winners.map(&:to_s).and}, 3 matches, 6 players" end end context 'without challenges' do let!(:team) { Fabricate(:team) } let(:season) { Season.new(team:) } it 'cannot be created' do expect(season).not_to be_valid expect(season.errors.messages).to eq(challenges: ['No matches have been recorded.']) end it 'to_s' do expect(season.to_s).to eq 'Current: n/a, 0 matches, 0 players' end end context 'without challenges and a lost match' do let!(:team) { Fabricate(:team) } let(:challenger) { Fabricate(:user, team:) } let(:challenged) { Fabricate(:user, team:) } let(:season) { Season.new(team:) } before do Match.lose!(team:, winners: [challenger], losers: [challenged]) end it 'can be created' do expect(season).to be_valid end it 'to_s' do expect(season.to_s).to eq "Current: #{season.winners.map(&:to_s).and}, 1 match, 2 players" end it 'has one winner' do expect(season.winners.count).to eq 1 end end context 'current season with one match' do let!(:match) { Fabricate(:match) } let(:season) { Season.new(team:) } it 'to_s' do expect(season.to_s).to eq "Current: #{season.winners.map(&:to_s).and}, 1 match, 2 players" end it 'has one winner' do expect(season.winners.count).to eq 1 end end context 'current season with multiple matches and one winner' do let(:user) { Fabricate(:user, team:) } let!(:matches) { Array.new(3) { Fabricate(:match, challenge: Fabricate(:challenge, challengers: [user])) } } let(:season) { Season.new(team:) } it 'to_s' do expect(season.to_s).to eq "Current: #{season.winners.map(&:to_s).and}, 3 matches, 4 players" end it 'has one winner' do expect(season.winners.count).to eq 1 expect(season.winners.first.wins).to eq 3 end context 'with an unplayed challenge' do before do Fabricate(:challenge) end it 'only counts played matches' do expect(season.to_s).to eq "Current: #{season.winners.map(&:to_s).and}, 3 matches, 4 players" end end end context 'current season with two winners' do let!(:matches) { Array.new(2) { Fabricate(:match, team:) } } let!(:matches) { Array.new(2) { Fabricate(:match, team:) } } let(:season) { Season.new(team:) } it 'has two winners' do expect(season.winners.count).to eq 2 expect(season.winners.map(&:wins).uniq).to eq([1]) end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/models/match_spec.rb
spec/models/match_spec.rb
require 'spec_helper' describe Match do describe '#to_s' do let(:match) { Fabricate(:match) } it 'displays match' do expect(match.to_s).to eq "#{match.winners.first.user_name} defeated #{match.losers.first.user_name} with #{Score.scores_to_string(match.scores)}" end context 'unregistered users' do before do match.winners.first.unregister! end it 'removes user name' do expect(match.to_s).to eq "<unregistered> defeated #{match.losers.first.user_name} with #{Score.scores_to_string(match.scores)}" end end context 'user with nickname' do before do match.winners.first.update_attributes!(nickname: 'bob') end it 'rewrites user name' do expect(match.to_s).to eq "bob defeated #{match.losers.first.user_name} with #{Score.scores_to_string(match.scores)}" end end end context 'elo' do context 'singles' do let(:match) { Fabricate(:match) } it 'updates elo and tau' do expect(match.winners.map(&:elo)).to eq [48] expect(match.winners.map(&:tau)).to eq [0.5] expect(match.losers.map(&:elo)).to eq [-48] expect(match.losers.map(&:tau)).to eq [0.5] end it 'updates streaks' do expect(match.winners.map(&:winning_streak)).to eq [1] expect(match.winners.map(&:losing_streak)).to eq [0] expect(match.losers.map(&:winning_streak)).to eq [0] expect(match.losers.map(&:losing_streak)).to eq [1] end end context 'singles tied' do let(:match) { Fabricate(:match, tied: true) } it 'updates elo and tau' do expect(match.winners.map(&:elo)).to eq [0.0] expect(match.winners.map(&:tau)).to eq [0.5] expect(match.losers.map(&:elo)).to eq [0.0] expect(match.losers.map(&:tau)).to eq [0.5] end it 'updates streaks' do expect(match.winners.map(&:winning_streak)).to eq [0] expect(match.winners.map(&:losing_streak)).to eq [0] expect(match.losers.map(&:winning_streak)).to eq [0] expect(match.losers.map(&:losing_streak)).to eq [0] end end context 'two consecutive losses' do let!(:match) { Fabricate(:match) } before do Fabricate(:match, winners: match.winners, losers: match.losers) end it 'updates streaks' do expect(match.winners.map(&:winning_streak)).to eq [2] expect(match.winners.map(&:losing_streak)).to eq [0] expect(match.losers.map(&:winning_streak)).to eq [0] expect(match.losers.map(&:losing_streak)).to eq [2] end end context 'three consecutive losses, then a break for losers preserves losing streak' do let!(:match) { Fabricate(:match) } before do 2.times { Fabricate(:match, winners: match.winners, losers: match.losers) } Fabricate(:match, winners: match.losers) end it 'updates streaks' do expect(match.winners.map(&:winning_streak)).to eq [3] expect(match.winners.map(&:losing_streak)).to eq [0] expect(match.losers.map(&:winning_streak)).to eq [1] expect(match.losers.map(&:losing_streak)).to eq [3] end end context 'after (MAX_TAU * 2) games' do let!(:match) { Fabricate(:match) } before do (Elo::MAX_TAU * 2).times { Fabricate(:match, winners: match.winners, losers: match.losers) } end it 'caps tau at MAX_TAU' do expect(match.winners.map(&:tau)).to eq [Elo::MAX_TAU] expect(match.losers.map(&:tau)).to eq [Elo::MAX_TAU] end end context 'doubles' do let(:match) { Fabricate(:match, challenge: Fabricate(:doubles_challenge)) } it 'updates elo and tau' do expect(match.winners.map(&:elo)).to eq [48, 48] expect(match.winners.map(&:tau)).to eq [0.5, 0.5] expect(match.losers.map(&:elo)).to eq [-48, -48] expect(match.losers.map(&:tau)).to eq [0.5, 0.5] end it 'updates streaks' do expect(match.winners.map(&:winning_streak)).to eq [1, 1] expect(match.winners.map(&:losing_streak)).to eq [0, 0] expect(match.losers.map(&:winning_streak)).to eq [0, 0] expect(match.losers.map(&:losing_streak)).to eq [1, 1] end end context 'two matches against previous losers' do let(:challenge1) { Fabricate(:doubles_challenge) } let(:challengers) { challenge1.challengers } let(:challenged) { [Fabricate(:user), Fabricate(:user)] } let(:match) { Fabricate(:match, challenge: Fabricate(:challenge, challengers:, challenged:)) } before do challenge1.accept!(challenge1.challenged.first) challenge1.lose!(challenge1.challengers.first) end it 'updates elo and tau' do expect(match.winners.map(&:elo)).to eq [5, 5] expect(match.winners.map(&:tau)).to eq [1, 1] expect(match.losers.map(&:elo)).to eq [-55, -55] expect(match.losers.map(&:tau)).to eq [0.5, 0.5] end it 'updates streaks' do expect(match.winners.map(&:winning_streak)).to eq [1, 1] expect(match.winners.map(&:losing_streak)).to eq [1, 1] expect(match.losers.map(&:winning_streak)).to eq [0, 0] expect(match.losers.map(&:losing_streak)).to eq [1, 1] end end context 'a tie against previous losers' do let(:challenge1) { Fabricate(:doubles_challenge) } let(:challengers) { challenge1.challengers } let(:challenged) { [Fabricate(:user), Fabricate(:user)] } let(:match) { Fabricate(:match, challenge: Fabricate(:challenge, challengers:, challenged:), tied: true) } before do challenge1.accept!(challenge1.challenged.first) challenge1.lose!(challenge1.challengers.first) end it 'updates elo and tau' do expect(match.winners.map(&:elo)).to eq [-21, -21] expect(match.winners.map(&:tau)).to eq [1, 1] expect(match.losers.map(&:elo)).to eq [-27, -27] expect(match.losers.map(&:tau)).to eq [0.5, 0.5] end it 'updates streaks' do expect(match.winners.map(&:winning_streak)).to eq [0, 0] expect(match.winners.map(&:losing_streak)).to eq [1, 1] expect(match.losers.map(&:winning_streak)).to eq [0, 0] expect(match.losers.map(&:losing_streak)).to eq [0, 0] end end context 'a tie against previous winners' do let(:challenge1) { Fabricate(:doubles_challenge) } let(:challengers) { challenge1.challengers } let(:challenged) { [Fabricate(:user), Fabricate(:user)] } let(:match) { Fabricate(:match, challenge: Fabricate(:challenge, challengers:, challenged:), tied: true) } before do challenge1.accept!(challenge1.challenged.first) challenge1.lose!(challenge1.challenged.first) end it 'updates elo and tau' do expect(match.winners.map(&:elo)).to eq [68, 68] expect(match.winners.map(&:tau)).to eq [1, 1] expect(match.losers.map(&:elo)).to eq [-20, -20] expect(match.losers.map(&:tau)).to eq [0.5, 0.5] end it 'updates streaks' do expect(match.winners.map(&:winning_streak)).to eq [1, 1] expect(match.winners.map(&:losing_streak)).to eq [0, 0] expect(match.losers.map(&:winning_streak)).to eq [0, 0] expect(match.losers.map(&:losing_streak)).to eq [0, 0] end end context 'two matches against previous winners' do let(:challenge1) { Fabricate(:doubles_challenge) } let(:challengers) { challenge1.challenged } let(:challenged) { [Fabricate(:user), Fabricate(:user)] } let(:match) { Fabricate(:match, challenge: Fabricate(:challenge, challengers:, challenged:)) } before do challenge1.accept!(challenge1.challenged.first) challenge1.lose!(challenge1.challengers.first) end it 'updates elo and tau' do expect(match.winners.map(&:elo)).to eq [88, 88] expect(match.winners.map(&:tau)).to eq [1, 1] expect(match.losers.map(&:elo)).to eq [-41, -41] expect(match.losers.map(&:tau)).to eq [0.5, 0.5] end end context 'scores' do let!(:team) { Fabricate(:team) } it 'loser first' do expect(Match.new(team:, scores: [[15, 21]])).to be_valid end it 'loser first with 3 scores' do expect(Match.new(team:, scores: [[15, 21], [21, 5], [3, 11]])).to be_valid end it 'winner first' do expect(Match.new(team:, scores: [[21, 15]])).not_to be_valid end it 'winner first with 3 scores' do expect(Match.new(team:, scores: [[21, 15], [5, 21], [11, 3]])).not_to be_valid end it 'draw' do expect(Match.new(team:, tied: true, scores: [[15, 15]])).to be_valid end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/models/team_spec.rb
spec/models/team_spec.rb
require 'spec_helper' describe Team do let!(:game) { Fabricate(:game) } describe '#find_or_create_from_env!' do before do ENV['SLACK_API_TOKEN'] = 'token' end after do ENV.delete 'SLACK_API_TOKEN' end context 'team', vcr: { cassette_name: 'team_info' } do it 'creates a team' do expect { Team.find_or_create_from_env! }.to change(Team, :count).by(1) team = Team.first expect(team.team_id).to eq 'T04KB5WQH' expect(team.name).to eq 'dblock' expect(team.domain).to eq 'dblockdotorg' expect(team.token).to eq 'token' expect(team.game).to eq game end end end describe '#destroy' do let!(:team) { Fabricate(:team) } let!(:match) { Fabricate(:match, team:) } let!(:season) { Fabricate(:season, team:) } it 'destroys dependent records' do expect(Team.count).to eq 1 expect(User.count).to eq 2 expect(Challenge.count).to eq 1 expect(Match.count).to eq 1 expect(Season.count).to eq 1 expect do expect do expect do expect do expect do team.destroy end.to change(Team, :count).by(-1) end.to change(User, :count).by(-2) end.to change(Challenge, :count).by(-1) end.to change(Match, :count).by(-1) end.to change(Season, :count).by(-1) end end describe '#purge!' do let!(:active_team) { Fabricate(:team) } let!(:inactive_team) { Fabricate(:team, active: false) } let!(:inactive_team_a_week_ago) { Fabricate(:team, updated_at: 1.week.ago, active: false) } let!(:inactive_team_two_weeks_ago) { Fabricate(:team, updated_at: 2.weeks.ago, active: false) } let!(:inactive_team_a_month_ago) { Fabricate(:team, updated_at: 1.month.ago, active: false) } it 'destroys teams inactive for two weeks' do expect do Team.purge! end.to change(Team, :count).by(-2) expect(Team.find(active_team.id)).to eq active_team expect(Team.find(inactive_team.id)).to eq inactive_team expect(Team.find(inactive_team_a_week_ago.id)).to eq inactive_team_a_week_ago expect(Team.find(inactive_team_two_weeks_ago.id)).to be_nil expect(Team.find(inactive_team_a_month_ago.id)).to be_nil end end describe '#dead? and #asleep?' do context 'default' do let(:team) { Fabricate(:team) } it 'false' do expect(team.asleep?).to be false expect(team.dead?).to be false end end context 'team created three weeks ago' do let(:team) { Fabricate(:team, created_at: 3.weeks.ago) } it 'dead=false' do expect(team.asleep?).to be true expect(team.dead?).to be false end context 'with a recent challenge' do let!(:challenge) { Fabricate(:challenge, team:) } it 'false' do expect(team.asleep?).to be false expect(team.dead?).to be false end end context 'with a recent match' do let!(:match) { Fabricate(:match, team:) } it 'false' do expect(team.asleep?).to be false expect(team.dead?).to be false end end context 'with a recent match lost to' do let!(:match) { Fabricate(:match_lost_to, team:) } it 'false' do expect(team.asleep?).to be false expect(team.dead?).to be false end end context 'with an old challenge' do let!(:challenge) { Fabricate(:challenge, updated_at: 3.weeks.ago, team:) } it 'true' do expect(team.asleep?).to be true expect(team.dead?).to be false end end end context 'team created over a month ago' do let(:team) { Fabricate(:team, created_at: 32.days.ago) } it 'dead=true' do expect(team.dead?).to be true end context 'with a recent challenge' do let!(:challenge) { Fabricate(:challenge, updated_at: 2.weeks.ago, team:) } it 'true' do expect(team.dead?).to be false end end context 'with an old challenge' do let!(:challenge) { Fabricate(:challenge, updated_at: 5.weeks.ago, team:) } it 'true' do expect(team.dead?).to be true end end end end context 'gifs' do let!(:team) { Fabricate(:team) } context 'with a played challenge' do let(:challenge) { Fabricate(:played_challenge) } context 'with a new challenge' do let!(:open_challenge) { Fabricate(:challenge, challengers: challenge.challengers, challenged: challenge.challenged) } it 'can be set' do expect(team.challenges.detect { |c| !c.valid? }).to be_nil expect { team.update_attributes!(gifs: !team.gifs) }.not_to raise_error end end end end context 'subscribed states' do let(:today) { DateTime.parse('2018/7/15 12:42pm') } let(:subscribed_team) { Fabricate(:team, subscribed: true) } let(:team_created_today) { Fabricate(:team, created_at: today) } let(:team_created_1_week_ago) { Fabricate(:team, created_at: (today - 1.week)) } let(:team_created_3_weeks_ago) { Fabricate(:team, created_at: (today - 3.weeks)) } before do Timecop.travel(today + 1.day) end after do Timecop.return end it 'subscription_expired?' do expect(subscribed_team.subscription_expired?).to be false expect(team_created_1_week_ago.subscription_expired?).to be false expect(team_created_3_weeks_ago.subscription_expired?).to be true end it 'trial_ends_at' do expect { subscribed_team.trial_ends_at }.to raise_error 'Team is subscribed.' expect(team_created_today.trial_ends_at).to eq team_created_today.created_at + 2.weeks expect(team_created_1_week_ago.trial_ends_at).to eq team_created_1_week_ago.created_at + 2.weeks expect(team_created_3_weeks_ago.trial_ends_at).to eq team_created_3_weeks_ago.created_at + 2.weeks end it 'remaining_trial_days' do expect { subscribed_team.remaining_trial_days }.to raise_error 'Team is subscribed.' expect(team_created_today.remaining_trial_days).to eq 13 expect(team_created_1_week_ago.remaining_trial_days).to eq 6 expect(team_created_3_weeks_ago.remaining_trial_days).to eq 0 end describe '#inform_trial!' do it 'subscribed' do expect(subscribed_team).not_to receive(:inform!) expect(subscribed_team).not_to receive(:inform_admin!) subscribed_team.inform_trial! end it '1 week ago' do expect(team_created_1_week_ago).to receive(:inform!).with( "Your trial subscription expires in 6 days. #{team_created_1_week_ago.subscribe_text}" ) expect(team_created_1_week_ago).to receive(:inform_admin!).with( "Your trial subscription expires in 6 days. #{team_created_1_week_ago.subscribe_text}" ) team_created_1_week_ago.inform_trial! end it 'expired' do expect(team_created_3_weeks_ago).not_to receive(:inform!) expect(team_created_3_weeks_ago).not_to receive(:inform_admin!) team_created_3_weeks_ago.inform_trial! end it 'informs once' do expect(team_created_1_week_ago).to receive(:inform!).once expect(team_created_1_week_ago).to receive(:inform_admin!).once 2.times { team_created_1_week_ago.inform_trial! } end end end describe '#inform!' do let(:team) { Fabricate(:team) } before do team.bot_user_id = 'bot_user_id' end it 'sends message to all channels', vcr: { cassette_name: 'users_conversations' } do expect_any_instance_of(Slack::Web::Client).to receive(:chat_postMessage).exactly(25).times.and_return('ts' => '1503435956.000247') team.inform!(message: 'message') end end describe '#activated' do pending 'DMs installing user when activated' end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/models/challenge_spec.rb
spec/models/challenge_spec.rb
require 'spec_helper' describe Challenge do describe '#to_s' do let(:challenge) { Fabricate(:challenge) } it 'displays challenge' do expect(challenge.to_s).to eq "a challenge between #{challenge.challengers.first.user_name} and #{challenge.challenged.first.user_name}" end context 'unregistered users' do before do challenge.challengers.first.unregister! end it 'removes user name' do expect(challenge.to_s).to eq "a challenge between <unregistered> and #{challenge.challenged.first.user_name}" end end context 'users with nickname' do before do challenge.challengers.first.update_attributes!(nickname: 'bob') end it 'rewrites user name' do expect(challenge.to_s).to eq "a challenge between bob and #{challenge.challenged.first.user_name}" end end end context 'find_by_user' do let(:challenge) { Fabricate(:challenge) } it 'finds a challenge by challenger' do challenge.challengers.each do |challenger| expect(Challenge.find_by_user(challenge.team, challenge.channel, challenger)).to eq challenge end end it 'finds a challenge by challenged' do challenge.challenged.each do |challenger| expect(Challenge.find_by_user(challenge.team, challenge.channel, challenger)).to eq challenge end end it 'does not find a challenge on another channel' do expect(Challenge.find_by_user(challenge.team, 'another', challenge.challengers.first)).to be_nil end end describe '#split_teammates_and_opponents', vcr: { cassette_name: 'user_info' } do let!(:challenger) { Fabricate(:user) } let(:client) { SlackRubyBot::Client.new } before do client.owner = challenger.team end it 'splits a single challenge' do opponent = Fabricate(:user, user_name: 'username') challengers, opponents = Challenge.split_teammates_and_opponents(client, challenger, ['username']) expect(challengers).to eq([challenger]) expect(opponents).to eq([opponent]) end it 'splits a double challenge' do teammate = Fabricate(:user) opponent1 = Fabricate(:user, user_name: 'username') opponent2 = Fabricate(:user) challengers, opponents = Challenge.split_teammates_and_opponents(client, challenger, ['username', opponent2.slack_mention, 'with', teammate.slack_mention]) expect(challengers).to eq([challenger, teammate]) expect(opponents).to eq([opponent1, opponent2]) end it 'requires known opponents' do allow(client.web_client).to receive(:users_info) expect do Challenge.split_teammates_and_opponents(client, challenger, ['username']) end.to raise_error SlackGamebot::Error, "I don't know who username is! Ask them to _register_." end end describe '#create_from_teammates_and_opponents!' do let!(:challenger) { Fabricate(:user) } let(:teammate) { Fabricate(:user) } let(:opponent) { Fabricate(:user) } let(:client) { SlackRubyBot::Client.new } before do client.owner = challenger.team end it 'requires an opponent' do expect do Challenge.create_from_teammates_and_opponents!(client, 'channel', challenger, []) end.to raise_error Mongoid::Errors::Validations, /Number of teammates \(1\) and opponents \(0\) must match./ end it 'requires the same number of opponents' do expect do Challenge.create_from_teammates_and_opponents!(client, 'channel', challenger, [opponent.slack_mention, 'with', teammate.slack_mention]) end.to raise_error Mongoid::Errors::Validations, /Number of teammates \(2\) and opponents \(1\) must match./ end context 'with unbalanced option enabled' do before do challenger.team.update_attributes!(unbalanced: true) end it 'requires an opponent' do expect do Challenge.create_from_teammates_and_opponents!(client, 'channel', challenger, []) end.to raise_error Mongoid::Errors::Validations, /Number of teammates \(1\) and opponents \(0\) must match./ end it 'does not requires the same number of opponents' do expect do Challenge.create_from_teammates_and_opponents!(client, 'channel', challenger, [opponent.slack_mention, 'with', teammate.slack_mention]) end.not_to raise_error end end it 'requires another opponent' do expect do Challenge.create_from_teammates_and_opponents!(client, 'channel', challenger, [challenger.slack_mention]) end.to raise_error Mongoid::Errors::Validations, /#{challenger.user_name} cannot play against themselves./ end it 'uniques opponents mentioned multiple times' do expect do Challenge.create_from_teammates_and_opponents!(client, 'channel', challenger, [opponent.slack_mention, opponent.slack_mention, 'with', teammate.slack_mention]) end.to raise_error Mongoid::Errors::Validations, /Number of teammates \(2\) and opponents \(1\) must match./ end context 'with another singles proposed challenge' do let(:challenge) { Fabricate(:challenge) } it 'cannot create a duplicate challenge for the challenger' do existing_challenger = challenge.challengers.first expect do Challenge.create_from_teammates_and_opponents!(client, challenge.channel, challenger, [existing_challenger.slack_mention]) end.to raise_error Mongoid::Errors::Validations, /#{existing_challenger.user_name} can't play./ end it 'cannot create a duplicate challenge for the challenge' do existing_challenger = challenge.challenged.first expect do Challenge.create_from_teammates_and_opponents!(client, challenge.channel, challenger, [existing_challenger.slack_mention]) end.to raise_error Mongoid::Errors::Validations, /#{existing_challenger.user_name} can't play./ end end context 'with another doubles proposed challenge' do let(:challenge) { Fabricate(:challenge, challengers: [Fabricate(:user), Fabricate(:user)], challenged: [Fabricate(:user), Fabricate(:user)]) } it 'cannot create a duplicate challenge for the challenger' do existing_challenger = challenge.challengers.last expect do Challenge.create_from_teammates_and_opponents!(client, challenge.channel, challenger, [existing_challenger.slack_mention]) end.to raise_error Mongoid::Errors::Validations, /#{existing_challenger.user_name} can't play./ end end end describe '#accept!' do let(:challenge) { Fabricate(:challenge) } it 'can be accepted' do accepted_by = challenge.challenged.first challenge.accept!(accepted_by) expect(challenge.updated_by).to eq accepted_by expect(challenge.state).to eq ChallengeState::ACCEPTED end it 'requires accepted_by' do challenge.state = ChallengeState::ACCEPTED expect(challenge).not_to be_valid end it 'cannot be accepted by another player' do expect do challenge.accept!(challenge.challengers.first) end.to raise_error Mongoid::Errors::Validations, /Only #{challenge.challenged.map(&:user_name).or} can accept this challenge./ end it 'cannot be accepted twice' do accepted_by = challenge.challenged.first challenge.accept!(accepted_by) expect do challenge.accept!(accepted_by) end.to raise_error SlackGamebot::Error, /Challenge has already been accepted./ end end describe '#decline!' do let(:challenge) { Fabricate(:challenge) } it 'can be declined' do declined_by = challenge.challenged.first challenge.decline!(declined_by) expect(challenge.updated_by).to eq declined_by expect(challenge.state).to eq ChallengeState::DECLINED end it 'requires declined_by' do challenge.state = ChallengeState::DECLINED expect(challenge).not_to be_valid end it 'cannot be declined by another player' do expect do challenge.decline!(challenge.challengers.first) end.to raise_error Mongoid::Errors::Validations, /Only #{challenge.challenged.map(&:user_name).or} can decline this challenge./ end it 'cannot be declined twice' do declined_by = challenge.challenged.first challenge.decline!(declined_by) expect do challenge.decline!(declined_by) end.to raise_error SlackGamebot::Error, /Challenge has already been declined./ end end describe '#cancel!' do let(:challenge) { Fabricate(:challenge) } it 'can be canceled by challenger' do canceled_by = challenge.challengers.first challenge.cancel!(canceled_by) expect(challenge.updated_by).to eq canceled_by expect(challenge.state).to eq ChallengeState::CANCELED end it 'can be canceled by challenged' do canceled_by = challenge.challenged.first challenge.cancel!(canceled_by) expect(challenge.updated_by).to eq canceled_by expect(challenge.state).to eq ChallengeState::CANCELED end it 'requires canceled_by' do challenge.state = ChallengeState::CANCELED expect(challenge).not_to be_valid end it 'cannot be canceled_by by another player' do player = Fabricate(:user) expect do challenge.cancel!(player) end.to raise_error Mongoid::Errors::Validations, /Only #{challenge.challengers.map(&:display_name).and} or #{challenge.challenged.map(&:display_name).and} can cancel this challenge./ end it 'cannot be canceled_by twice' do canceled_by = challenge.challengers.first challenge.cancel!(canceled_by) expect do challenge.cancel!(canceled_by) end.to raise_error SlackGamebot::Error, /Challenge has already been canceled./ end end describe '#lose!' do let(:challenge) { Fabricate(:challenge) } before do challenge.accept!(challenge.challenged.first) end it 'can be lost by the challenger' do expect do challenge.lose!(challenge.challengers.first) end.to change(Match, :count).by(1) game = Match.last expect(game.challenge).to eq challenge expect(game.winners).to eq challenge.challenged expect(game.losers).to eq challenge.challengers expect(game.winners.all? { |player| player.wins == 1 && player.losses == 0 }).to be true expect(game.losers.all? { |player| player.wins == 0 && player.losses == 1 }).to be true end it 'can be lost by the challenged' do expect do challenge.lose!(challenge.challenged.first) end.to change(Match, :count).by(1) game = Match.last expect(game.challenge).to eq challenge expect(game.winners).to eq challenge.challengers expect(game.losers).to eq challenge.challenged expect(game.winners.all? { |player| player.wins == 1 && player.losses == 0 }).to be true expect(game.losers.all? { |player| player.wins == 0 && player.losses == 1 }).to be true end end describe '#draw!' do let(:challenge) { Fabricate(:challenge) } before do challenge.accept!(challenge.challenged.first) end it 'requires both sides to draw' do expect do challenge.draw!(challenge.challengers.first) end.not_to change(Match, :count) expect do challenge.draw!(challenge.challenged.first) end.to change(Match, :count).by(1) game = Match.last expect(game.tied?).to be true expect(game.challenge).to eq challenge expect(game.winners).to eq challenge.challengers expect(game.losers).to eq challenge.challenged expect(game.winners.all? { |player| player.wins == 0 && player.losses == 0 && player.ties == 1 }).to be true expect(game.losers.all? { |player| player.wins == 0 && player.losses == 0 && player.ties == 1 }).to be true end end context 'a new challenge' do let(:played_challenge) { Fabricate(:played_challenge) } let(:new_challenge) { Fabricate(:challenge, challengers: played_challenge.challengers, challenged: played_challenge.challenged) } it 'does not render the played challenge invalid' do expect(new_challenge).to be_valid expect(played_challenge).to be_valid end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/models/game_spec.rb
spec/models/game_spec.rb
require 'spec_helper' describe Game do describe '#find_or_create_from_env!' do before do ENV['SLACK_CLIENT_ID'] = 'slack_client_id' ENV['SLACK_CLIENT_SECRET'] = 'slack_client_secret' ENV['SLACK_RUBY_BOT_ALIASES'] = 'pp :pong:' end after do ENV.delete 'SLACK_CLIENT_ID' ENV.delete 'SLACK_CLIENT_SECRET' ENV.delete 'SLACK_RUBY_BOT_ALIASES' end context 'game' do it 'creates a game' do expect { Game.find_or_create_from_env! }.to change(Game, :count).by(1) game = Game.first expect(game.name).to be_nil expect(game.client_id).to eq 'slack_client_id' expect(game.client_secret).to eq 'slack_client_secret' expect(game.aliases).to eq(['pp', ':pong:']) end end end describe '#destroy' do let!(:game) { Fabricate(:game) } it 'can destroy a game' do expect do game.destroy end.to change(Game, :count).by(-1) end context 'with teams' do let!(:team) { Fabricate(:team, game:) } it 'cannot destroy a game that has teams' do expect do expect do game.destroy end.to raise_error 'The game has teams and cannot be destroyed.' end.not_to change(Game, :count) end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/models/score_spec.rb
spec/models/score_spec.rb
require 'spec_helper' describe Score do describe '#points' do it 'returns losing and winning points for one score' do expect(Score.points([[15, 21]])).to eq [15, 21] end it 'returns losing and winning points for mulitple scores' do expect(Score.points([[15, 21], [11, 9]])).to eq [26, 30] end end describe '#valid?' do it 'loser first' do expect(Score.valid?([[15, 21]])).to be true end it 'loser first with 3 scores' do expect(Score.valid?([[15, 21], [21, 5], [3, 11]])).to be true end it 'winner first' do expect(Score.valid?([[21, 15]])).to be false end it 'winner first with 3 scores' do expect(Score.valid?([[21, 15], [5, 21], [11, 3]])).to be false end end describe '#tie?' do it 'tie with the same number of points' do expect(Score.tie?([[15, 15]])).to be true end it 'tie with different number of points' do expect(Score.tie?([[21, 15]])).to be false end it 'tie with multiple same number of points' do expect(Score.tie?([[15, 14], [14, 15]])).to be true end it 'tie with multiple different number of points' do expect(Score.tie?([[21, 15], [15, 14]])).to be false end end describe '#parse' do it 'nil' do expect(Score.parse(nil)).to be_nil end it 'x:y' do expect { Score.parse('x:y') }.to raise_error SlackGamebot::Error, 'Invalid score: x:y, invalid value for Integer(): "x".' end it '-1:5' do expect { Score.parse('-1:5') }.to raise_error SlackGamebot::Error, 'Invalid score: -1:5, points must be greater or equal to zero.' end it '21:0' do expect(Score.parse('21:0')).to eq [[21, 0]] end it '5:3' do expect(Score.parse('5:3')).to eq [[5, 3]] end it '5-3' do expect(Score.parse('5-3')).to eq [[5, 3]] end it '5:3 9:11' do expect(Score.parse('5:3 9:11')).to eq [[5, 3], [9, 11]] end it '5:3, 9:11.' do expect(Score.parse('5:3, 9:11.')).to eq [[5, 3], [9, 11]] end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/models/user_rank_spec.rb
spec/models/user_rank_spec.rb
require 'spec_helper' describe UserRank do describe '#from_user' do it 'creates a record' do user = Fabricate(:user) user_rank = UserRank.from_user(user) expect(user_rank.user).to eq user expect(user_rank.user_name).to eq user.user_name expect(user_rank.wins).to eq user.wins expect(user_rank.losses).to eq user.losses expect(user_rank.tau).to eq user.tau expect(user_rank.elo).to eq user.elo expect(user_rank.elo_history).to eq user.elo_history expect(user_rank.rank).to eq user.rank end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/models/elo_spec.rb
spec/models/elo_spec.rb
require 'spec_helper' describe Elo do describe '#team_elo' do it 'is rounded average of elo' do expect(Elo.team_elo([User.new(elo: 1)])).to eq 1 expect(Elo.team_elo([User.new(elo: 1), User.new(elo: 2)])).to eq 1.5 expect(Elo.team_elo([User.new(elo: 3), User.new(elo: 3), User.new(elo: 4)])).to eq 3.33 end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/models/user_spec.rb
spec/models/user_spec.rb
require 'spec_helper' describe User do let(:team) { Fabricate(:team) } describe '#find_by_slack_mention!' do let(:web_client) { double(Slack::Web::Client, users_info: nil) } let(:client) { double(Slack::RealTime::Client, owner: team, web_client:) } let!(:user) { Fabricate(:user, team:, nickname: 'bob') } it 'finds by slack id' do expect(User.find_by_slack_mention!(client, "<@#{user.user_id}>")).to eq user end it 'finds by username' do expect(User.find_by_slack_mention!(client, user.user_name)).to eq user end it 'finds by username is case-insensitive' do expect(User.find_by_slack_mention!(client, user.user_name.capitalize)).to eq user end it 'requires a known user' do expect do User.find_by_slack_mention!(client, '<@nobody>') end.to raise_error SlackGamebot::Error, "I don't know who <@nobody> is! Ask them to _register_." end it 'finds by nickname' do expect(User.find_by_slack_mention!(client, user.nickname)).to eq user end %w[here channel].each do |name| it "always finds #{name}" do mention = "<!#{name}>" expect do 3.times do expect(User.find_by_slack_mention!(client, mention)).to be_a User end end.to change(User, :count).by(1) end end end context 'with a mismatching user id in slack_mention' do let!(:user) { Fabricate(:user, team:, nickname: 'bob') } let(:web_client) { double(Slack::Web::Client, users_info: { user: { id: user.user_id, name: user.user_name } }) } let(:client) { double(Slack::RealTime::Client, owner: team, web_client:) } it 'finds by different slack id returned from slack info' do expect(User.find_by_slack_mention!(client, '<@unknown>')).to eq user end end describe '#find_many_by_slack_mention!' do let(:web_client) { double(Slack::Web::Client, users_info: nil) } let(:client) { double(Slack::RealTime::Client, owner: team, web_client:) } let!(:users) { [Fabricate(:user, team:), Fabricate(:user, team:)] } it 'finds by slack_id or slack_mention' do results = User.find_many_by_slack_mention!(client, [users.first.user_name, users.last.slack_mention]) expect(results).to match_array(users) end it 'requires known users' do expect do User.find_many_by_slack_mention!(client, %w[foo bar]) end.to raise_error SlackGamebot::Error, "I don't know who foo is! Ask them to _register_." end end describe '#find_create_or_update_by_slack_id!', vcr: { cassette_name: 'user_info' } do let(:client) { SlackRubyBot::Client.new } before do client.owner = team end context 'without a user' do it 'creates a user' do expect do user = User.find_create_or_update_by_slack_id!(client, 'U42') expect(user).not_to be_nil expect(user.user_id).to eq 'U42' expect(user.user_name).to eq 'username' end.to change(User, :count).by(1) end end context 'with a user' do let!(:user) { Fabricate(:user, team:) } it 'creates another user' do expect do User.find_create_or_update_by_slack_id!(client, 'U42') end.to change(User, :count).by(1) end it 'updates the username of the existing user' do expect do User.find_create_or_update_by_slack_id!(client, user.user_id) end.not_to change(User, :count) expect(user.reload.user_name).to eq 'username' end end end describe '#to_s' do let(:user) { Fabricate(:user, elo: 48, team: Fabricate(:team, elo: 2)) } it 'respects team elo' do expect(user.to_s).to include 'elo: 50' end context 'unregistered user' do before do user.update_attributes!(registered: false) end it 'hides name' do expect(user.to_s).to eq '<unregistered>: 0 wins, 0 losses (elo: 50)' end end context 'user with nickname' do before do user.update_attributes!(nickname: 'bob') end it 'rewrites user name' do expect(user.to_s).to eq 'bob: 0 wins, 0 losses (elo: 50)' end end context 'with a longest winning streak >= 3' do before do user.update_attributes!(winning_streak: 3) end it 'displays lws' do expect(user.to_s).to eq "#{user.user_name}: 0 wins, 0 losses (elo: 50, lws: 3)" end end context 'equal streaks' do before do user.update_attributes!(winning_streak: 5, losing_streak: 5) end it 'prefers winning streak' do expect(user.to_s).to eq "#{user.user_name}: 0 wins, 0 losses (elo: 50, lws: 5)" end end context 'with a longest losing streak >= 3' do before do user.update_attributes!(losing_streak: 3, winning_streak: 2) end it 'displays lls' do expect(user.to_s).to eq "#{user.user_name}: 0 wins, 0 losses (elo: 50, lls: 3)" end end end describe '#reset_all' do it 'resets all user stats' do user1 = Fabricate(:user, elo: 48, losses: 1, wins: 2, ties: 3, tau: 0.5) user2 = Fabricate(:user, elo: 54, losses: 2, wins: 1, tau: 1.5) User.reset_all!(user1.team) user1.reload user2.reload expect(user1.wins).to eq 0 expect(user1.losses).to eq 0 expect(user1.ties).to eq 0 expect(user1.tau).to eq 0 expect(user1.elo).to eq 0 expect(user1.rank).to be_nil expect(user1.winning_streak).to eq 0 expect(user1.losing_streak).to eq 0 expect(user1.elo_history).to eq [] expect(user2.wins).to eq 0 expect(user2.losses).to eq 0 expect(user2.ties).to eq 0 expect(user2.tau).to eq 0 expect(user2.elo).to eq 0 expect(user2.rank).to be_nil expect(user2.winning_streak).to eq 0 expect(user2.losing_streak).to eq 0 expect(user2.elo_history).to eq [] end end describe '#rank!' do it 'updates when elo changes' do user = Fabricate(:user) expect(user.rank).to be_nil user.update_attributes!(elo: 65, wins: 1) expect(user.rank).to eq 1 end it 'stores elo history' do user = Fabricate(:user) user.update_attributes!(elo: 65, wins: 1) expect(user.elo_history).to eq [0, 65] user.update_attributes!(elo: 45, wins: 2) expect(user.elo_history).to eq [0, 65, 45] end it 'ranks four players' do user1 = Fabricate(:user, elo: 100, wins: 4, losses: 0) user2 = Fabricate(:user, elo: 40, wins: 1, losses: 1) user3 = Fabricate(:user, elo: 60, wins: 2, losses: 0) user4 = Fabricate(:user, elo: 80, wins: 3, losses: 0) expect(user1.reload.rank).to eq 1 expect(user2.reload.rank).to eq 4 expect(user3.reload.rank).to eq 3 expect(user4.reload.rank).to eq 2 end it 'ranks players with the same elo and different wins' do user1 = Fabricate(:user, elo: 40, wins: 1, losses: 0) user2 = Fabricate(:user, elo: 40, wins: 4, losses: 0) expect(user1.reload.rank).to eq 2 expect(user2.reload.rank).to eq 1 end it 'ranks players with the same elo, wins and losses and different ties' do user1 = Fabricate(:user, elo: 40, wins: 1, losses: 0, ties: 0) user2 = Fabricate(:user, elo: 40, wins: 1, losses: 0, ties: 1) expect(user1.reload.rank).to eq 2 expect(user2.reload.rank).to eq 1 end it 'ranks players with the same elo and wins/losses equally' do user1 = Fabricate(:user, elo: 1, wins: 1, losses: 1) user2 = Fabricate(:user, elo: 2, wins: 1, losses: 1) expect(user1.rank).to eq 1 expect(user1.rank).to eq user2.rank end it 'is updated for all users' do user1 = Fabricate(:user, elo: 65, wins: 1) expect(user1.rank).to eq 1 user2 = Fabricate(:user, elo: 75, wins: 2) expect(user1.reload.rank).to eq 2 expect(user2.rank).to eq 1 user1.update_attributes!(elo: 100, wins: 3) expect(user1.rank).to eq 1 expect(user2.reload.rank).to eq 2 end it 'does not rank unregistered users' do user1 = Fabricate(:user, elo: 40, wins: 1, losses: 0, registered: false) user2 = Fabricate(:user, elo: 40, wins: 4, losses: 0) expect(user1.reload.rank).to be_nil expect(user2.reload.rank).to eq 1 end end describe '.ranked' do it 'returns an empty list' do expect(User.ranked).to eq [] end it 'ignores players without rank' do user1 = Fabricate(:user, elo: 1, wins: 1, losses: 1) Fabricate(:user) expect(User.ranked).to eq [user1] end end describe '.rank_section' do let(:team) { Fabricate(:team) } it 'returns a section' do user1 = Fabricate(:user, team:, elo: 100, wins: 4, losses: 0) user2 = Fabricate(:user, team:, elo: 40, wins: 1, losses: 1) user3 = Fabricate(:user, team:, elo: 60, wins: 2, losses: 0) user4 = Fabricate(:user, team:, elo: 80, wins: 3, losses: 0) [user1, user2, user3, user4].each(&:reload) expect(User.rank_section(team, [user1])).to eq [user1] expect(User.rank_section(team, [user1, user3])).to eq [user1, user4, user3] expect(User.rank_section(team, [user1, user3, user4])).to eq [user1, user4, user3] end it 'limits by team' do user = Fabricate(:user, elo: 100, wins: 4, losses: 0) expect(User.rank_section(Fabricate(:team), [user])).to eq [] end it 'only returns one unranked user' do user1 = Fabricate(:user, team:) user2 = Fabricate(:user, team:) expect(User.rank_section(team, [user1])).to eq [user1] expect(User.rank_section(team, [user1, user2])).to eq [user1, user2] end end describe '#calculate_streaks!' do let(:user) { Fabricate(:user) } it 'is 0 by default' do expect(user.winning_streak).to eq 0 expect(user.losing_streak).to eq 0 end it 'is 0 without matches' do user.calculate_streaks! expect(user.winning_streak).to eq 0 expect(user.losing_streak).to eq 0 end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/api/swagger_documentation_spec.rb
spec/api/swagger_documentation_spec.rb
require 'spec_helper' describe Api do include Api::Test::EndpointTest context 'swagger root' do subject do get '/api/swagger_doc' JSON.parse(last_response.body) end it 'documents root level apis' do expect(subject['paths'].keys.sort).to eq [ '/api/status', '/api/users/{id}', '/api/users', '/api/challenges/{id}', '/api/challenges', '/api/matches/{id}', '/api/matches', '/api/seasons/current', '/api/seasons/{id}', '/api/seasons', '/api/teams/{id}', '/api/teams', '/api/games/{id}', '/api/games', '/api/subscriptions', '/api/credit_cards' ].sort end end context 'users' do subject do get '/api/swagger_doc/users' JSON.parse(last_response.body) end it 'documents users apis' do expect(subject['paths'].keys.sort).to eq [ '/api/users/{id}', '/api/users' ].sort end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/api/cors_spec.rb
spec/api/cors_spec.rb
require 'spec_helper' describe Api do include Api::Test::EndpointTest context 'CORS' do it 'supports options' do options '/', {}, 'HTTP_ORIGIN' => 'http://cors.example.com', 'HTTP_ACCESS_CONTROL_REQUEST_HEADERS' => 'Origin, Accept, Content-Type', 'HTTP_ACCESS_CONTROL_REQUEST_METHOD' => 'GET' expect(last_response.status).to eq 200 expect(last_response.headers['Access-Control-Allow-Origin']).to eq '*' expect(last_response.headers['Access-Control-Expose-Headers']).to eq '' end it 'includes Access-Control-Allow-Origin in the response' do get '/api/', {}, 'HTTP_ORIGIN' => 'http://cors.example.com' expect(last_response.status).to eq 200 expect(last_response.headers['Access-Control-Allow-Origin']).to eq '*' end it 'includes Access-Control-Allow-Origin in errors' do get '/api/invalid', {}, 'HTTP_ORIGIN' => 'http://cors.example.com' expect(last_response.status).to eq 404 expect(last_response.headers['Access-Control-Allow-Origin']).to eq '*' end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/api/robots_spec.rb
spec/api/robots_spec.rb
require 'spec_helper' describe Api do include Api::Test::EndpointTest it 'returns a robots.txt that disallows indexing' do get '/robots.txt' expect(last_response.status).to eq 200 expect(last_response.headers['Content-Type']).to eq 'text/plain' expect(last_response.body).to eq "User-Agent: *\nDisallow: /api" end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/api/404_spec.rb
spec/api/404_spec.rb
require 'spec_helper' describe Api do include Api::Test::EndpointTest context '404' do it 'returns a plain 404' do get '/api/foobar' expect(last_response.status).to eq 404 expect(last_response.body).to eq '404 Not Found' end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/api/endpoints/status_endpoint_spec.rb
spec/api/endpoints/status_endpoint_spec.rb
require 'spec_helper' describe Api::Endpoints::StatusEndpoint do include Api::Test::EndpointTest before do allow_any_instance_of(Team).to receive(:ping!).and_return(ok: 1) end context 'status' do it 'returns a status' do status = client.status expect(status.games_count).to eq 0 end context 'with a team that is inactive' do let!(:team) { Fabricate(:team, api: true, active: false) } it 'returns a status' do status = client.status expect(status.games_count).to eq 1 game = status.games[team.game.name] expect(game['teams_count']).to eq 1 expect(game['active_teams_count']).to eq 0 expect(game['api_teams_count']).to eq 1 end end context 'with a team that has an inactive account' do let!(:team) { Fabricate(:team, api: true, active: true) } before do expect_any_instance_of(Team).to receive(:ping!) { raise Slack::Web::Api::Errors::SlackError, 'account_inactive' } end it 'returns a status and deactivates team' do status = client.status expect(status.games_count).to eq 1 game = status.games[team.game.name] expect(game['teams_count']).to eq 1 expect(game['active_teams_count']).to eq 1 expect(game['api_teams_count']).to eq 1 expect(team.reload.active).to be false end end context 'with a team with api off' do let!(:team) { Fabricate(:team, api: false) } it 'returns total counts anyway' do status = client.status expect(status.games_count).to eq 1 game = status.games[team.game.name] expect(game['teams_count']).to eq 1 expect(game['api_teams_count']).to eq 0 end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/api/endpoints/credit_cards_endpoint_spec.rb
spec/api/endpoints/credit_cards_endpoint_spec.rb
require 'spec_helper' describe Api::Endpoints::CreditCardsEndpoint do include Api::Test::EndpointTest context 'credit cards' do it 'requires stripe parameters' do expect { client.credit_cards._post }.to raise_error Faraday::ClientError do |e| json = JSON.parse(e.response[:body]) expect(json['message']).to eq 'Invalid parameters.' expect(json['type']).to eq 'param_error' end end context 'subscribed team without a stripe customer id' do let!(:team) { Fabricate(:team, subscribed: true, stripe_customer_id: nil) } it 'fails to update credit_card' do expect do client.credit_cards._post( team_id: team._id, stripe_token: 'token' ) end.to raise_error Faraday::ClientError do |e| json = JSON.parse(e.response[:body]) expect(json['error']).to eq 'Not a Subscriber' end end end context 'existing subscribed team' do include_context 'stripe mock' let!(:team) { Fabricate(:team) } before do stripe_helper.create_plan(id: 'slack-playplay-yearly', amount: 2999) customer = Stripe::Customer.create( source: stripe_helper.generate_card_token, plan: 'slack-playplay-yearly', email: 'foo@bar.com' ) expect_any_instance_of(Team).to receive(:inform!).once team.update_attributes!(subscribed: true, stripe_customer_id: customer['id']) end it 'updates a credit card' do new_source = stripe_helper.generate_card_token client.credit_cards._post( team_id: team._id, stripe_token: new_source, stripe_token_type: 'card' ) team.reload customer = Stripe::Customer.retrieve(team.stripe_customer_id) expect(customer.source).to eq new_source end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false