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
dalibor/octoshark
https://github.com/dalibor/octoshark/blob/0971743cb8e5c8eb2686f60188267d3549001503/spec/support/helpers.rb
spec/support/helpers.rb
require 'yaml' module Helpers def configs { db1: { adapter: "sqlite3", database: "tmp/db1.sqlite" }, db2: { adapter: "sqlite3", database: "tmp/db2.sqlite" } } end def mysql2_configs YAML.load_file('spec/support/config.yml').with_indifferent_access end def db(connection) case connection when ActiveRecord::ConnectionAdapters::SQLite3Adapter connection.execute('PRAGMA database_list').first['file'].split('/').last.split('.').first when ActiveRecord::ConnectionAdapters::Mysql2Adapter connection.instance_variable_get(:@config)[:database] end end end
ruby
MIT
0971743cb8e5c8eb2686f60188267d3549001503
2026-01-04T17:48:18.822915Z
false
dalibor/octoshark
https://github.com/dalibor/octoshark/blob/0971743cb8e5c8eb2686f60188267d3549001503/spec/octoshark/connection_pools_manager_spec.rb
spec/octoshark/connection_pools_manager_spec.rb
require 'spec_helper' describe Octoshark::ConnectionPoolsManager do describe "#initialize" do it "initializes connection manager with default connection" do manager = Octoshark::ConnectionPoolsManager.new expect(manager.connection_pools.length).to eq(0) expect(manager.connection_pools[:default]).to be_nil end it "initializes connection manager with custom connections" do manager = Octoshark::ConnectionPoolsManager.new(configs) expect(manager.connection_pools.length).to eq(2) expect(manager.connection_pools[:db1]).to be_an_instance_of(ActiveRecord::ConnectionAdapters::ConnectionPool) expect(manager.connection_pools[:db2]).to be_an_instance_of(ActiveRecord::ConnectionAdapters::ConnectionPool) end it "accepts configs with string keys" do configs = { 'db1' => { 'adapter' => "sqlite3", 'database' => "tmp/db1.sqlite" } } manager = Octoshark::ConnectionPoolsManager.new(configs) expect { manager.connection_pools[:db1].connection }.not_to raise_error end end describe '#find_connection_pool' do it "can find connection pool by name" do manager = Octoshark::ConnectionPoolsManager.new(configs) expect(manager.find_connection_pool(:db1)).to be_an_instance_of(ActiveRecord::ConnectionAdapters::ConnectionPool) end it "raises Octoshark::Error::NoConnection when no pool with that name" do manager = Octoshark::ConnectionPoolsManager.new({}) expect { manager.find_connection_pool(:invalid) }.to raise_error(Octoshark::Error::NoConnection) end end describe '#with_connection' do it "can use multiple connections" do manager = Octoshark::ConnectionPoolsManager.new(configs) manager.with_connection(:db1) do expect(db(manager.current_connection)).to eq("db1") end manager.with_connection(:db2) do expect(db(manager.current_connection)).to eq("db2") end end it "can nest connection" do manager = Octoshark::ConnectionPoolsManager.new(configs) manager.with_connection(:db1) do expect(db(manager.current_connection)).to eq("db1") manager.with_connection(:db2) do expect(db(manager.current_connection)).to eq("db2") end expect(db(manager.current_connection)).to eq("db1") end end it "returns value from execution" do manager = Octoshark::ConnectionPoolsManager.new(configs) result = manager.with_connection(:db1) { |connection| connection.execute("SELECT 1") } expect(result.first['1']).to eq(1) end it "raises Octoshark::Error::NoConnection" do manager = Octoshark::ConnectionPoolsManager.new({}) expect { manager.with_connection(:invalid) }.to raise_error(Octoshark::Error::NoConnection) end context "using specific database", mysql2: true do it "can use specific database" do manager = Octoshark::ConnectionPoolsManager.new(mysql2_configs) db1 = mysql2_configs[:db1]['database'] db2 = mysql2_configs[:db2]['database'] manager.with_connection(:db1, db1) do expect(db(manager.current_connection)).to eq(db1) manager.with_connection(:db2, db2) do expect(db(manager.current_connection)).to eq(db2) end expect(db(manager.current_connection)).to eq(db1) end end it "sets database name on the connection" do manager = Octoshark::ConnectionPoolsManager.new(mysql2_configs) db1 = mysql2_configs[:db1]['database'] manager.with_connection(:db1, db1) do |connection| expect(connection.database_name).to eq('octoshark_db1') end end it "returns value from execution" do manager = Octoshark::ConnectionPoolsManager.new(mysql2_configs) db1 = mysql2_configs[:db1]['database'] result = manager.with_connection(:db1, db1) { |connection| connection.execute("SELECT 1") }.to_a expect(result).to eq([[1]]) end end end describe "#disconnect!" do it "removes all connections from connection pools" do manager = Octoshark::ConnectionPoolsManager.new(configs) manager.with_connection(:db1) { |connection| connection.execute("SELECT 1") } expect(manager.find_connection_pool(:db1)).to be_connected manager.disconnect! expect(manager.find_connection_pool(:db1)).to_not be_connected end end describe ".reset!" do it "gets new connection pools ready to rock" do manager = Octoshark::ConnectionPoolsManager.new(configs) manager.with_connection(:db1) { |connection| connection.execute("SELECT 1") } expect(manager.connection_pools[:db1].connections.count).to eq(1) manager.reset! expect(manager.connection_pools[:db1].connections.count).to eq(0) manager.with_connection(:db1) { |connection| connection.execute("SELECT 1") } expect(manager.connection_pools[:db1].connections.count).to eq(1) end end describe ".reset_connection_managers!" do it "resets connection managers" do manager = Octoshark::ConnectionPoolsManager.new(configs) old_pools = manager.connection_pools.map(&:object_id) Octoshark::ConnectionPoolsManager.reset_connection_managers! new_pools = manager.connection_pools.map(&:object_id) expect(new_pools).to_not eq(old_pools) end end describe ".disconnect!" do it "disconnects connection managers" do manager = Octoshark::ConnectionPoolsManager.new(configs) Octoshark::ConnectionPoolsManager.disconnect! expect(Octoshark::ConnectionPoolsManager.connection_managers).to be_blank end it "cleans old connections" do manager = Octoshark::ConnectionPoolsManager.new(configs) manager.with_connection(:db1) { |connection| connection.execute("SELECT 1") } manager.with_connection(:db2) { |connection| connection.execute("SELECT 1") } expect(manager.connection_pools[:db1].connections.count).to eq(1) expect(manager.connection_pools[:db2].connections.count).to eq(1) Octoshark::ConnectionPoolsManager.disconnect! expect(manager.connection_pools[:db1].connections.count).to eq(0) expect(manager.connection_pools[:db2].connections.count).to eq(0) end end end
ruby
MIT
0971743cb8e5c8eb2686f60188267d3549001503
2026-01-04T17:48:18.822915Z
false
dalibor/octoshark
https://github.com/dalibor/octoshark/blob/0971743cb8e5c8eb2686f60188267d3549001503/spec/octoshark/active_record_extensions_spec.rb
spec/octoshark/active_record_extensions_spec.rb
require 'spec_helper' require 'logger' describe "ActiveRecord Extensions" do it "logs current connection name" do io = StringIO.new logger = Logger.new(io) ActiveRecord::Base.logger = logger manager = Octoshark::ConnectionPoolsManager.new(configs) manager.with_connection(:db1) do |connection| connection.execute("SELECT 1") end expect(io.string).to include('[Octoshark: db1]') ActiveRecord::Base.logger = nil end it "logs current database name", mysql2: true do io = StringIO.new logger = Logger.new(io) database_name = mysql2_configs[:db1][:database] ActiveRecord::Base.logger = logger manager = Octoshark::ConnectionPoolsManager.new(mysql2_configs) manager.with_connection(:db1, database_name) do |connection| connection.execute("SELECT 1") end expect(io.string).to include("[Octoshark: db1 #{database_name}]") ActiveRecord::Base.logger = nil end it "logs the connection name for the Octoshark connection only" do io = StringIO.new logger = Logger.new(io) ActiveRecord::Base.logger = logger manager = Octoshark::ConnectionPoolsManager.new(configs) manager.with_connection(:db1) do |connection| ActiveRecord::Base.connection.execute("SELECT 1") end expect(io.string).not_to include('[Octoshark: db1]') ActiveRecord::Base.logger = nil end end
ruby
MIT
0971743cb8e5c8eb2686f60188267d3549001503
2026-01-04T17:48:18.822915Z
false
dalibor/octoshark
https://github.com/dalibor/octoshark/blob/0971743cb8e5c8eb2686f60188267d3549001503/spec/octoshark/connection_manager_spec.rb
spec/octoshark/connection_manager_spec.rb
require 'spec_helper' describe Octoshark::ConnectionManager do describe "#with_connection", mysql2: true do it "creates temporary connection to database server" do manager = Octoshark::ConnectionManager.new connection_reference = nil config = mysql2_configs[:db1] manager.with_connection(config.except(:database)) do |connection| connection_reference = connection connection.execute("SELECT 1") expect(connection.database_name).to be_nil end expect(connection_reference.active?).to eq(false) end it "creates temporary connection to specific database", mysql2: true do manager = Octoshark::ConnectionManager.new connection_reference = nil config = mysql2_configs[:db1] database_name = config.fetch('database') manager.with_connection(config) do |connection| connection_reference = connection connection.execute("SELECT 1") expect(connection.database_name).to eq(database_name) end expect(connection_reference.active?).to eq(false) end it "returns query results with temporary connection" do manager = Octoshark::ConnectionManager.new config = configs[:db1] result = manager.with_connection(config) do |connection| connection.execute("SELECT 1") end expect(result.first['1']).to eq(1) end end end
ruby
MIT
0971743cb8e5c8eb2686f60188267d3549001503
2026-01-04T17:48:18.822915Z
false
dalibor/octoshark
https://github.com/dalibor/octoshark/blob/0971743cb8e5c8eb2686f60188267d3549001503/spec/octoshark/current_connection_spec.rb
spec/octoshark/current_connection_spec.rb
require 'spec_helper' describe "connection manager" do let(:config) { configs[:db1] } describe "#identifier" do it "has unique identifiers" do manager1 = Octoshark::ConnectionManager.new manager2 = Octoshark::ConnectionManager.new expect(manager1.identifier).to_not eq(manager2.identifier) end end describe "#current_connection" do it "returns last used connection as current one" do manager = Octoshark::ConnectionManager.new manager.with_connection(config) do |connection| expect(manager.current_connection).to eq(connection) end end it "raises error when no current connection" do manager = Octoshark::ConnectionManager.new expect { manager.current_connection }.to raise_error(Octoshark::Error::NoCurrentConnection) end end describe "#current_connection?" do it "returns true if current one" do manager = Octoshark::ConnectionManager.new manager.with_connection(config) do expect(manager.current_connection?).to be_truthy end end it "returns false if no current one" do manager = Octoshark::ConnectionManager.new expect(manager.current_connection?).to be_falsey end end describe "#current_or_default_connection" do it "returns current connection" do manager = Octoshark::ConnectionManager.new manager.with_connection(config) do |connection| expect(manager.current_or_default_connection).to eq(connection) end end it "returns default connection when no current connection" do manager = Octoshark::ConnectionManager.new expect(manager.current_or_default_connection).to eq(ActiveRecord::Base.connection_pool.connection) end end describe '#without_connection' do it "can reset current connection temporarily inside nested connection block" do manager = Octoshark::ConnectionManager.new manager.with_connection(config) do expect(db(manager.current_connection)).to eq("db1") manager.without_connection do expect { manager.current_connection }.to raise_error(Octoshark::Error::NoCurrentConnection) end expect(db(manager.current_connection)).to eq("db1") end end end end
ruby
MIT
0971743cb8e5c8eb2686f60188267d3549001503
2026-01-04T17:48:18.822915Z
false
dalibor/octoshark
https://github.com/dalibor/octoshark/blob/0971743cb8e5c8eb2686f60188267d3549001503/lib/octoshark.rb
lib/octoshark.rb
require 'octoshark/version' require 'active_record' require 'octoshark/active_record_extensions' module Octoshark autoload :CurrentConnection, 'octoshark/current_connection' autoload :ConnectionManager, 'octoshark/connection_manager' autoload :ConnectionPoolsManager, 'octoshark/connection_pools_manager' autoload :Error, 'octoshark/error' end
ruby
MIT
0971743cb8e5c8eb2686f60188267d3549001503
2026-01-04T17:48:18.822915Z
false
dalibor/octoshark
https://github.com/dalibor/octoshark/blob/0971743cb8e5c8eb2686f60188267d3549001503/lib/octoshark/connection_pools_manager.rb
lib/octoshark/connection_pools_manager.rb
module Octoshark class ConnectionPoolsManager include CurrentConnection # Octoshark needs to keep track of all persistent connection managers # in order to automatically reconnect on connection establish. @@connection_managers = [] def self.connection_managers @@connection_managers end def self.reset_connection_managers! connection_managers.each(&:reset!) end def self.disconnect! connection_managers.map(&:disconnect!) @@connection_managers = [] end attr_reader :connection_pools def initialize(configs = {}) @configs = configs.with_indifferent_access setup_connection_pools self.class.connection_managers << self end def reset! disconnect! setup_connection_pools end def with_connection(name, database_name = nil, &block) connection_pool = find_connection_pool(name) connection_pool.with_connection do |connection| connection.connection_name = name if database_name connection.database_name = database_name connection.execute("use #{database_name}") end change_connection_reference(connection) do yield(connection) end end end def find_connection_pool(name) @connection_pools[name] || raise(Octoshark::Error::NoConnection, "No such database connection '#{name}'") end def disconnect! @connection_pools.values.each do |connection_pool| connection_pool.disconnect! end end private def setup_connection_pools @connection_pools = HashWithIndifferentAccess.new @configs.each_pair do |name, config| @connection_pools[name] = create_connection_pool(name, config) end end def create_connection_pool(name, config) spec = build_connection_pool_spec(name, config) ActiveRecord::ConnectionAdapters::ConnectionPool.new(spec) end private def build_connection_pool_spec(name, config) if active_record_6_1_or_7? env_name = defined?(Rails) ? Rails.env : nil require "active_record/database_configurations" db_config = ActiveRecord::DatabaseConfigurations::HashConfig.new(env_name, name, config) pool_config_class = ActiveRecord::ConnectionAdapters::PoolConfig if pool_config_class.instance_method(:initialize).arity == 2 # ActiveRecord 6.1 pool_config_class.new(owner_name = ActiveRecord::Base, db_config) else # ActiveRecord 7.0 pool_config_class.new( owner_name = ActiveRecord::Base, db_config, role = ActiveRecord::Base.current_role, shard = ActiveRecord::Base.current_shard ) end else adapter_method = "#{config[:adapter]}_connection" if active_record_4_or_5_or_6? spec_class = ActiveRecord::ConnectionAdapters::ConnectionSpecification if spec_class.instance_method(:initialize).arity == 3 # ActiveRecord 5.x and 6.0 spec_class.new(name, config, adapter_method) else # ActiveRecord 4.x spec_class.new(config, adapter_method) end else # ActiveRecord 3.x ActiveRecord::Base::ConnectionSpecification.new(config, adapter_method) end end end def active_record_6_1_or_7? defined?(ActiveRecord::ConnectionAdapters::PoolConfig) end def active_record_4_or_5_or_6? defined?(ActiveRecord::ConnectionAdapters::ConnectionSpecification) end end end
ruby
MIT
0971743cb8e5c8eb2686f60188267d3549001503
2026-01-04T17:48:18.822915Z
false
dalibor/octoshark
https://github.com/dalibor/octoshark/blob/0971743cb8e5c8eb2686f60188267d3549001503/lib/octoshark/connection_manager.rb
lib/octoshark/connection_manager.rb
module Octoshark class ConnectionManager include CurrentConnection def with_connection(config, connection_name: nil, &block) connection = if ActiveRecord::ConnectionAdapters.respond_to?(:resolve) # Rails 7.2+ ActiveRecord::ConnectionAdapters.resolve(config[:adapter]).new(config) else connection_method = "#{config[:adapter]}_connection" ActiveRecord::Base.send(connection_method, config) end connection.connection_name = connection_name connection.database_name = config[:database] if config[:database] begin change_connection_reference(connection) do yield(connection) end ensure connection.disconnect! end end end end
ruby
MIT
0971743cb8e5c8eb2686f60188267d3549001503
2026-01-04T17:48:18.822915Z
false
dalibor/octoshark
https://github.com/dalibor/octoshark/blob/0971743cb8e5c8eb2686f60188267d3549001503/lib/octoshark/version.rb
lib/octoshark/version.rb
module Octoshark VERSION = "0.6.0" end
ruby
MIT
0971743cb8e5c8eb2686f60188267d3549001503
2026-01-04T17:48:18.822915Z
false
dalibor/octoshark
https://github.com/dalibor/octoshark/blob/0971743cb8e5c8eb2686f60188267d3549001503/lib/octoshark/current_connection.rb
lib/octoshark/current_connection.rb
module Octoshark module CurrentConnection def current_connection Thread.current[identifier] || raise(Octoshark::Error::NoCurrentConnection, "No current connection") end def current_connection? !Thread.current[identifier].nil? end def current_or_default_connection Thread.current[identifier] || ActiveRecord::Base.connection_pool.connection end def without_connection(&block) change_connection_reference(nil) do yield end end def identifier @identifier ||= "octoshark_#{object_id}" end private def change_connection_reference(connection, &block) previous_connection = Thread.current[identifier] Thread.current[identifier] = connection begin yield ensure Thread.current[identifier] = previous_connection end end end end
ruby
MIT
0971743cb8e5c8eb2686f60188267d3549001503
2026-01-04T17:48:18.822915Z
false
dalibor/octoshark
https://github.com/dalibor/octoshark/blob/0971743cb8e5c8eb2686f60188267d3549001503/lib/octoshark/active_record_extensions.rb
lib/octoshark/active_record_extensions.rb
module Octoshark module ConnectionHandler # def establish_connection(owner, spec) # Rails 3.x # def establish_connection(config_or_env = nil) # Rails 4.x - 6.1 # def establish_connection(config, owner_name:, role:, shard:) # Rails 6.2+ def establish_connection(*args, **kwargs) Octoshark::ConnectionPoolsManager.reset_connection_managers! if kwargs.empty? # For backward compatibility with older versions of Rails on Ruby 3 # that separates positional (args) and keyword arguments (kwargs). super(*args) else super(*args, **kwargs) end end end module ConnectionHandlerRails3 def establish_connection(*args) Octoshark::ConnectionPoolsManager.reset_connection_managers! super(*args) end end module ActiveRecordAbstractAdapter attr_accessor :connection_name, :database_name def log(sql, name = "SQL", *other_args, **kwargs, &block) if connection_name || database_name name = "[Octoshark: #{[connection_name, database_name].compact.join(' ')}] #{name}" end super(sql, name, *other_args, **kwargs, &block) end end module ConnectionPool # Handle Rails 8.0 ConnectionPool#connection deprecation def connection if respond_to?(:lease_connection) # Rails 7.2+ lease_connection else super end end end end # Rails 3.0 and 3.1 does not lazy load unless defined?(ActiveRecord::ConnectionAdapters::ConnectionHandler) require 'active_record/connection_adapters/abstract_adapter' end ActiveRecord::ConnectionAdapters::ConnectionHandler.send(:prepend, Octoshark::ConnectionHandler) ActiveRecord::ConnectionAdapters::AbstractAdapter.send(:prepend, Octoshark::ActiveRecordAbstractAdapter) ActiveRecord::ConnectionAdapters::ConnectionPool.send(:prepend, Octoshark::ConnectionPool)
ruby
MIT
0971743cb8e5c8eb2686f60188267d3549001503
2026-01-04T17:48:18.822915Z
false
dalibor/octoshark
https://github.com/dalibor/octoshark/blob/0971743cb8e5c8eb2686f60188267d3549001503/lib/octoshark/error.rb
lib/octoshark/error.rb
module Octoshark class Error < StandardError class NoConnection < Error; end; class NoCurrentConnection < Error; end; end end
ruby
MIT
0971743cb8e5c8eb2686f60188267d3549001503
2026-01-04T17:48:18.822915Z
false
adzap/active_enum
https://github.com/adzap/active_enum/blob/18606452ea0dd2afa82a71a0b924e93d8a255a83/init.rb
init.rb
require 'active_enum'
ruby
MIT
18606452ea0dd2afa82a71a0b924e93d8a255a83
2026-01-04T17:48:23.635701Z
false
adzap/active_enum
https://github.com/adzap/active_enum/blob/18606452ea0dd2afa82a71a0b924e93d8a255a83/spec/active_enum_spec.rb
spec/active_enum_spec.rb
require "spec_helper" describe ActiveEnum do describe ".define" do it 'should define enum constants using block' do ActiveEnum.define do enum(:foo) do value :id => 1, :name => 'Foo 1' end enum(:bar) do value :id => 1, :name => 'Bar 1' end end expect(Foo.all).to eq([[1,'Foo 1']]) expect(Bar.all).to eq([[1,'Bar 1']]) end end describe ".setup" do before :all do @original = ActiveEnum.use_name_as_value end it 'should pass module into block as configuration object' do expect(ActiveEnum.use_name_as_value).to be_falsey ActiveEnum.setup {|config| config.use_name_as_value = true } expect(ActiveEnum.use_name_as_value).to be_truthy end after :all do ActiveEnum.use_name_as_value = @original end end describe ".extend_classes!" do it 'should add enumerate extensions to given classes' do ActiveEnum.extend_classes = [NotActiveRecord] expect(NotActiveRecord).not_to respond_to(:enumerate) ActiveEnum.extend_classes! expect(NotActiveRecord).to respond_to(:enumerate) end end it 'should use the memory store by default' do expect(ActiveEnum.storage).to eq(:memory) end end
ruby
MIT
18606452ea0dd2afa82a71a0b924e93d8a255a83
2026-01-04T17:48:23.635701Z
false
adzap/active_enum
https://github.com/adzap/active_enum/blob/18606452ea0dd2afa82a71a0b924e93d8a255a83/spec/spec_helper.rb
spec/spec_helper.rb
ENV["RAILS_ENV"] ||= 'test' require 'logger' require 'rails' require 'active_record' require 'action_controller/railtie' require 'action_view' require 'action_mailer' require 'active_enum' require 'active_enum/acts_as_enum' module ActiveEnum class Application < Rails::Application config.generators do |g| g.orm :active_record g.test_framework :rspec, :fixture => false end config.active_support.deprecation = :notify end end I18n.enforce_available_locales = false I18n.available_locales = ['en', 'ja'] ActiveRecord::Migration.verbose = false ActiveRecord::Base.establish_connection({:adapter => "sqlite3", :database => ':memory:'}) require 'rspec/rails' require 'support/schema' Dir[File.dirname(__FILE__) + "/support/**/*.rb"].each { |f| require f } class Person < ActiveRecord::Base; end class NoEnumPerson < ActiveRecord::Base self.table_name = 'people' end class NotActiveRecord include ActiveModel::Validations attr_accessor :name end ActiveEnum.extend_classes = [ActiveRecord::Base] ActiveEnum.extend_classes! module SpecHelper def reset_class(klass, &block) name = klass.name.to_sym Object.send(:remove_const, name) eval "class #{klass}#{' < ' + klass.superclass.to_s if klass.superclass != Class}; end", TOPLEVEL_BINDING new_klass = Object.const_get(name) new_klass.class_eval &block if block_given? new_klass end end RSpec.configure do |config| config.include SpecHelper config.include ConfigHelper # rspec-rails 3 will no longer automatically infer an example group's spec type # from the file location. You can explicitly opt-in to the feature using this # config option. # To explicitly tag specs without using automatic inference, set the `:type` # metadata manually: # # describe ThingsController, :type => :controller do # # Equivalent to being in spec/controllers # end config.infer_spec_type_from_file_location! end
ruby
MIT
18606452ea0dd2afa82a71a0b924e93d8a255a83
2026-01-04T17:48:23.635701Z
false
adzap/active_enum
https://github.com/adzap/active_enum/blob/18606452ea0dd2afa82a71a0b924e93d8a255a83/spec/support/config_helper.rb
spec/support/config_helper.rb
module ConfigHelper extend ActiveSupport::Concern def with_config(preference_name, temporary_value) original_config_value = ActiveEnum.config.send(preference_name) ActiveEnum.config.send(:"#{preference_name}=", temporary_value) yield ensure ActiveEnum.config.send(:"#{preference_name}=", original_config_value) end module ClassMethods def with_config(preference_name, temporary_value) original_config_value = ActiveEnum.config.send(preference_name) before(:all) do ActiveEnum.config.send(:"#{preference_name}=", temporary_value) end after(:all) do ActiveEnum.config.send(:"#{preference_name}=", original_config_value) end end end end
ruby
MIT
18606452ea0dd2afa82a71a0b924e93d8a255a83
2026-01-04T17:48:23.635701Z
false
adzap/active_enum
https://github.com/adzap/active_enum/blob/18606452ea0dd2afa82a71a0b924e93d8a255a83/spec/support/schema.rb
spec/support/schema.rb
ActiveRecord::Schema.define(:version => 1) do create_table :people, :force => true do |t| t.string :first_name t.string :last_name t.integer :sex t.integer :attending t.integer :staying t.integer :employment_status end create_table :sorted_people, :force => true do |t| t.string :first_name t.string :last_name t.integer :sex t.integer :attending t.integer :staying end create_table :sexes, :force => true do |t| t.string :name end end
ruby
MIT
18606452ea0dd2afa82a71a0b924e93d8a255a83
2026-01-04T17:48:23.635701Z
false
adzap/active_enum
https://github.com/adzap/active_enum/blob/18606452ea0dd2afa82a71a0b924e93d8a255a83/spec/active_enum/base_spec.rb
spec/active_enum/base_spec.rb
require "spec_helper" describe ActiveEnum::Base do describe ".store" do it 'should load the storage class instance using the storage setting' do expect(ActiveEnum::Base.send(:store)).to be_instance_of(ActiveEnum::Storage::MemoryStore) end end describe ".enum_classes" do it 'should return all enum classes defined use class definition' do ActiveEnum.enum_classes = [] class NewEnum < ActiveEnum::Base; end expect(ActiveEnum.enum_classes).to eq([NewEnum]) end it 'should return all enum classes defined using define block' do ActiveEnum.enum_classes = [] ActiveEnum.define do enum(:bulk_new_enum) { } end expect(ActiveEnum.enum_classes).to eq([BulkNewEnum]) end end describe ".values" do it 'should return an empty array when no values defined' do expect(define_enum.values).to eq([]) end it 'should return an array of arrays with all values defined as [id, name]' do enum = define_enum do value name: 'Name 1' value name: 'Name 2' end expect(enum.values).to eq([[1,'Name 1'], [2, 'Name 2']]) end end describe ".value" do it 'should allow me to define a value with an id and name' do enum = define_enum do value id: 1, name: 'Name' end expect(enum.values).to eq([[1,'Name']]) end it 'should allow me to define a value with a name only' do enum = define_enum do value name: 'Name' end expect(enum.values).to eq([[1,'Name']]) end it 'should allow me to define a value as hash with id as key and name as value' do enum = define_enum do value 1 => 'Name' end expect(enum.values).to eq([[1,'Name']]) end it 'should allow to define meta data value with extra key value pairs' do enum = define_enum do value id: 1, name: 'Name', description: 'extra' end expect(enum.values).to eq([[1,'Name',{description: 'extra'}]]) end it 'should increment value ids when defined without ids' do enum = define_enum do value name: 'Name 1' value name: 'Name 2' end expect(enum.values).to eq([[1,'Name 1'], [2, 'Name 2']]) end it 'should raise error if the id is a duplicate' do expect { define_enum do value id: 1, name: 'Name 1' value id: 1, name: 'Name 2' end }.to raise_error(ActiveEnum::DuplicateValue) end it 'should raise error if the name is a duplicate' do expect { define_enum do value id: 1, name: 'Name' value id: 2, name: 'Name' end }.to raise_error(ActiveEnum::DuplicateValue) end end describe ".meta" do it 'should return meta values hash for a given index value' do enum = define_enum do value id: 1, name: 'Name', description: 'extra' end expect(enum.meta(1)).to eq({description: 'extra'}) end it 'should return empty hash for index with no meta defined' do enum = define_enum do value id: 1, name: 'Name' end expect(enum.meta(1)).to eq({}) end context "with raise_on_not_found: false" do let(:enum) { define_enum do value id: 1, name: 'Name', description: 'extra' end } it "should raise ActiveEnum::NotFound for missing id" do expect { enum.meta(0, raise_on_not_found: true) }.to raise_error(ActiveEnum::NotFound) end it "should raise ActiveEnum::NotFound for missing name" do expect { enum.meta('Not a value', raise_on_not_found: true) }.to raise_error(ActiveEnum::NotFound) end end end context "sorting" do it 'should return values ascending by default' do enum = define_enum do value id: 2, name: 'Name 2' value id: 1, name: 'Name 1' end expect(enum.values).to eq([[1,'Name 1'], [2, 'Name 2']]) end it 'should return sorted values by id using order setting' do enum = define_enum do order :desc value id: 1, name: 'Name 1' value id: 2, name: 'Name 2' end expect(enum.values).to eq([[2, 'Name 2'], [1,'Name 1']]) end it 'should return sorted values by id using order setting' do enum = define_enum do order :natural value id: 3, name: 'Name 3' value id: 1, name: 'Name 1' value id: 2, name: 'Name 2' end expect(enum.values).to eq([[3,'Name 3'], [1,'Name 1'], [2, 'Name 2']]) end end describe ".ids" do it 'should return array of ids' do enum = define_enum do value id: 1, name: 'Name 1' value id: 2, name: 'Name 2' end expect(enum.ids).to eq([1,2]) end end describe ".names" do it 'should return array of names' do enum = define_enum do value id: 1, name: 'Name 1' value id: 2, name: 'Name 2' end expect(enum.names).to eq(['Name 1', 'Name 2']) end end context "element reference method" do let(:enum) { define_enum do value id: 1, name: 'Name 1' value id: 2, name: 'Name 2' end } it 'should return name when given an id' do expect(enum[1]).to eq('Name 1') end it 'should return id when given a name' do expect(enum['Name 1']).to eq(1) end it 'should return id when given a symbol of the name' do expect(enum[:Name_1]).to eq(1) expect(enum[:name_1]).to eq(1) end context "for missing value" do it "should return nil for missing id" do expect(enum['Not a value']).to eq nil end it "should return nil for missing name" do expect(enum[0]).to eq nil end context "with config raise_on_not_found" do with_config :raise_on_not_found, true it "should raise ActiveEnum::NotFound for missing id" do expect { enum['Not a value'] }.to raise_error(ActiveEnum::NotFound) end it "should raise ActiveEnum::NotFound for missing name" do expect { enum[0] }.to raise_error(ActiveEnum::NotFound) end end end end describe '.get' do with_config :raise_on_not_found, false let(:enum) { define_enum do value id: 1, name: 'Name 1' value id: 2, name: 'Name 2' end } context "with raise_on_not_found: false" do it "should raise ActiveEnum::NotFound for missing id" do expect { enum.get('Not a value', raise_on_not_found: true) }.to raise_error(ActiveEnum::NotFound) end it "should raise ActiveEnum::NotFound for missing name" do expect { enum.get(0, raise_on_not_found: true) }.to raise_error(ActiveEnum::NotFound) end end end describe ".include?" do let(:enum) { define_enum do value id: 1, name: 'Name 1' value id: 2, name: 'Name 2' end } it "should return true if value is a fixnum and matches an id" do expect(enum.include?(1)).to be_truthy end it "should return false if value is a fixnum and does not match an id" do expect(enum.include?(3)).to be_falsey end it "should return true if value is a string and matches a name" do expect(enum.include?('Name 1')).to be_truthy end it "should return false if value is a string and does not match a name" do expect(enum.include?('No match')).to be_falsey end end describe ".to_select" do it 'should return array for select helpers' do enum = define_enum do value id: 1, name: 'Name 1' value id: 2, name: 'Name 2' end expect(enum.to_select).to eq([['Name 1',1], ['Name 2',2]]) end it 'should return array sorted using order setting' do enum = define_enum do order :desc value id: 1, name: 'Name 1' value id: 2, name: 'Name 2' end expect(enum.to_select).to eq([['Name 2',2], ['Name 1',1]]) end end describe ".to_grouped_select" do it 'should return array for grouped select helpers grouped by meta key value' do enum = define_enum do value id: 1, name: 'Name 1', category: 'Foo' value id: 2, name: 'Name 2', category: 'Bar' end expect(enum.to_grouped_select(:category)).to eq([ [ 'Foo', [ ['Name 1',1] ] ], [ 'Bar', [ ['Name 2',2] ] ] ]) end it 'should group any value missing the group_by key by nil' do enum = define_enum do value id: 1, name: 'Name 1', category: 'Foo' value id: 2, name: 'Name 2' end expect(enum.to_grouped_select(:category)).to eq([ [ 'Foo', [ ['Name 1',1] ] ], [ nil, [ ['Name 2',2] ] ] ]) end it 'shoud transform group name with custom group transform proc' do enum = define_enum do value id: 1, name: 'Name 1', category: 'Foo' value id: 2, name: 'Name 2' end expect(enum.to_grouped_select(:category, group_transform: proc { |group| group.to_s.upcase })).to eq([ [ 'FOO', [ ['Name 1',1] ] ], [ '', [ ['Name 2',2] ] ] ]) end end describe ".to_h" do it 'should return hash of ids as keys and names as values' do enum = define_enum do value id: 1, name: 'Name 1' value id: 2, name: 'Name 2' end expect(enum.to_h).to eq({ 1 => 'Name 1', 2 => 'Name 2' }) end end describe ".length" do it 'should return number of values defined' do enum = define_enum do value id: 1, name: 'Name 1' value id: 2, name: 'Name 2' end expect(enum.length).to eq 2 end it 'should return 0 when no values defined' do enum = define_enum {} expect(enum.length).to eq 0 end it 'should be aliased as size' do enum = define_enum do value id: 1, name: 'Name 1' value id: 2, name: 'Name 2' end expect(enum.size).to eq enum.length end end def define_enum(&block) Class.new(ActiveEnum::Base, &block) end end
ruby
MIT
18606452ea0dd2afa82a71a0b924e93d8a255a83
2026-01-04T17:48:23.635701Z
false
adzap/active_enum
https://github.com/adzap/active_enum/blob/18606452ea0dd2afa82a71a0b924e93d8a255a83/spec/active_enum/extensions_spec.rb
spec/active_enum/extensions_spec.rb
require "spec_helper" describe ActiveEnum::Extensions do class Sex < ActiveEnum::Base value id: 1, name: 'Male' value id: 2, name: 'Female' end class Accepted < ActiveEnum::Base value id: 0, name: 'No' value id: 1, name: 'Definitely' value id: 2, name: 'Maybe' end it 'should add class :enumerate method to ActiveRecord' do expect(ActiveRecord::Base).to respond_to(:enumerate) end it 'should add class :active_enum_for method to ActiveRecord' do expect(ActiveRecord::Base).to respond_to(:active_enum_for) end it 'should allow multiple attributes to be enumerated with same enum' do Person.enumerate :attending, :staying, with: Accepted expect(Person.active_enum_for(:attending)).to eq(Accepted) expect(Person.active_enum_for(:staying)).to eq(Accepted) end it 'should allow multiple attributes to be enumerated with different enums' do Person.enumerate :sex, with: Sex Person.enumerate :attending, with: Accepted expect(Person.active_enum_for(:sex)).to eq(Sex) expect(Person.active_enum_for(:attending)).to eq(Accepted) end it 'should allow implicit enumeration class from attribute name' do Person.enumerate :sex expect(Person.active_enum_for(:sex)).to eq(Sex) end it 'should create enum namespaced enum class from block' do Person.enumerate :sex do value id: 1, name: 'Male' end expect(Person.active_enum_for(:sex)).to eq(::Person::Sex) end it 'should raise error if implicit enumeration class cannot be found' do expect { Person.enumerate :first_name }.to raise_error(ActiveEnum::EnumNotFound) end context "attribute" do let(:person) { Person.new(sex: 1) } before(:all) do reset_class Person do enumerate :sex, with: Sex end end context "with value" do it 'should return value with no arg' do expect(person.sex).to eq(1) end it 'should return enum id for value' do expect(person.sex(:id)).to eq(1) end it 'should return enum name for value' do expect(person.sex(:name)).to eq('Male') end it 'should return enum class for attribute' do expect(person.sex(:enum)).to eq(Sex) end end context "with nil value" do let(:person) { Person.new(sex: nil) } it 'should return nil with no arg' do expect(person.sex).to be_nil end it 'should return nil enum id' do expect(person.sex(:id)).to be_nil end it 'should return nil enum name' do expect(person.sex(:name)).to be_nil end it 'should return enum class for attribute' do expect(person.sex(:enum)).to eq(Sex) end context "and global raise_on_not_found set to true" do with_config :raise_on_not_found, true it "should not raise error when attribute is nil" do expect { person.sex(:id) }.to_not raise_error end end end context "with undefined value" do let(:person) { Person.new(sex: -1) } it 'should return value with no arg' do expect(person.sex).to eq(-1) end it 'should return nil enum id' do expect(person.sex(:id)).to be_nil end it 'should return nil enum name' do expect(person.sex(:name)).to be_nil end it 'should return enum class for attribute' do expect(person.sex(:enum)).to eq(Sex) end context "and global raise_on_not_found set to true" do with_config :raise_on_not_found, true it "should not raise error when attribute value is invalid" do expect { person.sex(:id) }.to_not raise_error end end end context "with meta data" do let(:person) { Person.new(sex: 1) } before(:all) do reset_class Person do enumerate :sex do value id: 1, name: 'Male', description: 'Man' value id: 2, name: 'Female', description: 'Woman' end end end it 'should return meta value for existing key' do expect(person.sex(:description)).to eq('Man') end it 'should return nil for missing meta value' do expect(person.sex(:nonexistent)).to be_nil end it 'should return nil for missing index' do person.sex = nil expect(person.sex(:description)).to be_nil end context "and global raise_on_not_found set to true" do let(:person) { Person.new(sex: -1) } with_config :raise_on_not_found, true it "should not raise error when attribute value is invalid" do expect { person.sex(:nonexistent) }.to_not raise_error end end end context "question method" do it 'should return normal value without arg' do expect(person.sex?).to be_truthy person.sex = nil expect(person.sex?).to be_falsey end it 'should return true if string name matches for id value' do expect(person.sex?("Male")).to be_truthy end it 'should return true if symbol name matches for id value' do expect(person.sex?(:male)).to be_truthy expect(person.sex?(:Male)).to be_truthy end it 'should return false if name does not match for id value' do expect(person.sex?("Female")).to be_falsey expect(person.sex?(:female)).to be_falsey expect(person.sex?(:Female)).to be_falsey end it 'should return false if attribute is nil regardless of enum value' do person.sex = nil expect(person.sex?(:nonexistent)).to be_falsey end end context "with value as enum name symbol" do it 'should store id value when valid enum name' do person.sex = :female expect(person.sex).to eq(2) end it 'should store nil value when invalid enum name' do person.sex = :invalid expect(person.sex).to eq(nil) end end context "with value as enum name" do before(:all) { ActiveEnum.use_name_as_value = true } let(:person) { Person.new(:sex =>1) } before do reset_class Person do enumerate :sex, with: Sex end end it 'should return text name value for attribute' do expect(person.sex).to eq('Male') end it 'should return true for boolean match' do expect(person.sex?(:male)).to be_truthy end after(:all) { ActiveEnum.use_name_as_value = false } end context "with skip_accessors: true" do before(:all) do reset_class Person do enumerate :sex, with: Sex, skip_accessors: true end end it 'read method should not accept arg' do expect{ person.sex(:name) }.to raise_error ArgumentError end it 'write method should not accept name' do person.sex = :male expect(person.sex).to_not eq Sex[:male] end it 'question method should not accept arg' do expect{ person.sex?(:male) }.to raise_error ArgumentError end end end end
ruby
MIT
18606452ea0dd2afa82a71a0b924e93d8a255a83
2026-01-04T17:48:23.635701Z
false
adzap/active_enum
https://github.com/adzap/active_enum/blob/18606452ea0dd2afa82a71a0b924e93d8a255a83/spec/active_enum/acts_as_enum_spec.rb
spec/active_enum/acts_as_enum_spec.rb
require "spec_helper" describe ActiveEnum::ActsAsEnum do class Person < ActiveRecord::Base acts_as_enum name_column: 'first_name' end class TestPerson < ActiveRecord::Base def self.extended_modules class << self self.included_modules end end end class SortedPerson < ActiveRecord::Base acts_as_enum name_column: 'first_name', order: :desc end before(:all) do Person.create!(first_name: 'Dave', last_name: 'Smith') Person.create!(first_name: 'John', last_name: 'Doe') SortedPerson.create!(first_name: 'Dave', last_name: 'Smith') SortedPerson.create!(first_name: 'John', last_name: 'Doe') end it "should mixin enum class methods only when act_as_enum defined" do expect(TestPerson.extended_modules).not_to include(ActiveEnum::ActsAsEnum::ClassMethods) TestPerson.acts_as_enum expect(TestPerson.extended_modules).to include(ActiveEnum::ActsAsEnum::ClassMethods) end context "#[]" do it "should return name column value when passed id" do expect(Person[1]).to eq('Dave') end it "should return id column value when passed string name" do expect(Person['Dave']).to eq(1) expect(Person['dave']).to eq(1) end it "should return id column value when passed symbol name" do expect(Person[:dave]).to eq(1) end end context '#get' do it "should return name column value when passed id" do expect(Person.get(1)).to eq('Dave') end it "should return id column value when passed string name" do expect(Person.get('Dave')).to eq(1) expect(Person.get('dave')).to eq(1) end it "should return id column value when passed symbol name" do expect(Person.get(:dave)).to eq(1) end it "should not raise for missing id when raise_on_not_found is false" do expect { Person.get(0, raise_on_not_found: false) }.to_not raise_error end it "should raise for missing id when raise_on_not_found is true" do expect { Person.get(0, raise_on_not_found: true) }.to raise_error(ActiveEnum::NotFound) end end context '#values' do it "should return array of arrays containing id and name column values" do expect(Person.values).to eq([[1, 'Dave'], [2, 'John']]) end end context '#to_select' do it "should return array for select helpers" do expect(Person.to_select).to eq([['Dave', 1], ['John', 2]]) end it "should return sorted array from order value for select helpers when an order is specified" do expect(SortedPerson.to_select).to eq([['John', 2], ['Dave', 1]]) end end context '#meta' do it "should return record attributes hash without id and name columns" do expect(Person.meta(1)).to eq(Person.find(1).attributes.except('id', 'first_name')) end end context '#include?' do it "should return true if value is integer and model has id" do expect(Person.exists?(id: 1)).to eq(true) expect(Person.include?(1)).to eq(true) end it "should return false if value is integer and model does not have id" do expect(Person.exists?(id: 100)).to eq(false) expect(Person.include?(100)).to eq(false) end it "should return super if value is a module" do expect(Person.include?(ActiveRecord::Attributes)).to eq(true) expect(Person.include?(Module.new)).to eq(false) end end end
ruby
MIT
18606452ea0dd2afa82a71a0b924e93d8a255a83
2026-01-04T17:48:23.635701Z
false
adzap/active_enum
https://github.com/adzap/active_enum/blob/18606452ea0dd2afa82a71a0b924e93d8a255a83/spec/active_enum/storage/memory_store_spec.rb
spec/active_enum/storage/memory_store_spec.rb
require "spec_helper" describe ActiveEnum::Storage::MemoryStore do attr_accessor :store class TestMemoryStoreEnum < ActiveEnum::Base; end class TestOtherAREnum < ActiveEnum::Base; end describe '#set' do it 'should store value of id and name' do store.set 1, 'test name' expect(store.values).to eq([[1, 'test name']]) end it 'should store value of id, name and meta hash' do store.set 1, 'test name', description: 'meta' expect(store.values).to eq([[1, 'test name', {description: 'meta'}]]) end it 'should raise error if duplicate id' do expect { store.set 1, 'Name 1' store.set 1, 'Other Name' }.to raise_error(ActiveEnum::DuplicateValue) end it 'should raise error if duplicate name' do expect { store.set 1, 'Name 1' store.set 2, 'Name 1' }.to raise_error(ActiveEnum::DuplicateValue) end it 'should raise error if duplicate name matches title-case name' do expect { store.set 1, 'Name 1' store.set 2, 'name 1' }.to raise_error(ActiveEnum::DuplicateValue) end end describe "#values" do it 'should return array of stored values' do store.set 1, 'Name 1' expect(store.values).to eq([[1, 'Name 1']]) end it 'should return values for set enum only' do alt_store.set 1, 'Other Name 1' store.set 1, 'Name 1' expect(store.values).to eq([[1, 'Name 1']]) end end describe "#get_by_id" do it 'should return the value for a given id' do store.set 1, 'test name', description: 'meta' expect(store.get_by_id(1)).to eq([1, 'test name', {description: "meta"}]) end it 'should return nil when id not found' do expect(store.get_by_id(1)).to be_nil end end describe "#get_by_name" do it 'should return the value for a given name' do store.set 1, 'test name' expect(store.get_by_name('test name')).to eq([1, 'test name']) end it 'should return the value with title-cased name for a given lowercase name' do store.set 1, 'Test Name' expect(store.get_by_name('test name')).to eq([1, 'Test Name']) end it 'should return nil when name not found' do expect(store.get_by_name('test name')).to be_nil end end describe "#sort!" do it 'should sort values ascending when passed :asc' do @order = :asc store.set 2, 'Name 2' store.set 1, 'Name 1' expect(store.values).to eq([[1,'Name 1'], [2, 'Name 2']]) end it 'should sort values descending when passed :desc' do @order = :desc store.set 1, 'Name 1' store.set 2, 'Name 2' expect(store.values).to eq([[2, 'Name 2'], [1,'Name 1']]) end it 'should not sort values when passed :natural' do @order = :natural store.set 1, 'Name 1' store.set 3, 'Name 3' store.set 2, 'Name 2' expect(store.values).to eq([[1,'Name 1'], [3,'Name 3'], [2, 'Name 2']]) end end def store @store ||= ActiveEnum::Storage::MemoryStore.new(TestMemoryStoreEnum, @order) end def alt_store @alt_store ||= ActiveEnum::Storage::MemoryStore.new(TestOtherAREnum, :asc) end end
ruby
MIT
18606452ea0dd2afa82a71a0b924e93d8a255a83
2026-01-04T17:48:23.635701Z
false
adzap/active_enum
https://github.com/adzap/active_enum/blob/18606452ea0dd2afa82a71a0b924e93d8a255a83/spec/active_enum/storage/i18n_store_spec.rb
spec/active_enum/storage/i18n_store_spec.rb
require "spec_helper" describe ActiveEnum::Storage::I18nStore do class TestI18nStoreEnum < ActiveEnum::Base; end let(:enum_class) { TestI18nStoreEnum } let(:enum_key) { enum_class.name.underscore } let(:store) { ActiveEnum::Storage::I18nStore.new(enum_class, :asc) } before(:all) do @_default_store = ActiveEnum.storage ActiveEnum.storage = :i18n end after(:all) do ActiveEnum.storage = @_default_store end before do @default_locale = I18n.locale end after do I18n.locale = @default_locale end describe '#set' do it 'should store value of id and name' do store.set 1, 'test name' expect(store.send(:_values)).to eq([[1, 'test name']]) end it 'should store value of id, name and meta hash' do store.set 1, 'test name', description: 'meta' expect(store.send(:_values)).to eq([[1, 'test name', { description: 'meta' }]]) end it 'should raise error if duplicate id' do expect { store.set 1, 'Name 1' store.set 1, 'Other Name' }.to raise_error(ActiveEnum::DuplicateValue) end it 'should raise error if duplicate name' do expect { store.set 1, 'Name 1' store.set 2, 'Name 1' }.to raise_error(ActiveEnum::DuplicateValue) end it 'should not raise error if duplicate name with alternate case matches' do expect { store.set 1, 'Name 1' store.set 2, 'name 1' }.not_to raise_error() end end describe "#values" do before do I18n.backend.store_translations :en, active_enum: { enum_key => { thanks: 'Thanks' } } I18n.backend.store_translations :fr, active_enum: { enum_key => { thanks: 'Merce' } } end it 'should return array of stored values for current locale' do store.set 1, 'thanks' I18n.locale = :en expect(store.values).to eq([ [1, 'Thanks'] ]) I18n.locale = :fr expect(store.values).to eq([ [1, 'Merce'] ]) end end describe "#get_by_id" do before do I18n.backend.store_translations :en, active_enum: { enum_key => { 'test' => 'Testing' } } I18n.locale = :en end it 'should return the value for a given id' do store.set 1, 'test' expect(store.get_by_id(1)).to eq([1, 'Testing']) end it 'should return the value with meta for a given id' do store.set 1, 'test', description: 'meta' expect(store.get_by_id(1)).to eq([1, 'Testing', { description: 'meta' }]) end it 'should return nil when id not found' do expect(store.get_by_id(1)).to be_nil end it 'should return key when translation missing' do I18n.locale = :ja store.set 1, 'test' expect(store.get_by_id(1)).to eq([1, 'test']) end end describe "#get_by_name" do before do I18n.backend.store_translations :en, active_enum: { enum_key => { 'test' => 'Testing' } } I18n.locale = :en end it 'should return the value for a given name' do store.set 1, 'test' expect(store.get_by_name('test')).to eq([1, 'Testing']) end it 'should return the value with meta for a given name' do store.set 1, 'test', description: 'meta' expect(store.get_by_name('test')).to eq([1, 'Testing', { description: 'meta' }]) end it 'should return nil when name not found' do expect(store.get_by_name('test')).to be_nil end end describe "#sort!" do before do I18n.backend.store_translations :en, active_enum: { enum_key => { 'name1' => 'Name 1', 'name2' => 'Name 2', 'name3' => 'Name 3', } } end it 'should sort values ascending when passed :asc' do store = described_class.new(enum_class, :asc) store.set 2, 'name2' store.set 1, 'name1' expect(store.values).to eq([[1,'Name 1'], [2, 'Name 2']]) end it 'should sort values descending when passed :desc' do store = described_class.new(enum_class, :desc) store.set 1, 'name1' store.set 2, 'name2' expect(store.values).to eq([[2, 'Name 2'], [1,'Name 1']]) end it 'should not sort values when passed :natural' do store = described_class.new(enum_class, :natural) store.set 1, 'name1' store.set 3, 'name3' store.set 2, 'name2' expect(store.values).to eq([[1,'Name 1'], [3,'Name 3'], [2, 'Name 2']]) end end context "loaded from yaml locale" do before do I18n.load_path << File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'support', 'i18n.yml')) I18n.reload! I18n.locale = :en end context "for top level enum" do class TopLevelEnum < ActiveEnum::Base; end let(:enum_class) { TopLevelEnum } it 'should return array values from yaml' do store.set 1, 'things' expect(store.get_by_name('things')).to eq [1, 'Generic things'] end it 'should not load locale entry unless defined in enum' do store.set 1, 'things' expect(store.get_by_name('not_found')).to be_nil end end context "for namespaced model enum" do module Namespaced; class ModelEnum < ActiveEnum::Base; end; end let(:enum_class) { Namespaced::ModelEnum } it 'should return array values from yaml' do store.set 1, 'things' expect(store.get_by_name('things')).to eq [1, 'Model things'] end it 'should not load locale entry unless defined in enum' do store.set 1, 'things' expect(store.get_by_name('not_found')).to be_nil end end end end
ruby
MIT
18606452ea0dd2afa82a71a0b924e93d8a255a83
2026-01-04T17:48:23.635701Z
false
adzap/active_enum
https://github.com/adzap/active_enum/blob/18606452ea0dd2afa82a71a0b924e93d8a255a83/spec/active_enum/form_helpers/simple_form_spec.rb
spec/active_enum/form_helpers/simple_form_spec.rb
require "spec_helper" require 'simple_form' require 'active_enum/form_helpers/simple_form' describe ActiveEnum::FormHelpers::SimpleForm, type: :helper do include SimpleForm::ActionViewExtensions::FormHelper before do allow(controller).to receive(:action_name).and_return('new') reset_class Person do enumerate :sex do value id: 1, name: 'Male' value id: 2, name: 'Female' end enumerate :employment_status do value id: 1, name: 'Full-time', group: 'Waged' value id: 3, name: 'Part-time', group: 'Waged' value id: 4, name: 'Casual', group: 'Waged' value id: 5, name: 'Student', group: 'Un-waged' value id: 6, name: 'Retired', group: 'Un-waged' value id: 7, name: 'Unemployed', group: 'Un-waged' value id: 8, name: 'Carer', group: 'Un-waged' end end end it "should use enum input type for enumerated attribute" do output = simple_form_for(Person.new, url: people_path) do |f| concat f.input(:sex) end expect(output).to have_selector('select#person_sex') expect(output).to have_xpath('//option[@value=1]', text: 'Male') expect(output).to have_xpath('//option[@value=2]', text: 'Female') end it "should use explicit :enum input type" do output = simple_form_for(Person.new, url: people_path) do |f| concat f.input(:sex, as: :enum) end expect(output).to have_selector('select#person_sex') expect(output).to have_xpath('//option[@value=1]', text: 'Male') expect(output).to have_xpath('//option[@value=2]', text: 'Female') end it "should use explicit :grouped_enum input type" do output = simple_form_for(Person.new, url: people_path) do |f| concat f.input(:employment_status, as: :grouped_enum, group_by: :group) end expect(output).to have_selector('select#person_employment_status') expect(output).to have_xpath('//optgroup[@label="Waged"]/option[@value=1]', text: 'Full-time') expect(output).to have_xpath('//optgroup[@label="Un-waged"]/option[@value=8]', text: 'Carer') end it "should not use enum input type if :as option indicates other type" do output = simple_form_for(Person.new, url: people_path) do |f| concat f.input(:sex, as: :string) end expect(output).to have_selector('input#person_sex') end it "should raise error if attribute for enum input is not enumerated" do expect { simple_form_for(Person.new, url: people_path) do |f| f.input(:attending, as: :enum) end }.to raise_error "Attribute 'attending' has no enum class" end it "should not use enum input type if class does not support ActiveEnum" do output = simple_form_for(NotActiveRecord.new, as: :not_active_record, url: people_path) do |f| concat f.input(:name) end expect(output).to have_selector('input#not_active_record_name') end it "should allow non-enum fields to use default input determination" do output = simple_form_for(Person.new, url: people_path) do |f| concat f.input(:first_name) end expect(output).to have_selector('input#person_first_name') end it "should allow models without enumerated attributes to behave normally" do output = simple_form_for(NoEnumPerson.new, url: people_path) do |f| concat f.input(:first_name) end expect(output).to have_selector('input#no_enum_person_first_name') end def people_path '/people' end end
ruby
MIT
18606452ea0dd2afa82a71a0b924e93d8a255a83
2026-01-04T17:48:23.635701Z
false
adzap/active_enum
https://github.com/adzap/active_enum/blob/18606452ea0dd2afa82a71a0b924e93d8a255a83/lib/active_enum.rb
lib/active_enum.rb
require 'active_enum/base' require 'active_enum/extensions' require 'active_enum/storage/abstract_store' require 'active_enum/version' require 'active_enum/railtie' if defined?(Rails) module ActiveEnum mattr_accessor :enum_classes @@enum_classes = [] mattr_accessor :use_name_as_value @@use_name_as_value = false mattr_accessor :raise_on_not_found @@raise_on_not_found = false mattr_accessor :storage @@storage = :memory mattr_accessor :storage_options @@storage_options = {} mattr_accessor :default_select_value_transform @@default_select_value_transform = proc { |value| [ value[1].html_safe, value[0] ] } mattr_accessor :default_select_group_transform @@default_select_group_transform = proc { |group| group&.html_safe } def storage=(*args) @@storage_options = args.extract_options! @@storage = args.first end mattr_accessor :extend_classes @@extend_classes = [] # Setup method for plugin configuration def self.setup yield config extend_classes! end def self.config self end class EnumDefinitions def enum(name, &block) class_name = name.to_s.camelize eval("class #{class_name} < ActiveEnum::Base; end", TOPLEVEL_BINDING) new_enum = Module.const_get(class_name) new_enum.class_eval(&block) end end # Define enums in bulk def self.define(&block) raise "Define requires block" unless block_given? EnumDefinitions.new.instance_eval(&block) end def self.storage_class @@storage_class ||= "ActiveEnum::Storage::#{storage.to_s.classify}Store".constantize end private def self.extend_classes! extend_classes.each {|klass| klass.send(:include, ActiveEnum::Extensions) } end end
ruby
MIT
18606452ea0dd2afa82a71a0b924e93d8a255a83
2026-01-04T17:48:23.635701Z
false
adzap/active_enum
https://github.com/adzap/active_enum/blob/18606452ea0dd2afa82a71a0b924e93d8a255a83/lib/generators/active_enum/install_generator.rb
lib/generators/active_enum/install_generator.rb
module ActiveEnum module Generators class InstallGenerator < Rails::Generators::Base desc "Copy ActiveEnum default files" source_root File.expand_path('../templates', __FILE__) def copy_initializers copy_file 'config.rb', 'config/initializers/active_enum.rb' end end end end
ruby
MIT
18606452ea0dd2afa82a71a0b924e93d8a255a83
2026-01-04T17:48:23.635701Z
false
adzap/active_enum
https://github.com/adzap/active_enum/blob/18606452ea0dd2afa82a71a0b924e93d8a255a83/lib/generators/active_enum/locale_generator.rb
lib/generators/active_enum/locale_generator.rb
module ActiveEnum module Generators class LocaleGenerator < Rails::Generators::Base desc "Copy ActiveEnum locale file for I18n storage" source_root File.expand_path('../templates', __FILE__) class_option :lang, :type => :string, :default => 'en', :desc => "Language for locale file" def copy_initializers template 'locale.yml', locale_full_path end def locale_filename "active_enum.#{options[:lang]}.yml" end def locale_full_path "config/locales/#{locale_filename}" end end end end
ruby
MIT
18606452ea0dd2afa82a71a0b924e93d8a255a83
2026-01-04T17:48:23.635701Z
false
adzap/active_enum
https://github.com/adzap/active_enum/blob/18606452ea0dd2afa82a71a0b924e93d8a255a83/lib/generators/active_enum/templates/config.rb
lib/generators/active_enum/templates/config.rb
# Form helper integration # require 'active_enum/form_helpers/simple_form' # for SimpleForm ActiveEnum.setup do |config| # Extend classes to add enumerate method # config.extend_classes = [ ActiveRecord::Base ] # Return name string as value for attribute method # config.use_name_as_value = false # Raise exception ActiveEnum::NotFound if enum value for a given id or name is not found # config.raise_on_not_found = false # Storage of values (:memory, :i18n) # config.storage = :memory end # ActiveEnum.define do # # enum(:enum_name) do # value 1 => 'Name' # end # # end
ruby
MIT
18606452ea0dd2afa82a71a0b924e93d8a255a83
2026-01-04T17:48:23.635701Z
false
adzap/active_enum
https://github.com/adzap/active_enum/blob/18606452ea0dd2afa82a71a0b924e93d8a255a83/lib/active_enum/version.rb
lib/active_enum/version.rb
module ActiveEnum VERSION = '1.3.0' end
ruby
MIT
18606452ea0dd2afa82a71a0b924e93d8a255a83
2026-01-04T17:48:23.635701Z
false
adzap/active_enum
https://github.com/adzap/active_enum/blob/18606452ea0dd2afa82a71a0b924e93d8a255a83/lib/active_enum/extensions.rb
lib/active_enum/extensions.rb
module ActiveEnum class EnumNotFound < StandardError; end module Extensions extend ActiveSupport::Concern included do class_attribute :enumerated_attributes end module ClassMethods # Declare an attribute to be enumerated by an enum class # # Example: # class Person < ActiveRecord::Base # enumerate :sex, :with => Sex # enumerate :sex # implies a Sex enum class exists # # # Pass a block to create implicit enum class namespaced by model e.g. Person::Sex # enumerate :sex do # value :id => 1, :name => 'Male' # end # # # Multiple attributes with same enum # enumerate :to, :from, :with => Sex # def enumerate(*attributes, &block) options = attributes.extract_options! self.enumerated_attributes ||= {} attributes_enum = {} attributes.each do |attribute| begin if block_given? enum = define_implicit_enum_class_for_attribute(attribute, block) else enum = options[:with] || attribute.to_s.camelize.constantize end attribute = attribute.to_sym attributes_enum[attribute] = enum define_active_enum_methods_for_attribute(attribute, options) unless options[:skip_accessors] rescue NameError => e raise e unless e.message.match?(/uninitialized constant/) raise ActiveEnum::EnumNotFound, "Enum class could not be found for attribute '#{attribute}' in class #{self}. Specify the enum class using the :with option." end end enumerated_attributes.merge!(attributes_enum) end def active_enum_for(attribute) enumerated_attributes && enumerated_attributes[attribute.to_sym] end def define_active_enum_methods_for_attribute(attribute, options={}) define_active_enum_read_method(attribute) unless options[:skip_read] define_active_enum_write_method(attribute) unless options[:skip_write] define_active_enum_question_method(attribute) unless options[:skip_predicate] end def define_implicit_enum_class_for_attribute(attribute, block) enum_class_name = "#{name}::#{attribute.to_s.camelize}" eval("class #{enum_class_name} < ActiveEnum::Base; end") enum = enum_class_name.constantize enum.class_eval(&block) enum end # Define read method to allow an argument for the enum component # # Examples: # user.sex # user.sex(:id) # user.sex(:name) # user.sex(:enum) # user.sex(:meta_key) # def define_active_enum_read_method(attribute) class_eval <<-DEF def #{attribute}(arg=nil) enum = self.class.active_enum_for(:#{attribute}) return enum if arg == :enum value = super() return if value.nil? case arg when nil #{ActiveEnum.use_name_as_value ? 'enum[value]' : 'value' } when :id value if enum.get(value, raise_on_not_found: false) when :name enum.get(value, raise_on_not_found: false).dup when Symbol (enum.meta(value, raise_on_not_found: false) || {})[arg].try(:dup) end end DEF end # Define write method to also handle enum value # # Examples: # user.sex = 1 # user.sex = :male # def define_active_enum_write_method(attribute) class_eval <<-DEF def #{attribute}=(arg) if arg.is_a?(Symbol) super(self.class.active_enum_for(:#{attribute})[arg]) else super end end DEF end # Define question method to check enum value against attribute value # # Example: # user.sex?(:male) # def define_active_enum_question_method(attribute) class_eval <<-DEF def #{attribute}?(arg=nil) if arg self.#{attribute}(:id).present? && self.#{attribute}(:id) == self.class.active_enum_for(:#{attribute})[arg] else super() end end DEF end end end end
ruby
MIT
18606452ea0dd2afa82a71a0b924e93d8a255a83
2026-01-04T17:48:23.635701Z
false
adzap/active_enum
https://github.com/adzap/active_enum/blob/18606452ea0dd2afa82a71a0b924e93d8a255a83/lib/active_enum/railtie.rb
lib/active_enum/railtie.rb
module ActiveEnum class Railtie < Rails::Railtie initializer "active_enum.active_record_extensions" do ActiveSupport.on_load(:active_record) do require 'active_enum/acts_as_enum' ActiveEnum.extend_classes << ActiveRecord::Base ActiveEnum.extend_classes! end end end end
ruby
MIT
18606452ea0dd2afa82a71a0b924e93d8a255a83
2026-01-04T17:48:23.635701Z
false
adzap/active_enum
https://github.com/adzap/active_enum/blob/18606452ea0dd2afa82a71a0b924e93d8a255a83/lib/active_enum/base.rb
lib/active_enum/base.rb
module ActiveEnum class DuplicateValue < StandardError; end class InvalidValue < StandardError; end class NotFound < StandardError; end class Base class << self attr_reader :store def inherited(subclass) ActiveEnum.enum_classes << subclass end # Define enum values. # # Examples: # value :id => 1, :name => 'Foo' # value :name => 'Foo' # implicit id, incrementing from 1. # value 1 => 'Foo' # def value(enum_value) store.set(*id_and_name_and_meta(enum_value)) end # Specify order enum values are returned. # Allowed values are :asc, :desc or :natural # def order(order) raise "Invalid order '#{order}' in #{self}" unless order.in?([:asc, :desc, :as_defined, :natural]) if order == :as_defined ActiveSupport::Deprecation.warn("You are using the order :as_defined which has been deprecated. Use :natural.") order = :natural end @order = order end # Array of arrays of stored values defined id, name, meta values hash def values store.values end alias_method :all, :values def each(&block) all.each(&block) end # Array of all enum id values def ids store.values.map { |v| v[0] } end # Array of all enum name values def names store.values.map { |v| v[1] } end # Return enum values in an array suitable to pass to a Rails form select helper. def to_select(value_transform: ActiveEnum.default_select_value_transform) store.values.map(&value_transform) end # Return enum values in a nested array suitable to pass to a Rails form grouped select helper. def to_grouped_select(group_by, group_transform: ActiveEnum.default_select_group_transform, value_transform: ActiveEnum.default_select_value_transform) store.values.group_by { |(_id, _name, meta)| (meta || {})[group_by] }.map { |group, collection| [ group_transform.call(group), collection.map { |(id, name, _meta)| [ name.html_safe, id ] } ] } end # Return a simple hash of key value pairs id => name for each value def to_h store.values.inject({}) { |hash, row| hash.merge(row[0] => row[1]) } end # Return count of values defined def length store.values.length end alias_method :size, :length # Access id or name value. Pass an id number to retrieve the name or # a symbol or string to retrieve the matching id. def get(index, raise_on_not_found: ActiveEnum.raise_on_not_found) row = get_value(index, raise_on_not_found) return if row.nil? index.is_a?(Integer) ? row[1] : row[0] end def [](index) get(index) end def include?(value) !get_value(value, false).nil? end # Access any meta data defined for a given id or name. Returns a hash. def meta(index, raise_on_not_found: ActiveEnum.raise_on_not_found) row = get_value(index, raise_on_not_found) row[2] || {} if row end private # Access value row array for a given id or name value. def get_value(index, raise_on_not_found = ActiveEnum.raise_on_not_found) if index.is_a?(Integer) store.get_by_id(index) else store.get_by_name(index) end || (raise_on_not_found ? raise(ActiveEnum::NotFound, "#{self} value for '#{index}' was not found") : nil) end def id_and_name_and_meta(hash) if hash.has_key?(:name) id = hash.fetch(:id) { next_id } name = hash.fetch(:name).freeze meta = hash.except(:id, :name).freeze return id, name, (meta.empty? ? nil : meta) elsif hash.keys.first.is_a?(Integer) return *Array(hash).first.tap { |arr| arr[1].freeze } else raise ActiveEnum::InvalidValue, "The value supplied, #{hash}, is not a valid format." end end def next_id ids.max.to_i + 1 end def store @store ||= ActiveEnum.storage_class.new(self, @order || :asc, ActiveEnum.storage_options) end end end end
ruby
MIT
18606452ea0dd2afa82a71a0b924e93d8a255a83
2026-01-04T17:48:23.635701Z
false
adzap/active_enum
https://github.com/adzap/active_enum/blob/18606452ea0dd2afa82a71a0b924e93d8a255a83/lib/active_enum/acts_as_enum.rb
lib/active_enum/acts_as_enum.rb
module ActiveEnum module ActsAsEnum module MacroMethods def acts_as_enum(options={}) extend ClassMethods class_attribute :active_enum_options self.active_enum_options = options.reverse_merge(name_column: 'name') end end module ClassMethods def enum_values select(Arel.sql("#{primary_key}, #{active_enum_options[:name_column]}")) .where(active_enum_options[:conditions]) .order(Arel.sql("#{primary_key} #{active_enum_options[:order]}")) end def values enum_values.map { |v| [ v.id, v.send(active_enum_options[:name_column]) ] } end def ids enum_values.map { |v| v.id } end def names enum_values.map { |v| v.send(active_enum_options[:name_column]) } end def to_select enum_values.map { |v| [v.send(active_enum_options[:name_column]), v.id] } end def [](index) get(index) end def get(index, raise_on_not_found: ActiveEnum.raise_on_not_found) row = get_value(index, raise_on_not_found) return if row.nil? index.is_a?(Integer) ? row.send(active_enum_options[:name_column]) : row.id end # Access any meta data defined for a given id or name. Returns a hash. def meta(index, raise_on_not_found: ActiveEnum.raise_on_not_found) row = lookup_relation(index).unscope(:select).first raise(ActiveEnum::NotFound, "#{self} value for '#{index}' was not found") if raise_on_not_found row&.attributes.except(primary_key.to_s, active_enum_options[:name_column].to_s) end # Enables use as a delimiter in inclusion validation def include?(value) return super if value.is_a?(Module) !self[value].nil? end private def get_value(index, raise_on_not_found = ActiveEnum.raise_on_not_found) lookup_relation(index).first || begin raise(ActiveEnum::NotFound, "#{self} value for '#{index}' was not found") if raise_on_not_found end end def lookup_relation(index) if index.is_a?(Integer) enum_values.where(id: index) else enum_values.where("lower(#{active_enum_options[:name_column]}) = lower(:name)", name: index.to_s) end end end end end ActiveRecord::Base.extend ActiveEnum::ActsAsEnum::MacroMethods
ruby
MIT
18606452ea0dd2afa82a71a0b924e93d8a255a83
2026-01-04T17:48:23.635701Z
false
adzap/active_enum
https://github.com/adzap/active_enum/blob/18606452ea0dd2afa82a71a0b924e93d8a255a83/lib/active_enum/storage/abstract_store.rb
lib/active_enum/storage/abstract_store.rb
module ActiveEnum module Storage autoload :MemoryStore, "active_enum/storage/memory_store" autoload :I18nStore, "active_enum/storage/i18n_store" class NotImplemented < StandardError; end class AbstractStore def initialize(enum_class, order, options={}) @enum, @order, @options = enum_class, order, options end def set(id, name, meta=nil) raise NotImplemented end def get_by_id(id) raise NotImplemented end def get_by_name(name) raise NotImplemented end def check_duplicate(id, name) if get_by_id(id) raise ActiveEnum::DuplicateValue, "#{@enum}: Duplicate id #{id}" elsif get_by_name(name) raise ActiveEnum::DuplicateValue, "#{@enum}: Duplicate name '#{name}'" end end def values _values end private def _values raise NotImplemented end end end end
ruby
MIT
18606452ea0dd2afa82a71a0b924e93d8a255a83
2026-01-04T17:48:23.635701Z
false
adzap/active_enum
https://github.com/adzap/active_enum/blob/18606452ea0dd2afa82a71a0b924e93d8a255a83/lib/active_enum/storage/i18n_store.rb
lib/active_enum/storage/i18n_store.rb
require 'i18n' module ActiveEnum module Storage class I18nStore < MemoryStore def get_by_id(id) row = _values.assoc(id) [ id, translate(row[1]), row[2] ].compact if row end def get_by_name(name) row = _values.rassoc(name.to_s) [ row[0], translate(row[1]), row[2] ].compact if row end def values _values.map { |(id, _)| get_by_id(id) } end def i18n_scope @i18n_scope ||= [ :active_enum ] + @enum.name.split("::").map { |nesting| nesting.underscore.to_sym } end def translate(key) I18n.translate key, scope: i18n_scope, default: key end end end end
ruby
MIT
18606452ea0dd2afa82a71a0b924e93d8a255a83
2026-01-04T17:48:23.635701Z
false
adzap/active_enum
https://github.com/adzap/active_enum/blob/18606452ea0dd2afa82a71a0b924e93d8a255a83/lib/active_enum/storage/memory_store.rb
lib/active_enum/storage/memory_store.rb
module ActiveEnum module Storage class MemoryStore < AbstractStore def set(id, name, meta=nil) check_duplicate id, name _values << [ id, name.to_s, meta ].compact sort! end def get_by_id(id) _values.assoc(id) end def get_by_name(name) _values.rassoc(name.to_s) || _values.rassoc(name.to_s.titleize) end def sort! case @order when :asc _values.sort! { |a,b| a[0] <=> b[0] } when :desc _values.sort! { |a,b| b[0] <=> a[0] } end end def _values @_values ||= [] end end end end
ruby
MIT
18606452ea0dd2afa82a71a0b924e93d8a255a83
2026-01-04T17:48:23.635701Z
false
adzap/active_enum
https://github.com/adzap/active_enum/blob/18606452ea0dd2afa82a71a0b924e93d8a255a83/lib/active_enum/form_helpers/simple_form.rb
lib/active_enum/form_helpers/simple_form.rb
require 'simple_form/version' module ActiveEnum module FormHelpers module SimpleForm module BuilderExtension def find_custom_type(attribute_name) return :enum if object.class.active_enum_for(attribute_name) if object.class.respond_to?(:active_enum_for) super end end end end end class ActiveEnum::FormHelpers::SimpleForm::EnumInput < ::SimpleForm::Inputs::CollectionSelectInput def initialize(*args) super raise "Attribute '#{attribute_name}' has no enum class" unless enum = object.class.active_enum_for(attribute_name) input_options[:collection] = enum.to_select end end class ActiveEnum::FormHelpers::SimpleForm::GroupedEnumInput < ::SimpleForm::Inputs::GroupedCollectionSelectInput def initialize(*args) super raise "Attribute '#{attribute_name}' has no enum class" unless enum = object.class.active_enum_for(attribute_name) input_options[:collection] = enum.to_grouped_select(input_options[:group_by]) input_options[:group_method] = :last end end SimpleForm::FormBuilder.class_eval do prepend ActiveEnum::FormHelpers::SimpleForm::BuilderExtension map_type :enum, to: ActiveEnum::FormHelpers::SimpleForm::EnumInput map_type :grouped_enum, to: ActiveEnum::FormHelpers::SimpleForm::GroupedEnumInput alias_method :collection_enum, :collection_select end
ruby
MIT
18606452ea0dd2afa82a71a0b924e93d8a255a83
2026-01-04T17:48:23.635701Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/test/test_helper.rb
test/test_helper.rb
begin require "hector" require "test/unit" require "mocha/test_unit" rescue LoadError => e if require "rubygems" retry else raise e end end $:.unshift File.dirname(__FILE__) + "/lib" require "logger" TEST_LOG_DIR = File.expand_path(File.dirname(__FILE__) + "/../log") Hector.logger = Logger.new(File.open(TEST_LOG_DIR + "/test.log", "w+")) require "hector/test_case" require "hector/test_connection" require "hector/test_deference" require "hector/test_heartbeat" require "hector/test_service" require "hector/integration_test" module Hector def self.fixture_path(filename) File.join(File.dirname(__FILE__), "fixtures", filename) end IDENTITY_FIXTURES = fixture_path("identities.yml") Identity.adapter = YamlIdentityAdapter.new(IDENTITY_FIXTURES) end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/test/integration/services_test.rb
test/integration/services_test.rb
require "test_helper" module Hector class ServicesTest < IntegrationTest def setup super Hector::Session.register(Hector::TestService.new("TestService")) end test :"intercepting a channel message and delivering a replacement from the origin" do authenticated_connections(:join => "#test") do |c1, c2| c1.receive_line "PRIVMSG #test :!reverse foo bar" assert_not_sent_to c1, ":user1!sam@hector.irc PRIVMSG #test :rab oof" assert_not_sent_to c2, ":user1!sam@hector.irc PRIVMSG #test :!reverse foo bar" assert_sent_to c2, ":user1!sam@hector.irc PRIVMSG #test :rab oof" end end test :"intercepting a channel message and delivering a replacement from the service" do authenticated_connections(:join => "#test") do |c1, c2| c1.receive_line "PRIVMSG #test :!sum 2 3" assert_not_sent_to c2, ":user1!sam@hector.irc PRIVMSG #test :!sum 2 3" assert_sent_to c1, ":TestService!~TestService@hector.irc PRIVMSG #test :2 + 3 = 5" assert_sent_to c2, ":TestService!~TestService@hector.irc PRIVMSG #test :2 + 3 = 5" end end test :"WHO responses should not include services" do authenticated_connections(:join => "#test") do |c1, c2| c2.receive_line "WHO #test" assert_sent_to c2, ":hector.irc 352 user2 #test sam hector.irc hector.irc user1 H :0 Sam Stephenson" assert_sent_to c2, ":hector.irc 352 user2 #test sam hector.irc hector.irc user2 H :0 Sam Stephenson" assert_sent_to c2, ":hector.irc 315 user2 #test" end end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/test/integration/messaging_test.rb
test/integration/messaging_test.rb
require "test_helper" module Hector class MessagingTest < IntegrationTest test :"messages can be sent between two sessions" do authenticated_connections do |c1, c2| c1.receive_line "PRIVMSG user2 :hello world" assert_sent_to c2, ":user1!sam@hector.irc PRIVMSG user2 :hello world" end end test :"notices can be sent between two sessions" do authenticated_connections do |c1, c2| c1.receive_line "NOTICE user2 :hello world" assert_sent_to c2, ":user1!sam@hector.irc NOTICE user2 :hello world" end end test :"sending a message to a nonexistent session should result in a 401" do authenticated_connection.tap do |c| c.receive_line "PRIVMSG clint :hi clint" assert_no_such_nick_or_channel c, "clint" end end test :"sending a notice to a nonexistent session should result in a 401" do authenticated_connection.tap do |c| c.receive_line "NOTICE clint :hi clint" assert_no_such_nick_or_channel c, "clint" end end test :"sending a message to a nonexistent channel should respond with a 401" do authenticated_connection.tap do |c| c.receive_line "PRIVMSG #test :hello" assert_no_such_nick_or_channel c, "#test" end end test :"sending a notice to a nonexistent channel should respond with a 401" do authenticated_connection.tap do |c| c.receive_line "NOTICE #test :hello" assert_no_such_nick_or_channel c, "#test" end end test :"sending a message to an unjoined channel should respond with a 404" do authenticated_connections do |c1, c2| c1.receive_line "JOIN #test" c2.receive_line "PRIVMSG #test :hello" assert_cannot_send_to_channel c2, "#test" end end test :"sending a notice to an unjoined channel should respond with a 404" do authenticated_connections do |c1, c2| c1.receive_line "JOIN #test" c2.receive_line "NOTICE #test :hello" assert_cannot_send_to_channel c2, "#test" end end test :"sending a message to a joined channel should broadcast it to everyone except the sender" do authenticated_connections(:join => "#test") do |c1, c2, c3| assert_nothing_sent_to(c1) { c1.receive_line "PRIVMSG #test :hello" } assert_sent_to c2, ":user1!sam@hector.irc PRIVMSG #test :hello" assert_sent_to c3, ":user1!sam@hector.irc PRIVMSG #test :hello" end end test :"sending a notice to a joined channel should broadcast it to everyone except the sender" do authenticated_connections(:join => "#test") do |c1, c2, c3| assert_nothing_sent_to(c1) { c1.receive_line "NOTICE #test :hello" } assert_sent_to c2, ":user1!sam@hector.irc NOTICE #test :hello" assert_sent_to c3, ":user1!sam@hector.irc NOTICE #test :hello" end end test :"messages can be sent between two sessions, one with an away message" do authenticated_connections do |c1, c2| c2.receive_line "AWAY :bai" c1.receive_line "PRIVMSG user2 :hello world" assert_sent_to c2, ":user1!sam@hector.irc PRIVMSG user2 :hello world" assert_sent_to c1, ":hector.irc 301 user2 :bai" end end test :"messages can be sent between two sessions, neither away" do authenticated_connections do |c1, c2| c2.receive_line "AWAY :bai" c2.receive_line "AWAY" c1.receive_line "PRIVMSG user2 :hello world" assert_sent_to c2, ":user1!sam@hector.irc PRIVMSG user2 :hello world" assert_not_sent_to c1, ":hector.irc 301 user2 :bai" end end test :"users can be invited to channels and only the invited user gets the message" do authenticated_connections do |c1,c2,c3| c1.receive_line "JOIN #test" c1.receive_line "INVITE user2 :#test" assert_sent_to c2, ":user1!sam@hector.irc INVITE user2 :#test" assert_not_sent_to c3, ":user1!sam@hector.irc INVITE user2 :#test" end end test :"users cannot invite non-existent users" do authenticated_connections do |c| c.receive_line "JOIN #test" c.receive_line "INVITE user2 :#test" assert_no_such_nick_or_channel c, "user2" end end test :"users cannot invite a user to a channel they are already in" do authenticated_connections do |c1,c2| c1.receive_line "JOIN #test" c2.receive_line "JOIN #test" c1.receive_line "INVITE user2 :#test" assert_not_sent_to c2, ":user1!sam@hector.irc INVITE user2 :#test" assert_sent_to c1, ":hector.irc 443 user2 #test is already on channel" end end test :"users cannot invite someone to a channel they aren't in" do authenticated_connections do |c1,c2,c3| c1.receive_line "INVITE user2 :#test" assert_sent_to c1, ":hector.irc 442 #test You're not on that channel" end end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/test/integration/connection_test.rb
test/integration/connection_test.rb
# encoding: UTF-8 require "test_helper" module Hector class ConnectionTest < IntegrationTest test :"connecting without specifying a password shouldn't create a session" do connection.tap do |c| user! c nick! c assert_nil c.session end end test :"connecting with an invalid password should respond with a 464" do connection.tap do |c| pass! c, "invalid" user! c nick! c assert_nil c.session assert_invalid_password c assert_closed c end end test :"connecting with a valid password should create a session" do authenticated_connection.tap do |c| assert_not_nil c.session assert_welcomed c assert_not_closed c end end test :"sending a concatenated username and password with PASS should create a session" do connection.tap do |c| pass! c, "sam:secret" user! c nick! c assert_not_nil c.session assert_welcomed c assert_not_closed c end end test :"sending a username and password with PASS should create a session even if USER credentials are incorrect" do connection.tap do |c| pass! c, "sam:secret" user! c, "invalid" nick! c assert_not_nil c.session assert_welcomed c assert_not_closed c end end test :"sending an invalid concatenated username and password with PASS should respond with a 464" do connection.tap do |c| pass! c, "sam:invalid" user! c nick! c assert_nil c.session assert_invalid_password c assert_closed c end end test :"sending an unknown command before registration should result in immediate disconnection" do connection.tap do |c| pass! c assert_not_closed c c.receive_line "FOO" assert_closed c end end test :"sending CAP before registration should be ignored" do connection.tap do |c| c.receive_line "CAP LS" assert_not_closed c pass! c user! c nick! c assert_welcomed c end end test :"sending a command after registration should forward it to the session" do authenticated_connection.tap do |c| c.session.expects(:on_foo) c.receive_line "FOO" end end test :"sending QUIT after registration should result in disconnection" do authenticated_connection.tap do |c| c.receive_line "QUIT" assert_closed c end end test :"disconnecting should destroy the session" do authenticated_connection.tap do |c| c.session.expects(:destroy) c.unbind end end test :"two connections can't use the same nickname" do c1 = authenticated_connection("sam") assert_welcomed c1 c2 = authenticated_connection("sam") assert_nickname_in_use c2 assert_nil c2.session assert_not_closed c2 end test :"disconnecting frees the nickname for future use" do c1 = authenticated_connection("sam") c1.unbind c2 = authenticated_connection("sam") assert_welcomed c2 end test :"sending the ping command should respond with a pong" do authenticated_connection.tap do |c| c.receive_line "PING 12345" assert_sent_to c, ":hector.irc PONG hector.irc :12345" end end test :"quitting should respond with an error" do authenticated_connection.tap do |c| c.receive_line "QUIT :bye" assert_sent_to c, "ERROR :Closing Link: sam[hector] (Quit: bye)" end end test :"sending a privmsg should reset idle time" do authenticated_connection.tap do |c| sleep 1 assert_not_equal 0, c.session.seconds_idle c.receive_line "PRIVMSG joe :hey testing" sleep 1 assert_not_equal 0, c.session.seconds_idle assert c.session.seconds_idle < 2 end end test :"nicknames can be changed" do authenticated_connection("sam").tap do |c| c.receive_line "NICK joe" assert_sent_to c, ":sam NICK joe" c.receive_line "NICK jöe" assert_sent_to c, ":joe NICK jöe" end end test :"changing to a new nickname coerces it to UTF-8" do authenticated_connection("sam").tap do |c| c.receive_line "NICK säm".force_encoding("ASCII-8BIT") c.receive_line "NICK lée".force_encoding("ASCII-8BIT") c.receive_line "NICK røss".force_encoding("ASCII-8BIT") assert_sent_to c, ":sam NICK säm" assert_sent_to c, ":säm NICK lée" assert_sent_to c, ":lée NICK røss" end end if String.method_defined?(:force_encoding) test :"changing to an invalid nickname should respond with 432" do authenticated_connection("sam").tap do |c| c.receive_line "NICK $" assert_erroneous_nickname c, "$" end end test :"changing to a nickname that's already in use should respond with 433" do authenticated_connections do |c1, c2| c2.receive_line "NICK user1" assert_nickname_in_use c2, "user1" end end test :"away messages can be changed" do authenticated_connection("sam").tap do |c| c.receive_line "AWAY :bai guys" assert_sent_to c, ":hector.irc 306 :You have been marked as being away" c.receive_line "AWAY" assert_sent_to c, ":hector.irc 305 :You are no longer marked as being away" end end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/test/integration/keep_alive_test.rb
test/integration/keep_alive_test.rb
require "test_helper" module Hector class KeepAliveTest < IntegrationTest test :"keep-alive ping is sent on pulse" do authenticated_connection.tap do |c| assert_not_sent_to c, "PING hector.irc" assert_sent_to c, "PING hector.irc" do pulse(c) end assert !c.connection_closed? end end test :"responding with pong results in another ping on the next pulse" do authenticated_connection.tap do |c| pulse(c) c.receive_line "PONG hector.irc" assert_sent_to c, "PING hector.irc" do pulse(c) end assert !c.connection_closed? end end test :"not responding with pong results in disconnection on the next pulse" do authenticated_connection.tap do |c| pulse(c) assert_not_sent_to c, "PING hector.irc" do pulse(c) end assert c.connection_closed? end end test :"channel members are notified of keep-alive timeouts" do authenticated_connections(:join => "#test") do |c1, c2| pulse(c1) assert_sent_to c2, ":user1!sam@hector.irc QUIT" do pulse(c1) end end end def pulse(connection) heartbeat(connection).pulse end def heartbeat(connection) connection.session.instance_variable_get(:@heartbeat) end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/test/integration/async_authentication_test.rb
test/integration/async_authentication_test.rb
require "test_helper" require "hector/async_identity_adapter" module Hector class AsyncAuthenticationTest < IntegrationTest def setup super @yaml_identity_adapter = Identity.adapter Identity.adapter = AsyncIdentityAdapter.new(IDENTITY_FIXTURES) end def teardown super Identity.adapter = @yaml_identity_adapter end test :"connecting with an invalid password" do connection.tap do |c| pass! c, "invalid" user! c nick! c assert_nil c.session assert_invalid_password c assert_closed c end end test :"connecting with a nonexistent username" do connection.tap do |c| pass! c, "invalid" user! c, "invalid" assert_nil c.session assert_invalid_password c assert_closed c end end test :"connecting with a valid username and password" do connection.tap do |c| pass! c user! c nick! c assert_not_nil c.session assert_welcomed c assert_not_closed c end end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/test/integration/channels_test.rb
test/integration/channels_test.rb
# encoding: UTF-8 require "test_helper" module Hector class ChannelsTest < IntegrationTest test :"channels can be joined" do authenticated_connections do |c1, c2| c1.receive_line "JOIN #test" assert_sent_to c1, ":user1!sam@hector.irc JOIN :#test" c2.receive_line "JOIN #test" assert_sent_to c1, ":user2!sam@hector.irc JOIN :#test" assert_sent_to c2, ":user2!sam@hector.irc JOIN :#test" end end test :"channel names can only start with accepted characters" do authenticated_connection.tap do |c| c.receive_line "JOIN #test" assert_sent_to c, ":sam!sam@hector.irc JOIN :#test" c.receive_line "JOIN &test" assert_sent_to c, ":sam!sam@hector.irc JOIN :&test" c.receive_line "JOIN +test" assert_sent_to c, ":sam!sam@hector.irc JOIN :+test" c.receive_line "JOIN !test" assert_sent_to c, ":sam!sam@hector.irc JOIN :!test" c.receive_line "JOIN @test" assert_not_sent_to c, ":sam!sam@hector.irc JOIN :@test" assert_no_such_channel c, "@test" end end test :"channel names can contain prefix characters" do authenticated_connection.tap do |c| c.receive_line "JOIN ##" assert_sent_to c, ":sam!sam@hector.irc JOIN :##" c.receive_line "JOIN #test#" assert_sent_to c, ":sam!sam@hector.irc JOIN :#test#" c.receive_line "JOIN #&" assert_sent_to c, ":sam!sam@hector.irc JOIN :#&" c.receive_line "JOIN ++&#" assert_sent_to c, ":sam!sam@hector.irc JOIN :++&#" c.receive_line "JOIN !te&t" assert_sent_to c, ":sam!sam@hector.irc JOIN :!te&t" c.receive_line "JOIN #8*(&x" assert_sent_to c, ":sam!sam@hector.irc JOIN :#8*(&x" end end test :"joining a channel twice does nothing" do authenticated_connection.tap do |c| c.receive_line "JOIN #test" assert_nothing_sent_to(c) do c.receive_line "JOIN #test" end end end test :"joining an invalid channel name responds with a 403" do authenticated_connection.tap do |c| c.receive_line "JOIN #te,st" assert_no_such_channel c, "#te,st" end end test :"joining a channel should send session nicknames" do authenticated_connections(:join => "#test") do |c1, c2, c3| assert_sent_to c1, ":hector.irc 353 user1 = #test :user1" assert_sent_to c2, ":hector.irc 353 user2 = #test :user1 user2" assert_sent_to c3, ":hector.irc 353 user3 = #test :user1 user2 user3" end end test :"channels can be parted" do authenticated_connections(:join => "#test") do |c1, c2| c1.receive_line "PART #test :lämnar" assert_sent_to c1, ":user1!sam@hector.irc PART #test :lämnar" assert_sent_to c2, ":user1!sam@hector.irc PART #test :lämnar" end end test :"parting a channel should remove the session from the channel" do authenticated_connections(:join => "#test") do |c1, c2| c1.receive_line "PART #test" sent_data = capture_sent_data(c2) { c2.receive_line "NAMES #test" } assert sent_data !~ /user1/ end end test :"quitting should notify all the session's peers" do authenticated_connections(:join => "#test") do |c1, c2, c3| c1.receive_line "QUIT :outta here" assert_not_sent_to c1, ":user1!sam@hector.irc QUIT :Quit: outta here" assert_sent_to c2, ":user1!sam@hector.irc QUIT :Quit: outta here" assert_sent_to c3, ":user1!sam@hector.irc QUIT :Quit: outta here" end end test :"quitting should notify peers only once" do authenticated_connections(:join => ["#test1", "#test2"]) do |c1, c2| sent_data = capture_sent_data(c2) { c1.receive_line "QUIT :outta here" } assert_equal ":user1!sam@hector.irc QUIT :Quit: outta here\r\n", sent_data end end test :"quitting should remove the session from its channels" do authenticated_connections(:join => ["#test1", "#test2"]) do |c1, c2| c1.receive_line "QUIT :bye" sent_data = capture_sent_data(c2) do c2.receive_line "NAMES #test1" c2.receive_line "NAMES #test2" end assert sent_data !~ /user1/ end end test :"disconnecting without quitting should notify peers" do authenticated_connections(:join => "#test") do |c1, c2| c1.close_connection assert_sent_to c2, ":user1!sam@hector.irc QUIT :Connection closed" end end test :"disconnecting should remove the session from its channels" do authenticated_connections(:join => ["#test1", "#test2"]) do |c1, c2| c1.close_connection sent_data = capture_sent_data(c2) do c2.receive_line "NAMES #test1" c2.receive_line "NAMES #test2" end assert sent_data !~ /user1/ end end test :"names command should send session nicknames" do authenticated_connections(:join => "#test") do |c1, c2, c3| c1.receive_line "NAMES #test" assert_sent_to c1, ":hector.irc 353 user1 = #test :user1 user2 user3" assert_sent_to c1, ":hector.irc 366 user1 #test :" end end test :"names command should be split into 512-byte responses" do authenticated_connections(:join => "#test") do |c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c14, c15, c16, c17, c18, c19, c20, c21, c22, c23, c24, c25, c26, c27, c28, c29, c30, c31, c32, c33, c34, c35, c36, c37, c38, c39, c40, c41, c42, c43, c44, c45, c46, c47, c48, c49, c50, c51, c52, c53, c54, c55, c56, c57, c58, c59, c60, c61, c62, c63, c64, c65, c66, c67, c68, c69, c70| c1.receive_line "NAMES #test" assert_sent_to c1, ":hector.irc 353 user1 = #test :user1 user2 user3 user4 user5 user6 user7 user8 user9 user10 user11 user12 user13 user14 user15 user16 user17 user18 user19 user20 user21 user22 user23 user24 user25 user26 user27 user28 user29 user30 user31 user32 user33 user34 user35 user36 user37 user38 user39 user40 user41 user42 user43 user44 user45 user46 user47 user48 user49 user50 user51 user52 user53 user54 user55 user56 user57 user58 user59 user60 user61 user62 user63 user64 user65 user66 user67 user68 user69" assert_sent_to c1, ":hector.irc 353 user1 = #test :user70" assert_sent_to c1, ":hector.irc 366 user1 #test :" end end test :"topic command with text should set the channel topic" do authenticated_connections(:join => "#test") do |c1, c2| c1.receive_line "TOPIC #test :this is my topic" assert_sent_to c1, ":user1!sam@hector.irc TOPIC #test :this is my topic" assert_sent_to c2, ":user1!sam@hector.irc TOPIC #test :this is my topic" end end test :"topic command with no arguments should send the channel topic" do authenticated_connection.tap do |c| c.receive_line "JOIN #test" c.receive_line "TOPIC #test :hello world" assert_sent_to c, ":hector.irc 332 sam #test :hello world" do c.receive_line "TOPIC #test" end end end test :"topic command sends timestamp and nickname" do authenticated_connection.tap do |c| c.receive_line "JOIN #test" c.receive_line "TOPIC #test :hello world" assert_sent_to c, /^:hector\.irc 333 sam #test sam \d+/ do c.receive_line "TOPIC #test" end end end test :"topic command with no arguments should send 331 when no topic is set" do authenticated_connection.tap do |c| c.receive_line "JOIN #test" assert_sent_to c, ":hector.irc 331 sam #test :" do c.receive_line "TOPIC #test" end end end test :"channel topics are erased when the last session parts" do authenticated_connection("sam").tap do |c| c.receive_line "JOIN #test" c.receive_line "TOPIC #test :hello world" c.receive_line "PART #test" end authenticated_connection("clint").tap do |c| c.receive_line "JOIN #test" assert_not_sent_to c, ":hector.irc 332 clint #test :hello world" end end test :"channel topics are erased when the last session quits" do authenticated_connection("sam").tap do |c| c.receive_line "JOIN #test" c.receive_line "TOPIC #test :hello world" c.receive_line "QUIT" end authenticated_connection("clint").tap do |c| c.receive_line "JOIN #test" assert_not_sent_to c, ":hector.irc 332 clint #test :hello world" end end test :"sending a WHO command to an empty or undefined channel should produce an end of list message" do authenticated_connection.tap do |c| c.receive_line "WHO #test" assert_sent_to c, ":hector.irc 315 sam #test" assert_not_sent_to c, ":hector.irc 352" end end test :"sending a WHO command to a channel you have joined should list each occupant's info" do authenticated_connections(:join => "#test") do |c1, c2| c2.receive_line "WHO #test" assert_sent_to c2, ":hector.irc 352 user2 #test sam hector.irc hector.irc user1 H :0 Sam Stephenson" assert_sent_to c2, ":hector.irc 352 user2 #test sam hector.irc hector.irc user2 H :0 Sam Stephenson" assert_sent_to c2, ":hector.irc 315 user2 #test" end end test :"sending a WHO command to an active channel you've not yet joined should still list everyone" do authenticated_connections do |c1, c2, c3| c1.receive_line "JOIN #test" c2.receive_line "JOIN #test" c3.receive_line "WHO #test" assert_sent_to c3, ":hector.irc 352 user3 #test sam hector.irc hector.irc user1 H :0 Sam Stephenson" assert_sent_to c3, ":hector.irc 352 user3 #test sam hector.irc hector.irc user2 H :0 Sam Stephenson" assert_sent_to c3, ":hector.irc 315 user3 #test" end end test :"sending a WHO command about a real user should list their user data" do authenticated_connections do |c1, c2| c1.receive_line "WHO user2" assert_sent_to c1, ":hector.irc 352 user1 user2 sam hector.irc hector.irc user2 H :0 Sam Stephenson" assert_sent_to c1, ":hector.irc 315 user1 user2" end end test :"sending a WHO command about a non-existent user should produce an end of list message" do authenticated_connection.tap do |c| c.receive_line "WHO user2" assert_sent_to c, ":hector.irc 315 sam user2" assert_not_sent_to c, ":hector.irc 352" end end test :"sending a WHOIS on a non-existent user should reply with a 401 then 318" do authenticated_connection.tap do |c| c.receive_line "WHOIS user2" assert_sent_to c, ":hector.irc 401" assert_sent_to c, ":hector.irc 318" end end test :"sending a WHOIS on a user not on any channels should list the following items and 318" do authenticated_connections do |c1, c2| c1.receive_line "WHOIS user2" assert_sent_to c1, ":hector.irc 311" assert_sent_to c1, ":hector.irc 312" assert_sent_to c1, ":hector.irc 317" assert_sent_to c1, ":hector.irc 318" assert_not_sent_to c1, ":hector.irc 319" # no channels end end test :"sending a WHOIS on a user on channels should list the following items and 318" do authenticated_connections(:join => "#test") do |c1, c2| c1.receive_line "WHOIS user2" assert_sent_to c1, ":hector.irc 311" assert_sent_to c1, ":hector.irc 312" assert_sent_to c1, ":hector.irc 319" assert_sent_to c1, ":hector.irc 317" assert_sent_to c1, ":hector.irc 318" end end test :"sending a WHOIS to a user with an away message should send a 301" do authenticated_connections(:join => "#test") do |c1, c2| c2.receive_line "AWAY :wut heh" c1.receive_line "WHOIS user2" assert_sent_to c1, ":hector.irc 301" end end test :"whois includes the correct channels" do authenticated_connections(:join => "#test") do |c1, c2| c2.receive_line "JOIN #tset" c2.receive_line "WHOIS user1" assert_not_sent_to c2, /^:hector\.irc 319.*#tset.*/ end end test :"requesting the modes for a channel should reply with 324 and 329" do authenticated_connection.tap do |c| c.receive_line "JOIN #test" c.receive_line "MODE #test" assert_sent_to c, ":hector.irc 324" assert_sent_to c, /^:hector\.irc 329 sam #test \d+/ assert_not_sent_to c, ":hector.irc 368" end end test :"requesting the ban list for a channel should reply with 368" do authenticated_connection.tap do |c| c.receive_line "JOIN #test" c.receive_line "MODE #test b" assert_not_sent_to c, ":hector.irc 324" assert_not_sent_to c, ":hector.irc 329" assert_sent_to c, ":hector.irc 368" end end test :"requesting modes for a non-existent channel should return 401" do authenticated_connection.tap do |c| c.receive_line "MODE #test" assert_no_such_nick_or_channel c, "#test" assert_not_sent_to c, ":hector.irc 324" assert_not_sent_to c, ":hector.irc 329" assert_not_sent_to c, ":hector.irc 368" end end test :"requesting modes for a user should return 221" do authenticated_connection.tap do |c| c.receive_line "MODE sam" assert_sent_to c, ":hector.irc 221" end end test :"requesting modes for a non-existent user should return 401" do authenticated_connection.tap do |c| c.receive_line "MODE bob" assert_no_such_nick_or_channel c, "bob" assert_not_sent_to c, ":hector.irc 221" end end test :"changing nicknames should notify peers" do authenticated_connections(:join => "#test") do |c1, c2, c3, c4| c4.receive_line "PART #test" c1.receive_line "NICK sam" assert_sent_to c1, ":user1 NICK sam" assert_sent_to c2, ":user1 NICK sam" assert_sent_to c3, ":user1 NICK sam" assert_not_sent_to c4, ":user1 NICK sam" end end test :"changing realname should notify peers" do authenticated_connections(:join => "#test") do |c1, c2, c3, c4| c4.receive_line "PART #test" c1.receive_line "REALNAME :Sam Stephenson" assert_sent_to c1, /^:hector\.irc 352 user1 .* user1 H :0 Sam Stephenson/ assert_sent_to c2, /^:hector\.irc 352 user2 .* user1 H :0 Sam Stephenson/ assert_sent_to c3, /^:hector\.irc 352 user3 .* user1 H :0 Sam Stephenson/ assert_not_sent_to c4, ":hector.irc 352 user4" end end test :"multiple channels can be joined with a single command" do authenticated_connection.tap do |c| c.receive_line "JOIN #channel1,#channel2,#channel3" assert_sent_to c, ":sam!sam@hector.irc JOIN :#channel1" assert_sent_to c, ":sam!sam@hector.irc JOIN :#channel2" assert_sent_to c, ":sam!sam@hector.irc JOIN :#channel3" end end test :"unicode channels can be joined" do authenticated_connection.tap do |c| c.receive_line "JOIN #リンゴ" c.receive_line "JOIN #tuffieħa" c.receive_line "JOIN #تفاحة" c.receive_line "JOIN #תפוח" c.receive_line "JOIN #яблоко" c.receive_line "JOIN #" c.receive_line "JOIN #☬☃☢☠☆☆☆" c.receive_line "JOIN #ǝʃddɐ" assert_sent_to c, ":sam!sam@hector.irc JOIN :#リンゴ" assert_sent_to c, ":sam!sam@hector.irc JOIN :#tuffieħa" assert_sent_to c, ":sam!sam@hector.irc JOIN :#تفاحة" assert_sent_to c, ":sam!sam@hector.irc JOIN :#תפוח" assert_sent_to c, ":sam!sam@hector.irc JOIN :#яблоко" assert_sent_to c, ":sam!sam@hector.irc JOIN :#" assert_sent_to c, ":sam!sam@hector.irc JOIN :#☬☃☢☠☆☆☆" assert_sent_to c, ":sam!sam@hector.irc JOIN :#ǝʃddɐ" end end test :"channel names are coerced to UTF-8" do authenticated_connection.tap do |c| c.receive_line "JOIN #chännel".force_encoding("ASCII-8BIT") c.receive_line "JOIN #channèl".force_encoding("ASCII-8BIT") assert_sent_to c, ":sam!sam@hector.irc JOIN :#chännel" assert_sent_to c, ":sam!sam@hector.irc JOIN :#channèl" end end if String.method_defined?(:force_encoding) test :"names command with unicode nicks should still be split into 512-byte responses" do authenticated_connections(:join => "#test", :nickname => "⌘lee") do |c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c14, c15, c16, c17, c18, c19, c20, c21, c22, c23, c24, c25, c26, c27, c28, c29, c30, c31, c32, c33, c34, c35, c36, c37, c38, c39, c40, c41, c42, c43, c44, c45, c46, c47, c48, c49, c50, c51, c52, c53, c54, c55, c56, c57, c58, c59, c60, c61, c62, c63, c64, c65, c66, c67, c68, c69, c70| c1.receive_line "NAMES #test" first_line = ":hector.irc 353 ⌘lee1 = #test :⌘lee1 ⌘lee2 ⌘lee3 ⌘lee4 ⌘lee5 ⌘lee6 ⌘lee7 ⌘lee8 ⌘lee9 ⌘lee10 ⌘lee11 ⌘lee12 ⌘lee13 ⌘lee14 ⌘lee15 ⌘lee16 ⌘lee17 ⌘lee18 ⌘lee19 ⌘lee20 ⌘lee21 ⌘lee22 ⌘lee23 ⌘lee24 ⌘lee25 ⌘lee26 ⌘lee27 ⌘lee28 ⌘lee29 ⌘lee30 ⌘lee31 ⌘lee32 ⌘lee33 ⌘lee34 ⌘lee35 ⌘lee36 ⌘lee37 ⌘lee38 ⌘lee39 ⌘lee40 ⌘lee41 ⌘lee42 ⌘lee43 ⌘lee44 ⌘lee45 ⌘lee46 ⌘lee47 ⌘lee48 ⌘lee49 ⌘lee50 ⌘lee51 ⌘lee52 ⌘lee53 ⌘lee54\r\n" second_line = ":hector.irc 353 ⌘lee1 = #test :⌘lee55 ⌘lee56 ⌘lee57 ⌘lee58 ⌘lee59 ⌘lee60 ⌘lee61 ⌘lee62 ⌘lee63 ⌘lee64 ⌘lee65 ⌘lee66 ⌘lee67 ⌘lee68 ⌘lee69 ⌘lee70\r\n" assert_sent_to c1, first_line assert_sent_to c1, second_line assert_sent_to c1, ":hector.irc 366 ⌘lee1 #test :" assert (first_line.size < 512) assert (second_line.size < 512) end end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/test/lib/hector/integration_test.rb
test/lib/hector/integration_test.rb
module Hector class IntegrationTest < TestCase def setup reset! end def teardown reset! end def reset! Session.reset! Channel.reset! end def authenticated_connection(nickname = "sam") connection.tap do |c| authenticate! c, nickname end end def authenticated_connections(options = {}, &block) nickname = options[:nickname] || "user" connections = Array.new(block.arity) do |i| authenticated_connection("#{nickname}#{i+1}").tap do |c| if options[:join] Array(options[:join]).each do |channel| c.receive_line("JOIN #{channel}") end end end end yield *connections end def authenticate!(connection, nickname) pass! connection user! connection nick! connection, nickname end def pass!(connection, password = "secret") connection.receive_line("PASS #{password}") end def user!(connection, username = "sam", realname = "Sam Stephenson") connection.receive_line("USER #{username} * 0 :#{realname}") end def nick!(connection, nickname = "sam") connection.receive_line("NICK #{nickname}") end def connection_nickname(connection) connection.instance_variable_get(:@nickname) end def capture_sent_data(connection) length = connection.sent_data.length yield connection.sent_data[length..-1] end def assert_sent_to(connection, line, &block) sent_data = block ? capture_sent_data(connection, &block) : connection.sent_data assert sent_data =~ /^#{line.is_a?(Regexp) ? line : Regexp.escape(line)}/, explain_sent_to(line, sent_data) end def explain_sent_to(line, sent_data) [].tap do |lines| lines.push("Expected to receive #{line.inspect}, but did not receive it:") lines.concat(sent_data.split(/[\r\n]+/).map { |line| line.inspect }) end.join("\n") end def assert_not_sent_to(connection, line, &block) sent_data = block ? capture_sent_data(connection, &block) : connection.sent_data assert sent_data !~ /^#{line.is_a?(Regexp) ? line : Regexp.escape(line)}/, explain_not_sent_to(line, sent_data) end def explain_not_sent_to(line, sent_data) sent_data = sent_data.split(/[\r\n]+/).map do |sent_line| sent_line !~ /^#{line.is_a?(Regexp) ? line : Regexp.escape(line)}/ ? " #{sent_line.inspect}" : "* #{sent_line.inspect}" end line_number = sent_data.index { |line| line[0, 2] == "* " } [].tap do |lines| lines.push("Expected not to receive #{line.inspect}, but received it on line #{line_number}:") lines.concat(sent_data) end.join("\n") end def assert_nothing_sent_to(connection, &block) assert_equal "", capture_sent_data(connection, &block) end def assert_welcomed(connection) assert_sent_to connection, ":hector.irc 001 #{connection_nickname(connection)} :" assert_sent_to connection, ":hector.irc 422 :" end def assert_no_such_nick_or_channel(connection, nickname) assert_sent_to connection, ":hector.irc 401 #{nickname} :" end def assert_no_such_channel(connection, channel) assert_sent_to connection, ":hector.irc 403 #{channel} :" end def assert_cannot_send_to_channel(connection, channel) assert_sent_to connection, ":hector.irc 404 #{channel} :" end def assert_erroneous_nickname(connection, nickname = connection_nickname(connection)) assert_sent_to connection, ":hector.irc 432 #{nickname} :" end def assert_nickname_in_use(connection, nickname = connection_nickname(connection)) assert_sent_to connection, ":hector.irc 433 * #{nickname} :" end def assert_invalid_password(connection) assert_sent_to connection, ":hector.irc 464 :" end def assert_closed(connection) assert connection.connection_closed? end def assert_not_closed(connection) assert !connection.connection_closed? end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/test/lib/hector/async_identity_adapter.rb
test/lib/hector/async_identity_adapter.rb
module Hector class AsyncIdentityAdapter < YamlIdentityAdapter def authenticate(username, password) Hector.next_tick do super username, password end end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/test/lib/hector/test_deference.rb
test/lib/hector/test_deference.rb
module Hector class << self def deferred_blocks @deferred_blocks ||= [] end def defer(&block) deferred_blocks.push(block) end alias_method :next_tick, :defer def process_deferred_blocks until deferred_blocks.empty? deferred_blocks.shift.call end end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/test/lib/hector/test_case.rb
test/lib/hector/test_case.rb
module Hector class TestCase < Test::Unit::TestCase undef_method :default_test if method_defined?(:default_test) def self.test(name, &block) define_method("test #{name.inspect}", &block) end def run(*) Hector.logger.info "--- #@method_name ---" super ensure Hector.logger.info " " end def sleep(seconds) current_time = Time.now Time.expects(:now).at_least_once.returns(current_time + seconds) end def connection Hector::TestConnection.new("test") end def identity(username = "sam") Hector::Identity.new(username) end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/test/lib/hector/test_heartbeat.rb
test/lib/hector/test_heartbeat.rb
module Hector class Heartbeat def self.create_timer(interval) Object.new.tap do |o| def o.cancel; end end end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/test/lib/hector/test_service.rb
test/lib/hector/test_service.rb
module Hector class TestService < Service def received_privmsg intercept(/^!reverse (.+)/) do |line, text| deliver_message_from_origin(text.reverse) end intercept(/^!sum (\d+) (\d+)/) do |line, n, m| n, m = n.to_i, m.to_i deliver_message_from_service("#{n} + #{m} = #{n + m}") end end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/test/lib/hector/test_connection.rb
test/lib/hector/test_connection.rb
module Hector class TestConnection < Connection def sent_data @sent_data ||= "" end def send_data(data) sent_data << data end def connection_closed? @connection_closed end def close_connection(after_writing = false) unbind unless connection_closed? @connection_closed = true end def receive_line(*) super Hector.process_deferred_blocks end def address "test" end def port 0 end def start_timeout @timer ||= Object.new.tap do |o| def o.cancel; end end end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/test/unit/session_test.rb
test/unit/session_test.rb
# encoding: UTF-8 require "test_helper" module Hector class SessionTest < TestCase def teardown Session.reset! end test :"creating a session adds it to the session pool" do assert_equal [], session_names create_session("first") assert_equal ["first"], session_names create_session("second") assert_equal ["first", "second"], session_names end test :"destroying a session removes it from the session pool" do assert_equal [], session_names first = create_session("first") second = create_session("second") assert_equal ["first", "second"], session_names first.destroy assert_equal ["second"], session_names end test :"nicknames must be valid" do ["", "-", "foo bar"].each do |nickname| assert_raises(ErroneousNickname) do create_session(nickname) end end end test :"two sessions can't have the same nickname" do create_session("sam") assert_raises(NicknameInUse) do create_session("sam") end end test :"nicknames are case-insensitive" do create_session("sam") assert_raises(NicknameInUse) do create_session("SAM") end end test :"nicknames preserve their original case" do create_session("Sam") assert_equal "Sam", Session.find("sam").nickname end test :"idle time increases beginning with initial connection" do session = create_session("clint") sleep 1 assert_not_equal 0, session.seconds_idle end test :"sessions can be renamed" do session = create_session("sam") assert_equal "sam", session.nickname session.rename("joe") assert_equal "joe", session.nickname assert_nil Session.find("sam") assert_equal session, Session.find("joe") end test :"sessions can't be renamed to invalid nicknames" do session = create_session("sam") assert_raises(ErroneousNickname) do session.rename("$") end assert_equal "sam", session.nickname assert_equal session, Session.find("sam") end test :"sessions can't be renamed to a nickname already in use" do first = create_session("first") second = create_session("second") assert_raises(NicknameInUse) do second.rename("first") end assert_equal "second", second.nickname assert_equal first, Session.find("first") assert_equal second, Session.find("second") end test :"sessions can have unicode nicknames" do session1 = create_session("I♥") session2 = create_session("яблочный") session3 = create_session("quảtáo") session4 = create_session("☬☃☢☠☆☆☆") assert_equal "I♥", session1.nickname assert_equal "яблочный", session2.nickname assert_equal "quảtáo", session3.nickname assert_equal "☬☃☢☠☆☆☆", session4.nickname assert_equal session1, Session.find("I♥") assert_equal session2, Session.find("яблочный") assert_equal session3, Session.find("quảtáo") assert_equal session4, Session.find("☬☃☢☠☆☆☆") end test :"session nicknames are coerced to UTF-8" do session1 = create_session("säm".force_encoding("ASCII-8BIT")) session2 = create_session("lée".force_encoding("ASCII-8BIT")) session3 = create_session("røss".force_encoding("ASCII-8BIT")) assert_equal "säm", session1.nickname assert_equal "lée", session2.nickname assert_equal "røss", session3.nickname assert_equal session1, Session.find("säm") assert_equal session2, Session.find("lée") assert_equal session3, Session.find("røss") end if String.method_defined?(:force_encoding) test :"can set and remove away messages" do session = create_session("sam") assert !session.away? assert_nil session.away_message session.away("bai") assert_equal session.away_message, "bai" session.back assert !session.away? assert_nil session.away_message end def create_session(nickname) UserSession.create(nickname, connection, identity, "Real Name") end def session_names Session.nicknames.sort end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/test/unit/irc_error_test.rb
test/unit/irc_error_test.rb
require "test_helper" module Hector class TestError < IrcError("FOO", :text => "This is a test"); end class FatalError < IrcError("FATAL", :fatal => true); end class IrcErrorTest < TestCase test :"raising an IrcError without an argument" do exception = begin raise TestError rescue Exception => e e end assert_equal "FOO :This is a test\r\n", exception.response.to_s assert !exception.fatal? end test :"raising an IrcError with an argument" do exception = begin raise TestError, "bar" rescue Exception => e e end assert_equal "FOO bar :This is a test\r\n", exception.response.to_s assert !exception.fatal? end test :"raising a fatal IrcError" do exception = begin raise FatalError rescue Exception => e e end assert_equal "FATAL\r\n", exception.response.to_s assert exception.fatal? end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/test/unit/response_test.rb
test/unit/response_test.rb
# encoding: UTF-8 require "test_helper" module Hector class ResponseTest < TestCase test :"numeric response from the server" do assert_response ":hector.irc 001 sam :Welcome to IRC\r\n", "001", "sam", :text => "Welcome to IRC" end test :"response from a user" do assert_response ":ross!ross@hector.irc PRIVMSG sam :hello world\r\n", "PRIVMSG", "sam", :text => "hello world", :source => "ross!ross@hector.irc" end test :"a nickname and message with mixed encodings" do assert_response ":røss!ross@hector.irc PRIVMSG sam :hello world\r\n", "PRIVMSG", "sam", :text => "hello world", :source => "røss!ross@hector.irc".force_encoding("ASCII-8BIT") assert_response ":røss!ross@hector.irc PRIVMSG sam :hey there ☞\r\n", "PRIVMSG", "sam", :text => "hey there ☞", :source => "røss!ross@hector.irc".force_encoding("ASCII-8BIT") end def assert_response(line, *args) response = Response.new(*args) assert_equal line, response.to_s end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/test/unit/request_test.rb
test/unit/request_test.rb
require "test_helper" module Hector class RequestTest < TestCase test :"empty line" do assert_request :command => "", :args => [], :text => nil, :line => "" assert_request :command => "", :args => [], :text => nil, :line => " " end test :"just a command" do assert_request :command => "QUIT", :args => [], :text => nil, :line => "QUIT" assert_request :command => "QUIT", :args => [], :text => nil, :line => "QUIT " assert_request :command => "QUIT", :args => [], :text => nil, :line => " QUIT" assert_request :command => "QUIT", :args => [], :text => nil, :line => "quit" end test :"a command with text but no arguments" do assert_request :command => "QUIT", :args => ["foo"], :text => "foo", :line => "QUIT :foo" assert_request :command => "QUIT", :args => ["foo bar"], :text => "foo bar", :line => "QUIT :foo bar" assert_request :command => "QUIT", :args => ["foo"], :text => "foo", :line => "QUIT foo" assert_request :command => "QUIT", :args => [""], :text => "", :line => "QUIT :" end test :"a command with arguments" do assert_request :command => "JOIN", :args => ["#channel"], :line => "JOIN #channel" assert_request :command => "JOIN", :args => ["#channel", "key"], :line => "JOIN #channel key" end test :"a command with text and arguments" do assert_request :command => "PRIVMSG", :args => ["nickname", "message"], :text => "message", :line => "PRIVMSG nickname :message" assert_request :command => "PRIVMSG", :args => ["nickname", "message with spaces"], :text => "message with spaces", :line => "PRIVMSG nickname :message with spaces" assert_request :command => "PRIVMSG", :args => ["nickname", "message"], :text => "message", :line => "PRIVMSG nickname message" end def assert_request(options) request = Request.new(options.delete(:line)) options.each do |method, value| assert_equal value, request.send(method), "when calling method #{method.inspect}" end end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/test/unit/identity_test.rb
test/unit/identity_test.rb
require "test_helper" module Hector class IdentityTest < TestCase test :"authenticate yields nil when the identity doesn't exist" do Identity.authenticate("nonexistent", "foo") do |identity| assert_nil identity end end test :"authenticate yields nil when the password is invalid" do Identity.authenticate("sam", "foo") do |identity| assert_nil identity end end test :"authenticate yields the authenticated identity" do Identity.authenticate("sam", "secret") do |identity| assert_kind_of Identity, identity assert_equal "sam", identity.username end end test :"two identities with the same username are equal" do assert_equal Identity.new("sam"), Identity.new("sam") end test :"two identities with different usernames are not equal" do assert_not_equal Identity.new("sam"), Identity.new("clint") end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/test/unit/yaml_identity_adapter_test.rb
test/unit/yaml_identity_adapter_test.rb
module Hector class YamlIdentityAdapterTest < TestCase TEST_IDENTITY_FIXTURES = Hector.fixture_path("identities2.yml") attr_reader :adapter def setup FileUtils.cp(IDENTITY_FIXTURES, TEST_IDENTITY_FIXTURES) reload_adapter end def teardown FileUtils.rm_f(TEST_IDENTITY_FIXTURES) end def reload_adapter @adapter = YamlIdentityAdapter.new(TEST_IDENTITY_FIXTURES) end test :"successful authentication" do assert_authenticated "sam", "secret" end test :"failed authentication" do assert_not_authenticated "sam", "bananas" end test :"usernames are case-insensitive" do assert_authenticated "SAM", "secret" end test :"creating a new identity" do assert_not_authenticated "lee", "waffles" adapter.remember("lee", "waffles") assert_authenticated "lee", "waffles" reload_adapter assert_authenticated "lee", "waffles" end test :"deleting an existing identity" do adapter.forget("sam") assert_not_authenticated "sam", "secret" reload_adapter assert_not_authenticated "sam", "secret" end test :"changing the password of an existing identity" do adapter.remember("sam", "bananas") assert_authenticated "sam", "bananas" reload_adapter assert_authenticated "sam", "bananas" end test :"yaml file is automatically created if it doesn't exist" do teardown assert !File.exists?(TEST_IDENTITY_FIXTURES) reload_adapter assert_not_authenticated "sam", "secret" assert File.exists?(TEST_IDENTITY_FIXTURES) end def assert_authenticated(username, password, expected = true) adapter.authenticate(username, password) do |authenticated| assert_equal expected, authenticated end end def assert_not_authenticated(username, password) assert_authenticated(username, password, false) end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/lib/hector.rb
lib/hector.rb
require "digest/sha1" require "eventmachine" require "fileutils" require "socket" require "yaml" require "hector/errors" require "hector/concerns/authentication" require "hector/concerns/keep_alive" require "hector/concerns/presence" require "hector/commands/away" require "hector/commands/invite" require "hector/commands/join" require "hector/commands/mode" require "hector/commands/names" require "hector/commands/nick" require "hector/commands/notice" require "hector/commands/part" require "hector/commands/ping" require "hector/commands/pong" require "hector/commands/privmsg" require "hector/commands/quit" require "hector/commands/realname" require "hector/commands/topic" require "hector/commands/who" require "hector/commands/whois" require "hector/channel" require "hector/connection" require "hector/deference" require "hector/heartbeat" require "hector/identity" require "hector/logging" require "hector/request" require "hector/response" require "hector/server" require "hector/session" require "hector/service" require "hector/user_session" require "hector/version" require "hector/yaml_identity_adapter"
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/lib/hector/session.rb
lib/hector/session.rb
module Hector class Session include Concerns::KeepAlive include Concerns::Presence include Commands::Join include Commands::Mode include Commands::Names include Commands::Nick include Commands::Notice include Commands::Part include Commands::Ping include Commands::Pong include Commands::Privmsg include Commands::Quit include Commands::Realname include Commands::Topic include Commands::Who include Commands::Whois include Commands::Away include Commands::Invite attr_reader :nickname, :request, :response, :away_message SESSIONS = {} class << self def all sessions.values.grep(self) end def nicknames sessions.keys end def find(nickname) sessions[normalize(nickname)] end def rename(from, to) if find(to) raise NicknameInUse, to else find(from).tap do |session| delete(from) sessions[normalize(to)] = session end end end def delete(nickname) sessions.delete(normalize(nickname)) end def broadcast_to(sessions, command, *args) except = args.last.delete(:except) if args.last.is_a?(Hash) sessions.each do |session| session.respond_with(command, *args) unless session == except end end def normalize(nickname) nickname.force_encoding("UTF-8") if nickname.respond_to?(:force_encoding) if nickname =~ /^[\p{L}\p{M}\p{N}\p{So}\p{Co}\w][\p{L}\p{M}\p{N}\p{So}\p{Co}\p{P}\w\|\-]{0,15}$/u nickname.downcase else raise ErroneousNickname, nickname end end def register(session) yield session if block_given? sessions[normalize(session.nickname)] = session session end def reset! sessions.clear end protected def sessions SESSIONS end end def initialize(nickname) @nickname = nickname end def broadcast(command, *args) Session.broadcast_to(peer_sessions, command, *args) end def channel? false end def deliver(message_type, session, options) respond_with(message_type, nickname, options) end def destroy self.class.delete(nickname) end def find(name) destination_klass_for(name).find(name).tap do |destination| raise NoSuchNickOrChannel, name unless destination end end def hostname Hector.server_name end def name nickname end def realname nickname end def receive(request) @request = request if respond_to?(@request.event_name) send(@request.event_name) end ensure @request = nil end def rename(new_nickname) Session.rename(nickname, new_nickname) @nickname = new_nickname end def respond_with(command, *args) @response = command.is_a?(Response) ? command : Response.new(command, *preprocess_args(args)) if respond_to?(@response.event_name) send(@response.event_name) end @response ensure @response = nil end def away(away_message) @away_message = away_message end def away? !@away_message.nil? end def back @away_message = nil end def source "#{nickname}!#{username}@#{hostname}" end def username "~#{nickname}" end def who "#{identity.username} #{Hector.server_name} #{Hector.server_name} #{nickname} H :0 #{realname}" end protected def destination_klass_for(name) name =~ /^#/ ? Channel : Session end def preprocess_args(args) args.map do |arg| if arg.is_a?(Symbol) && arg.to_s[0, 1] == "$" send(arg.to_s[1..-1]) else arg end end end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/lib/hector/version.rb
lib/hector/version.rb
module Hector VERSION = "1.0.9" end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/lib/hector/channel.rb
lib/hector/channel.rb
module Hector class Channel attr_reader :name, :topic, :user_sessions, :created_at class << self def find(name) channels[normalize(name)] end def find_all_for_session(session) channels.values.find_all do |channel| channel.has_session?(session) end end def create(name) new(name).tap do |channel| channels[normalize(name)] = channel end end def find_or_create(name) find(name) || create(name) end def delete(name) channels.delete(name) end def normalize(name) name.force_encoding("UTF-8") if name.respond_to?(:force_encoding) if name =~ /^[#&+!][#&+!\-\w\p{L}\p{M}\p{N}\p{S}\p{P}\p{Co}]{1,49}$/u && name !~ /,/ name.downcase else raise NoSuchChannel, name end end def reset! @channels = nil end protected def channels @channels ||= {} end end def initialize(name) @name = name @user_sessions = [] @created_at = Time.now end def broadcast(command, *args) catch :stop do Session.broadcast_to(sessions, command, *args) end end def change_topic(session, topic) @topic = { :body => topic, :nickname => session.nickname, :time => Time.now } end def channel? true end def deliver(message_type, session, options) if has_session?(session) broadcast(message_type, name, options.merge(:except => session)) else raise CannotSendToChannel, name end end def destroy self.class.delete(name) end def has_session?(session) sessions.include?(session) end def join(session) return if has_session?(session) user_sessions.push(session) end def nicknames user_sessions.map { |session| session.nickname } end def part(session) user_sessions.delete(session) destroy if user_sessions.empty? end def services Service.all end def sessions services + user_sessions end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/lib/hector/identity.rb
lib/hector/identity.rb
module Hector class Identity attr_accessor :username class << self attr_accessor :adapter def authenticate(username, password) adapter.authenticate(username, password) do |authenticated| yield authenticated ? new(username) : nil end end end def initialize(username) @username = username end def ==(identity) Identity.adapter.normalize(username) == Identity.adapter.normalize(identity.username) end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/lib/hector/errors.rb
lib/hector/errors.rb
module Hector class Error < ::StandardError; end class LoadError < Error; end class IrcError < Error def response Response.new(command, *options).tap do |response| response.args.push(message) unless message == self.class.name end end end def self.IrcError(command, *options) fatal = options.last.is_a?(Hash) && options.last.delete(:fatal) Class.new(IrcError).tap do |klass| klass.class_eval do define_method(:command) { command.dup } define_method(:options) { options.dup } define_method(:fatal?) { fatal } end end end class NoSuchNickOrChannel < IrcError("401", :text => "No such nick/channel"); end class NoSuchChannel < IrcError("403", :text => "No such channel"); end class CannotSendToChannel < IrcError("404", :text => "Cannot send to channel"); end class ErroneousNickname < IrcError("432", :text => "Erroneous nickname"); end class NicknameInUse < IrcError("433", "*", :text => "Nickname is already in use"); end class InvalidPassword < IrcError("464", :text => "Invalid password", :fatal => true); end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/lib/hector/logging.rb
lib/hector/logging.rb
module Hector class NullLogger def level=(l) end def debug(*) end def info(*) end def warn(*) end def error(*) end def fatal(*) end end class << self attr_accessor :logger end self.logger = NullLogger.new end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/lib/hector/response.rb
lib/hector/response.rb
module Hector class Response attr_reader :command, :args, :source attr_accessor :text class << self def apportion_text(args, *base_args) base_response = Response.new(*base_args) max_length = 510 - base_response.to_s.bytesize args.inject([args.shift.dup]) do |texts, arg| if texts.last.bytesize + arg.bytesize + 1 >= max_length texts << arg.dup else texts.last << " " << arg end texts end.map do |text| base_response.dup.tap do |response| response.text = text end end end end def initialize(command, *args) @command = command.to_s.upcase @args = args options = args.pop if args.last.is_a?(Hash) @text = options[:text] if options @source = options[:source] if options @source ||= Hector.server_name if @command =~ /^\d+$/ end def event_name "received_#{command.downcase}" end def to_s [].tap do |line| line.push(":#{source}") if source line.push(command) line.concat(args) line.push(":#{text}") if text end.map do |arg| if arg.respond_to?(:force_encoding) then arg.force_encoding("UTF-8") else arg end end.join(" ")[0, 510] + "\r\n" end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/lib/hector/user_session.rb
lib/hector/user_session.rb
module Hector class UserSession < Session attr_reader :connection, :identity, :realname class << self def create(nickname, connection, identity, realname) if find(nickname) raise NicknameInUse, nickname else register UserSession.new(nickname, connection, identity, realname) end end end def initialize(nickname, connection, identity, realname) super(nickname) @connection = connection @identity = identity @realname = realname initialize_keep_alive initialize_presence end def destroy super destroy_presence destroy_keep_alive end def respond_with(*) connection.respond_with(super) end def username identity.username end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/lib/hector/connection.rb
lib/hector/connection.rb
module Hector class Connection < EventMachine::Protocols::LineAndTextProtocol include Concerns::Authentication attr_reader :session, :request, :identity def post_init log(:info, "opened connection") end def receive_line(line) @request = Request.new(line) log(:debug, "received", @request.to_s.inspect) unless @request.sensitive? if session session.receive(request) else if respond_to?(request.event_name) send(request.event_name) else close_connection(true) end end rescue IrcError => e handle_error(e) rescue Exception => e log(:error, [e, *e.backtrace].join("\n")) ensure @request = nil end def unbind session.destroy if session log(:info, "closing connection") end def respond_with(response, *args) response = Response.new(response, *args) unless response.is_a?(Response) send_data(response.to_s) log(:debug, "sent", response.to_s.inspect) end def handle_error(error) respond_with(error.response) close_connection(true) if error.fatal? end def error(klass, *args) handle_error(klass.new(*args)) end def log(level, *args) Hector.logger.send(level, [log_tag, *args].join(" ")) end def address peer_info[1] end def port peer_info[0] end protected def peer_info @peer_info ||= Socket.unpack_sockaddr_in(get_peername) end def log_tag "[#{address}:#{port}]".tap do |tag| tag << " (#{session.nickname})" if session end end end class SSLConnection < Connection def post_init log(:info, "opened SSL connection") start_tls(ssl_options) end private def ssl_options { :cert_chain_file => Hector.ssl_certificate_path.to_s, :private_key_file => Hector.ssl_certificate_key_path.to_s } end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/lib/hector/yaml_identity_adapter.rb
lib/hector/yaml_identity_adapter.rb
module Hector # Identity adapters must implement the following public methods: # - authenticate(username, password) # - remember(username, password) # - forget(username) # - normalize(username) # class YamlIdentityAdapter attr_reader :filename def initialize(filename) @filename = File.expand_path(filename) end def authenticate(username, password) yield load_identities[normalize(username)] == hash(normalize(username), password) end def remember(username, password) identities = load_identities identities[normalize(username)] = hash(normalize(username), password) store_identities(identities) end def forget(username) identities = load_identities identities.delete(normalize(username)) store_identities(identities) end def normalize(username) username.strip.downcase end protected def load_identities ensure_file_exists File.open(filename, "r") do |io| YAML.load(io) || {} end end def store_identities(identities) File.open(filename, "w") do |file| file.puts(identities.to_yaml) end end def hash(username, password) Digest::SHA1.hexdigest(Digest::SHA1.hexdigest(username) + password) end def ensure_file_exists FileUtils.mkdir_p(File.dirname(filename)) FileUtils.touch(filename) end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/lib/hector/deference.rb
lib/hector/deference.rb
module Hector class << self def defer(&block) EM.defer(&block) end def next_tick(&block) EM.next_tick(&block) end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/lib/hector/heartbeat.rb
lib/hector/heartbeat.rb
module Hector class Heartbeat def self.create_timer(interval, &block) EventMachine::PeriodicTimer.new(interval, &block) end def initialize(interval = 60, &block) @interval, @block = interval, block start end def start @timer ||= self.class.create_timer(@interval) { pulse } end def pulse @block.call end def stop @timer.cancel @timer = nil end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/lib/hector/server.rb
lib/hector/server.rb
module Hector class << self attr_accessor :server_name, :address, :port, :ssl_port, :ssl_certificate_path, :ssl_certificate_key_path def start_server EventMachine.start_server(@address, @port, Connection) EventMachine.start_server(@address, @ssl_port, SSLConnection) logger.info("Hector running on #{@address}:#{@port}") logger.info("Secure Hector running on #{@address}:#{@ssl_port}") end end self.server_name = "hector.irc" self.address = "0.0.0.0" self.port = 6767 self.ssl_port = 6868 end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/lib/hector/service.rb
lib/hector/service.rb
module Hector class Service < Session protected def deliver_message_from_origin(text) deliver_message_from_session(origin, text) end def deliver_message_from_service(text) deliver_message_from_session(self, text) end def deliver_message_from_session(session, text) command, destination = response.command, find(response.args.first) Hector.defer do destination.deliver(command, session, :source => session.source, :text => text) end end def intercept(pattern) if response.text =~ pattern yield *$~ throw :stop end end def origin find(response.source[/^([^!]+)!/, 1]) end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/lib/hector/request.rb
lib/hector/request.rb
module Hector class Request attr_reader :line, :command, :args, :text alias_method :to_s, :line def initialize(line) @line = line parse end def event_name "on_#{command.downcase}" end def sensitive? command.downcase == "pass" end protected def parse source = line.dup @command = extract!(source, /^ *([^ ]+)/, "").upcase @text = extract!(source, / :(.*)$/) @args = source.strip.split(" ") if @text @args.push(@text) else @text = @args.last end end def extract!(line, regex, default = nil) result = nil line.gsub!(regex) do |match| result = $~[1] "" end result || default end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/lib/hector/boot.rb
lib/hector/boot.rb
require "pathname" require "logger" module Hector class << self attr_accessor :lib, :root def start raise LoadError, "please specify HECTOR_ROOT" unless Hector.root load_defaults load_application end def load_root if root = ENV["HECTOR_ROOT"] Hector.root = Pathname.new(File.expand_path(root)) else Hector.root = find_application_root_from(Dir.pwd) end end def load_defaults log_path = Hector.root.join("log/hector.log") Hector.logger = Logger.new(log_path) Hector.logger.datetime_format = "%Y-%m-%d %H:%M:%S" identities_path = Hector.root.join("config/identities.yml") Hector::Identity.adapter = Hector::YamlIdentityAdapter.new(identities_path) end def load_application $:.unshift Hector.root.join("lib") load Hector.root.join("init.rb") end def find_application_root_from(working_directory) dir = Pathname.new(working_directory) dir = dir.parent while dir != dir.parent && dir.basename.to_s !~ /\.hect$/ dir == dir.parent ? nil : dir end end end Hector.lib = Pathname.new(File.expand_path(File.dirname(__FILE__) + "/..")) Hector.load_root if Hector.root vendor_lib = Hector.root.join("vendor/hector/lib") Hector.lib = vendor_lib if vendor_lib.exist? end $:.unshift Hector.lib begin require "hector" rescue LoadError => e if require "rubygems" retry else raise e end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/lib/hector/concerns/authentication.rb
lib/hector/concerns/authentication.rb
module Hector module Concerns module Authentication def on_user @username = request.args.first @realname = request.text authenticate end def on_pass @password = request.text authenticate end def on_nick @nickname = request.text authenticate end def on_cap # Do nothing end protected def authenticate start_timeout set_identity set_session end def set_identity if @username && @password && !@identity Identity.authenticate(@username, @password) do |identity| if @identity = identity cancel_timeout set_session elsif @password.include?(":") @username, @password = @password.split(":") set_identity else error InvalidPassword end end end end def set_session if @identity && @nickname && !@session @session = UserSession.create(@nickname, self, @identity, @realname) end end def start_timeout @timer ||= EventMachine::Timer.new(30) do close_connection(true) end end def cancel_timeout @timer.cancel if @timer end end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/lib/hector/concerns/presence.rb
lib/hector/concerns/presence.rb
module Hector module Concerns module Presence def self.included(klass) klass.class_eval do attr_reader :created_at, :updated_at end end def channels Channel.find_all_for_session(self) end def initialize_presence @created_at = Time.now @updated_at = Time.now deliver_welcome_message end def destroy_presence deliver_quit_message leave_all_channels end def seconds_idle Time.now - updated_at end def peer_sessions [self, *channels.map { |channel| channel.sessions }.flatten].uniq end def touch_presence @updated_at = Time.now end protected def deliver_welcome_message respond_with("001", nickname, :text => "Welcome to IRC") respond_with("422", :text => "MOTD File is missing") end def deliver_quit_message broadcast(:quit, :source => source, :text => quit_message, :except => self) respond_with(:error, :text => "Closing Link: #{nickname}[hector] (#{quit_message})") end def leave_all_channels channels.each do |channel| channel.part(self) end end def quit_message @quit_message || "Connection closed" end end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/lib/hector/concerns/keep_alive.rb
lib/hector/concerns/keep_alive.rb
module Hector module Concerns module KeepAlive def initialize_keep_alive @received_pong = true @heartbeat = Hector::Heartbeat.new { on_heartbeat } end def on_heartbeat if @received_pong @received_pong = false respond_with(:ping, Hector.server_name) else @quit_message = "Ping timeout" connection.close_connection(true) end end def destroy_keep_alive @heartbeat.stop end end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/lib/hector/commands/ping.rb
lib/hector/commands/ping.rb
module Hector module Commands module Ping def on_ping respond_with(:pong, Hector.server_name, :source => Hector.server_name, :text => request.text) end end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/lib/hector/commands/mode.rb
lib/hector/commands/mode.rb
module Hector module Commands module Mode def on_mode subject = find(request.args.first) if subject.channel? if requesting_modes? respond_with("324", nickname, subject.name, "+", :source => Hector.server_name) respond_with("329", nickname, subject.name, subject.created_at.to_i, :source => Hector.server_name) elsif requesting_bans? respond_with("368", nickname, subject.name, :text => "End of Channel Ban List", :source => Hector.server_name) end else if requesting_modes? respond_with("221", nickname, "+", :source => Hector.server_name) end end end private def requesting_modes? request.args.length == 1 end def requesting_bans? request.args.length == 2 && request.args.last[/^\+?b$/] end end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/lib/hector/commands/nick.rb
lib/hector/commands/nick.rb
module Hector module Commands module Nick def on_nick old_nickname = nickname rename(request.args.first) broadcast(:nick, nickname, :source => old_nickname) end end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/lib/hector/commands/topic.rb
lib/hector/commands/topic.rb
module Hector module Commands module Topic def on_topic channel = Channel.find(request.args.first) if request.args.length > 1 topic = request.text channel.change_topic(self, topic) channel.broadcast(:topic, channel.name, :source => source, :text => topic) else respond_to_topic(channel) end end def respond_to_topic(channel) if topic = channel.topic respond_with("332", nickname, channel.name, :source => Hector.server_name, :text => topic[:body]) respond_with("333", nickname, channel.name, topic[:nickname], topic[:time].to_i, :source => Hector.server_name) else respond_with("331", nickname, channel.name, :source => Hector.server_name, :text => "No topic is set.") end end end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/lib/hector/commands/pong.rb
lib/hector/commands/pong.rb
module Hector module Commands module Pong def on_pong @received_pong = true end end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/lib/hector/commands/who.rb
lib/hector/commands/who.rb
module Hector module Commands module Who def on_who name = request.args.first if destination = destination_klass_for(name).find(name) sessions_for_who(destination).each do |session| respond_with("352", nickname, name, session.who, :source => Hector.server_name) end end respond_with("315", nickname, name, :source => Hector.server_name, :text => "End of /WHO list.") end def sessions_for_who(destination) if destination.respond_to?(:sessions) destination.sessions.select do |session| session.respond_to?(:identity) end else [destination] end end def who "#{username} #{Hector.server_name} #{Hector.server_name} #{nickname} H :0 #{realname}" end end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/lib/hector/commands/away.rb
lib/hector/commands/away.rb
module Hector module Commands module Away def on_away away_message = request.args.first if away_message and !away_message.empty? @away_message = away_message respond_with("306", :text => "You have been marked as being away") else @away_message = nil respond_with("305", :text => "You are no longer marked as being away") end end end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/lib/hector/commands/quit.rb
lib/hector/commands/quit.rb
module Hector module Commands module Quit def on_quit @quit_message = "Quit: #{request.text}" connection.close_connection(true) end end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/lib/hector/commands/invite.rb
lib/hector/commands/invite.rb
module Hector module Commands module Invite def on_invite touch_presence nickname = request.args.first if session = Session.find(nickname) channel = Channel.find(request.args[1]) if channels.include?(channel) if !session.channels.include?(channel) session.deliver(:invite, self, :source => source, :text => request.text) else respond_with("443", nickname, channel.name, "is already on channel", :source => Hector.server_name) end else respond_with("442", request.args[1], "You're not on that channel", :source => Hector.server_name) end else raise NoSuchNickOrChannel, nickname end end end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/lib/hector/commands/privmsg.rb
lib/hector/commands/privmsg.rb
module Hector module Commands module Privmsg def on_privmsg touch_presence subject = find(request.args.first) subject.deliver(:privmsg, self, :source => source, :text => request.text) if !subject.channel? and subject.away? respond_with("301", subject.nickname, :text => subject.away_message) end end end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/lib/hector/commands/realname.rb
lib/hector/commands/realname.rb
module Hector module Commands module Realname def on_realname @realname = request.text broadcast("352", :$nickname, "*", who, :source => Hector.server_name) end end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/lib/hector/commands/join.rb
lib/hector/commands/join.rb
module Hector module Commands module Join def on_join request.args.first.split(/,(?=[#&+!])/).each do |channel_name| channel = Channel.find_or_create(channel_name) if channel.join(self) channel.broadcast(:join, :source => source, :text => channel.name) respond_to_topic(channel) respond_to_names(channel) end end end end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/lib/hector/commands/notice.rb
lib/hector/commands/notice.rb
module Hector module Commands module Notice def on_notice touch_presence find(request.args.first).deliver(:notice, self, :source => source, :text => request.text) end end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/lib/hector/commands/whois.rb
lib/hector/commands/whois.rb
module Hector module Commands module Whois def on_whois nickname = request.args.first if session = Session.find(nickname) respond_to_whois_for(self.nickname, session) else raise NoSuchNickOrChannel, nickname end ensure respond_with("318", self.nickname, nickname, "End of /WHOIS list.") end def respond_to_whois_for(destination, session) respond_with("301", session.nickname, :text => session.away_message) if session.away? respond_with("311", destination, session.nickname, session.whois) respond_with("319", destination, session.nickname, :text => session.channels.map { |channel| channel.name }.join(" ")) unless session.channels.empty? respond_with("312", destination, session.nickname, Hector.server_name, :text => "Hector") respond_with("317", destination, session.nickname, session.seconds_idle, session.created_at, :text => "seconds idle, signon time") end def whois "#{nickname} #{identity.username} #{Hector.server_name} * :#{realname}" end end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/lib/hector/commands/names.rb
lib/hector/commands/names.rb
module Hector module Commands module Names def on_names channel = Channel.find(request.args.first) respond_to_names(channel) end def respond_to_names(channel) responses = Response.apportion_text(channel.nicknames, "353", nickname, "=", channel.name, :source => Hector.server_name) responses.each { |response| respond_with(response) } respond_with("366", nickname, channel.name, :source => Hector.server_name, :text => "End of /NAMES list.") end end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
sstephenson/hector
https://github.com/sstephenson/hector/blob/91165fd15e20fd521ce270274c09100aaa74081c/lib/hector/commands/part.rb
lib/hector/commands/part.rb
module Hector module Commands module Part def on_part channel = Channel.find(request.args.first) channel.broadcast(:part, channel.name, :source => source, :text => request.text) channel.part(self) end end end end
ruby
MIT
91165fd15e20fd521ce270274c09100aaa74081c
2026-01-04T17:48:25.917910Z
false
stripe-contrib/stripe-cli
https://github.com/stripe-contrib/stripe-cli/blob/ee98caab204fabf3d5cc34d1baef33c1cc45c881/spec/command_spec.rb
spec/command_spec.rb
require 'spec_helper' describe Stripe::CLI::Command do let(:_id_) { "random-id-string" } describe "#find" do it "calls super, passing in `Stripe::Charge` and an `id`" do Stripe::Charge.should_receive(:retrieve).with( _id_, "stripe-key" ) Stripe::CLI::Runner.start ["charges", "find", _id_] end it "calls super, passing in `Stripe::Plan` and an `id`" do Stripe::Plan.should_receive(:retrieve).with( _id_, "stripe-key" ) Stripe::CLI::Runner.start ["plans", "find", _id_] end it "calls super, passing in `Stripe::Invoice` and an `id`" do Stripe::Invoice.should_receive(:retrieve).with( _id_, "stripe-key" ) Stripe::CLI::Runner.start ["invoices", "find", _id_] end it "calls super, passing in `Stripe::Coupon` and an `id`" do Stripe::Coupon.should_receive(:retrieve).with( _id_, "stripe-key" ) Stripe::CLI::Runner.start ["coupons", "find", _id_] end it "calls super, passing in `Stripe::Customer` and an `id`" do Stripe::Customer.should_receive(:retrieve).with( _id_, "stripe-key" ) Stripe::CLI::Runner.start ["customers", "find", _id_] end it "calls super, passing in `Stripe::BalanceTransaction` and an `id`" do Stripe::BalanceTransaction.should_receive(:retrieve).with( _id_, "stripe-key" ) Stripe::CLI::Runner.start ["transactions", "find", _id_] end end end
ruby
MIT
ee98caab204fabf3d5cc34d1baef33c1cc45c881
2026-01-04T17:48:21.359522Z
false
stripe-contrib/stripe-cli
https://github.com/stripe-contrib/stripe-cli/blob/ee98caab204fabf3d5cc34d1baef33c1cc45c881/spec/dollar_amounts_spec.rb
spec/dollar_amounts_spec.rb
require 'spec_helper' describe Stripe::CLI::Command do describe "#dollar_amounts" do it "defaults to true" do options = {} end end end
ruby
MIT
ee98caab204fabf3d5cc34d1baef33c1cc45c881
2026-01-04T17:48:21.359522Z
false
stripe-contrib/stripe-cli
https://github.com/stripe-contrib/stripe-cli/blob/ee98caab204fabf3d5cc34d1baef33c1cc45c881/spec/spec_helper.rb
spec/spec_helper.rb
require 'rspec' require_relative '../lib/stripe/cli.rb' module Stripe class StripeObject def body @stripe_values[:body] end end module CLI class Command < Thor protected def api_key "stripe-key" end def config Hash.new end end end end module Stripe def self.execute_request(body) body = JSON.generate(body) if !(body.kind_of? String) m = StripeObject.new m.instance_variable_set('@stripe_values', { :body => body }) m end def test_balance(params={}) { :pending => [ {:amount => 12345, :currency => "usd"} ], :available => [ {:amount => 6789, :currency => "usd"} ], :livemode => false, :object => "balance" }.merge(params) end def test_balance_transaction(params={}) { :amount => 100, :net => 41, :currency => "usd", :type => "charge", :created => 1371945005, :available_on => 1372549805, :status => "pending", :description => "A test balance transaction", :fee => 59, :object => "balance_transaction" }.merge(params) end def test_balance_transaction_array { :data => [test_balance_transaction, test_balance_transaction, test_balance_transaction], :object => "list", :url => "/v1/balance/history" } end def test_application_fee(params={}) id = params[:id] || 'fee_test_fee' { :refunded => false, :amount => 100, :application => "ca_test_application", :user => "acct_test_user", :charge => "ch_test_charge", :id => id, :livemode => false, :currency => "usd", :object => "application_fee", :refunds => test_application_fee_refund_array(id), :created => 1304114826 }.merge(params) end def test_application_fee_refund(params = {}) { :object => 'fee_refund', :amount => 30, :currency => "usd", :created => 1308595038, :id => "ref_test_app_fee_refund", :fee => "ca_test_application", :metadata => {} }.merge(params) end def test_application_fee_array { :data => [test_application_fee, test_application_fee, test_application_fee], :object => 'list', :url => '/v1/application_fees' } end def test_application_fee_refund_array(fee_id) { :data => [test_application_fee_refund, test_application_fee_refund, test_application_fee_refund], :object => 'list', :url => '/v1/application_fees/' + fee_id + '/refunds' } end def test_customer(params={}) id = params[:id] || 'c_test_customer' { :subscription_history => [], :bills => [], :charges => [], :livemode => false, :object => "customer", :id => id, :default_card => "cc_test_card", :created => 1304114758, :cards => test_card_array(id), :metadata => {}, :subscriptions => test_subscription_array(id) }.merge(params) end def test_customer_array { :data => [test_customer, test_customer, test_customer], :object => 'list', :url => '/v1/customers' } end def test_charge(params={}) id = params[:id] || 'ch_test_charge' { :refunded => false, :paid => true, :amount => 100, :card => { :type => "Visa", :last4 => "4242", :exp_month => 11, :country => "US", :exp_year => 2012, :id => "cc_test_card", :object => "card" }, :id => id, :reason => "execute_charge", :livemode => false, :currency => "usd", :object => "charge", :created => 1304114826, :refunds => test_refund_array(id), :metadata => {} }.merge(params) end def test_charge_array { :data => [test_charge, test_charge, test_charge], :object => 'list', :url => '/v1/charges' } end def test_card_array(customer_id) { :data => [test_card, test_card, test_card], :object => 'list', :url => '/v1/customers/' + customer_id + '/cards' } end def test_card(params={}) { :type => "Visa", :last4 => "4242", :exp_month => 11, :country => "US", :exp_year => 2012, :id => "cc_test_card", :customer => 'c_test_customer', :object => "card" }.merge(params) end def test_coupon(params={}) { :duration => 'repeating', :duration_in_months => 3, :percent_off => 25, :id => "co_test_coupon", :object => "coupon" }.merge(params) end #FIXME nested overrides would be better than hardcoding plan_id def test_subscription(params = {}) plan = params.delete(:plan) || 'gold' { :current_period_end => 1308681468, :status => "trialing", :plan => { :interval => "month", :amount => 7500, :trial_period_days => 30, :object => "plan", :identifier => plan }, :current_period_start => 1308595038, :start => 1308595038, :object => "subscription", :trial_start => 1308595038, :trial_end => 1308681468, :customer => "c_test_customer", :id => 's_test_subscription' }.merge(params) end def test_refund(params = {}) { :object => 'refund', :amount => 30, :currency => "usd", :created => 1308595038, :id => "ref_test_refund", :charge => "ch_test_charge", :metadata => {} }.merge(params) end def test_subscription_array(customer_id) { :data => [test_subscription, test_subscription, test_subscription], :object => 'list', :url => '/v1/customers/' + customer_id + '/subscriptions' } end def test_refund_array(charge_id) { :data => [test_refund, test_refund, test_refund], :object => 'list', :url => '/v1/charges/' + charge_id + '/refunds' } end def test_invoice { :id => 'in_test_invoice', :object => 'invoice', :livemode => false, :amount_due => 1000, :attempt_count => 0, :attempted => false, :closed => false, :currency => 'usd', :customer => 'c_test_customer', :date => 1349738950, :lines => { "invoiceitems" => [ { :id => 'ii_test_invoice_item', :object => '', :livemode => false, :amount => 1000, :currency => 'usd', :customer => 'c_test_customer', :date => 1349738950, :description => "A Test Invoice Item", :invoice => 'in_test_invoice' }, ], }, :paid => false, :period_end => 1349738950, :period_start => 1349738950, :starting_balance => 0, :subtotal => 1000, :total => 1000, :charge => nil, :discount => nil, :ending_balance => nil, :next_payemnt_attempt => 1349825350, } end def test_paid_invoice test_invoice.merge({ :attempt_count => 1, :attempted => true, :closed => true, :paid => true, :charge => 'ch_test_charge', :ending_balance => 0, :next_payment_attempt => nil, }) end def test_invoice_customer_array { :data => [test_invoice], :object => 'list', :url => '/v1/invoices?customer=test_customer' } end def test_recipient(params={}) id = params[:id] || 'rp_test_recipient' { :name => "Stripe User", :type => "individual", :livemode => false, :object => "recipient", :id => "rp_test_recipient", :cards => test_card_array(id), :default_card => "debit_test_card", :active_account => { :last4 => "6789", :bank_name => "STRIPE TEST BANK", :country => "US", :object => "bank_account" }, :created => 1304114758, :verified => true, :metadata => {} }.merge(params) end def test_recipient_array { :data => [test_recipient, test_recipient, test_recipient], :object => 'list', :url => '/v1/recipients' } end def test_transfer(params={}) { :status => 'pending', :amount => 100, :account => { :object => 'bank_account', :country => 'US', :bank_name => 'STRIPE TEST BANK', :last4 => '6789' }, :recipient => 'test_recipient', :fee => 0, :fee_details => [], :id => "tr_test_transfer", :livemode => false, :currency => "usd", :object => "transfer", :date => 1304114826, :metadata => {} }.merge(params) end def test_transfer_array { :data => [test_transfer, test_transfer, test_transfer], :object => 'list', :url => '/v1/transfers' } end def test_canceled_transfer test_transfer.merge({ :status => 'canceled' }) end def test_invalid_api_key_error { "error" => { "type" => "invalid_request_error", "message" => "Invalid API Key provided: invalid" } } end def test_invalid_exp_year_error { "error" => { "code" => "invalid_expiry_year", "param" => "exp_year", "type" => "card_error", "message" => "Your card's expiration year is invalid" } } end def test_missing_id_error { :error => { :param => "id", :type => "invalid_request_error", :message => "Missing id" } } end def test_api_error { :error => { :type => "api_error" } } end def test_delete_discount_response { :deleted => true, :id => "di_test_coupon" } end end
ruby
MIT
ee98caab204fabf3d5cc34d1baef33c1cc45c881
2026-01-04T17:48:21.359522Z
false
stripe-contrib/stripe-cli
https://github.com/stripe-contrib/stripe-cli/blob/ee98caab204fabf3d5cc34d1baef33c1cc45c881/spec/commands/recipient_spec.rb
spec/commands/recipient_spec.rb
require 'spec_helper' describe Stripe::CLI::Commands::Recipients do describe "#create" do it "can determine recipient type from the passed options" do Stripe.should_receive(:execute_request).with do |opts| opts[:headers][:authorization] == 'Bearer stripe-key' end request_hash = Stripe::CLI::Runner.start ["recipients", "create", "--corporation", "--name=John Doe"] expect(request_hash[:url]).to eq("https://api.stripe.com/v1/recipients") expect(request_hash[:payload]).to eq("type=individual&name=John Doe") end end end
ruby
MIT
ee98caab204fabf3d5cc34d1baef33c1cc45c881
2026-01-04T17:48:21.359522Z
false
stripe-contrib/stripe-cli
https://github.com/stripe-contrib/stripe-cli/blob/ee98caab204fabf3d5cc34d1baef33c1cc45c881/spec/commands/charges_spec.rb
spec/commands/charges_spec.rb
require 'spec_helper' describe Stripe::CLI::Commands::Charges do let(:_id_){ "a-charge-id" } describe "#refund" do # it "takes a charge_id and refunds the associated charge entirely" do # request_hash = Stripe::CLI::Runner.start ["charges", "refund", _id_] # request_hash[:url].should == "https://api.stripe.com/v1/charges/a-charge-id/refund" # request_hash[:payload].should == "" # end # # it "takes a charge_id and an optional [--amount] and partially refunds the associated charge" do # request_hash = Stripe::CLI::Runner.start ["charges", "refund", _id_, "--amount=100.99"] # request_hash[:url].should == "https://api.stripe.com/v1/charges/a-charge-id/refund" # request_hash[:payload].should == "amount=10099" # end end end
ruby
MIT
ee98caab204fabf3d5cc34d1baef33c1cc45c881
2026-01-04T17:48:21.359522Z
false
stripe-contrib/stripe-cli
https://github.com/stripe-contrib/stripe-cli/blob/ee98caab204fabf3d5cc34d1baef33c1cc45c881/lib/stripe/utils.rb
lib/stripe/utils.rb
module Stripe module Utils private def credit_card options = {} card = options.delete(:card) || {} { :name => card["name"] || options.delete(:card_name) || ask('Name on Card:'), :number => card["number"] || options.delete(:card_number) || ask('Card Number:'), :cvc => card["cvc"] || options.delete(:card_cvc) || ask('CVC code:'), :exp_month => card["exp-month"] || options.delete(:card_exp_month) || ask('Expiration Month:'), :exp_year => card["exp-year"] || options.delete(:card_exp_year) || ask('Expiration Year:') } end def bank_account options = {} account = options.delete(:bank_account) || {} { :account_number => account["account-number"] || options.delete(:account_number) || ask('Account Number:'), :routing_number => account["routing-number"] || options.delete(:routing_number) || ask('Routing Number:'), :country => account["country"] || options.delete(:country) || 'US' } end def convert_amount amount if dollar_amounts (Float(amount||ask('Amount In Dollars:')) * 100).to_i else amount||ask('Amount In Cents:') end end def retrieve_customer id begin ::Stripe::Customer.retrieve(id, api_key) rescue Exception => e ap e.message false end end def retrieve_charge id begin ::Stripe::Charge.retrieve(id, api_key) rescue Exception => e ap e.message false end end def retrieve_recipient id begin ::Stripe::Recipient.retrieve(id, api_key) rescue Exception => e ap e.message false end end def retrieve_subscription cust, id begin cust.subscriptions.retrieve(id) rescue Exception => e ap e.message false end end def retrieve_card owner, id begin owner.cards.retrieve(id) rescue Exception => e ap e.message false end end def retrieve_owner id if id.start_with? "r" retrieve_recipient(id) else retrieve_customer(id) end end end end
ruby
MIT
ee98caab204fabf3d5cc34d1baef33c1cc45c881
2026-01-04T17:48:21.359522Z
false
stripe-contrib/stripe-cli
https://github.com/stripe-contrib/stripe-cli/blob/ee98caab204fabf3d5cc34d1baef33c1cc45c881/lib/stripe/cli.rb
lib/stripe/cli.rb
require "thor" require "stripe" require "stripe/cli/version" require "awesome_print" require "stripe/utils" module Stripe module CLI autoload :Command, 'stripe/cli/command' autoload :Runner, 'stripe/cli/runner' autoload :Commands, 'stripe/cli/commands' end # `alias_method_chain' style patch to tweek the user-agent header sent with every API request # Doing this adds context to request data that can be viewed using the Stripe Dashboard # differentiating requests made by application code from those made using the Stripe-CLI gem class<<self def cat_user_agent_string api_key user_agent = original_request_headers(api_key)[:user_agent] original_request_headers(api_key).update(:user_agent => user_agent<<"/Stripe-CLI v#{Stripe::CLI::VERSION}") end alias_method :original_request_headers, :request_headers alias_method :request_headers, :cat_user_agent_string private :cat_user_agent_string end end
ruby
MIT
ee98caab204fabf3d5cc34d1baef33c1cc45c881
2026-01-04T17:48:21.359522Z
false
stripe-contrib/stripe-cli
https://github.com/stripe-contrib/stripe-cli/blob/ee98caab204fabf3d5cc34d1baef33c1cc45c881/lib/stripe/cli/command.rb
lib/stripe/cli/command.rb
require 'parseconfig' module Stripe module CLI class Command < Thor @@root_config = ::File.expand_path('~/.stripecli') @@local_config = ::File.expand_path('./.stripecli') class_option :key, :aliases => :k, :type => :string, :desc => "One of your API secret keys, provided by Stripe" class_option :env, :aliases => :e, :type => :string, :desc => "This param expects a ~/.stripecli file with section headers for any string passed into it" class_option :version, :aliases => :v, :type => :string, :desc => "Stripe API version-date. Looks like `YYYY-MM-DD`" class_option :dates, :aliases => :d, :type => :string, :desc => "Date Style. It should be either local, utc, or unix. Defaults to local.", :enum => %w(local utc unix) class_option :dollar_amounts, :type => :boolean, :desc => "set expected currency units to dollars or cents" class_option :strip_nils, :type => :boolean, :desc => "use this flag to strip nil valued attributes from the output" class_option :expand, :type => :array, :desc => "one or more ID properties of the response you'd like expanded into full objects" protected def api_key @api_key ||= options[:key] || stored_api_option('key') end def api_version @api_version ||= options.delete(:version) || stored_api_option('version') end def environment @env ||= options.delete(:env) || config['default'] end def date_format options.delete(:dates) || stored_api_option('dates') end def dollar_amounts options.delete(:dollar_amounts) { !(stored_api_option('dollar_amounts') == 'false') } end def strip_nils? options.delete(:strip_nils) { stored_api_option('strip_nils') == "true" } end def stored_api_option option if File.exists?(config_file) if environment config[environment][option.to_s] || config[option.to_s] else config[option.to_s] end end end def config ParseConfig.new(config_file) if File.exist?(config_file) end def config_file File.exist?(@@local_config) ? @@local_config : @@root_config end def list klass, options request klass, :all, options end def find klass, id request klass, :retrieve, {:id => id, :expand => options[:expand]} end def delete klass, id request klass.new( id, {:api_key => api_key} ), :delete end def create klass, options request klass, :create, options end def request object, method, *arguments pre_request_setup begin output object.send method, *arguments rescue StripeError => e output e.message end end def inspect object case object when Array object.map {|o| inspect(o) } when Hash handle_hash object when Stripe::ListObject inspect object.data when Stripe::StripeObject inspect object.instance_variable_get(:@values) when Numeric object > 1000000000 ? handle_date(object) : object else object end end public :inspect private def output objects ap inspect( objects ), :indent => -2 end # strip non-api params from options hash # set api_version & api_key def pre_request_setup @strip_nils = strip_nils? @date_format = date_format Stripe.api_key = api_key Stripe.api_version = api_version unless api_version.nil? end def handle_hash object object.inject({}) do |hash, (key, value)| hash[key] = inspect( value ) unless @strip_nils && value.nil? hash end end def handle_date object case @date_format when 'unix' then object when 'utc' Time.at( object ).utc else Time.at( object ) end end end end end
ruby
MIT
ee98caab204fabf3d5cc34d1baef33c1cc45c881
2026-01-04T17:48:21.359522Z
false