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
skaes/time_bandits
https://github.com/skaes/time_bandits/blob/6354956aa25040d2b68d21bdb49d50ea13a701b9/test/test_helper.rb
test/test_helper.rb
require 'minitest' require 'mocha/minitest' require 'minitest/autorun' require 'minitest/reporters' if ENV['MINITEST_REPORTER'] Minitest::Reporters.use! else Minitest::Reporters.use!([Minitest::Reporters::DefaultReporter.new]) end require 'active_support/testing/declarative' module Test module Unit class TestCase < Minitest::Test extend ActiveSupport::Testing::Declarative def assert_nothing_raised(*) yield end end end end require_relative '../lib/time_bandits' require "byebug" ActiveSupport::LogSubscriber.logger =::Logger.new("/dev/null") # fake Rails module Rails extend self ActiveSupport::Cache.format_version = 7.1 if Gem::Version.new(ActiveSupport::VERSION::STRING) >= Gem::Version.new("7.1.0") def cache @cache ||= ActiveSupport::Cache.lookup_store(:mem_cache_store) end def env "test" end end
ruby
MIT
6354956aa25040d2b68d21bdb49d50ea13a701b9
2026-01-04T17:46:28.976145Z
false
skaes/time_bandits
https://github.com/skaes/time_bandits/blob/6354956aa25040d2b68d21bdb49d50ea13a701b9/test/unit/beetle_test.rb
test/unit/beetle_test.rb
require_relative '../test_helper' require 'beetle' class BeetleTest < Test::Unit::TestCase def setup TimeBandits.time_bandits = [] TimeBandits.add TimeBandits::TimeConsumers::Beetle TimeBandits.reset @beetle = Beetle::Client.new @beetle.configure do message :foo end @bandit = TimeBandits::TimeConsumers::Beetle.instance end test "getting metrics" do nothing_measured = { :amqp_time => 0, :amqp_calls => 0 } assert_equal nothing_measured, TimeBandits.metrics assert_equal 0, TimeBandits.consumed assert_equal 0, TimeBandits.current_runtime end test "formatting" do @bandit.calls = 3 assert_equal "Beetle: 0.000(3)", TimeBandits.runtime end test "foreground work gets accounted for" do work check_work end test "background work is ignored" do Thread.new do work check_work end.join m = TimeBandits.metrics assert_equal 0, m[:amqp_calls] assert_equal 0, m[:amqp_time] end private def work TimeBandits.reset 2.times do @beetle.publish("foo") @beetle.publish("foo") end end def check_work m = TimeBandits.metrics assert_equal 4, m[:amqp_calls] assert 0 < m[:amqp_time] assert_equal m[:amqp_time], TimeBandits.consumed end end
ruby
MIT
6354956aa25040d2b68d21bdb49d50ea13a701b9
2026-01-04T17:46:28.976145Z
false
skaes/time_bandits
https://github.com/skaes/time_bandits/blob/6354956aa25040d2b68d21bdb49d50ea13a701b9/test/unit/redis_test.rb
test/unit/redis_test.rb
require_relative '../test_helper' class RedisTest < Test::Unit::TestCase def setup TimeBandits.time_bandits = [] TimeBandits.add TimeBandits::TimeConsumers::Redis TimeBandits.reset @redis = Redis.new @bandit = TimeBandits::TimeConsumers::Redis.instance end test "getting metrics" do nothing_measured = { :redis_time => 0, :redis_calls => 0 } assert_equal nothing_measured, TimeBandits.metrics assert_equal 0, TimeBandits.consumed assert_equal 0, TimeBandits.current_runtime end test "formatting" do @bandit.calls = 3 assert_equal "Redis: 0.000(3)", TimeBandits.runtime end test "foreground work gets accounted for" do work check_work end test "background work is ignored" do Thread.new do work check_work end.join m = TimeBandits.metrics assert_equal 0, m[:redis_calls] assert_equal 0, m[:redis_time] end test "counts pipelined calls as single call" do pipelined_work m = TimeBandits.metrics assert_equal 1, m[:redis_calls] end test "counts multi calls as single call" do pipelined_work(:multi) m = TimeBandits.metrics assert_equal 1, m[:redis_calls] end private def pipelined_work(type = :pipelined) TimeBandits.reset @redis.send(type) do |transaction| transaction.get("foo") transaction.set("bar", 1) transaction.hgetall("baz") end end def work TimeBandits.reset 2.times do @redis.get("foo") @redis.set("bar", 1) end end def check_work m = TimeBandits.metrics assert_equal 4, m[:redis_calls] assert 0 < m[:redis_time] assert_equal m[:redis_time], TimeBandits.consumed end end
ruby
MIT
6354956aa25040d2b68d21bdb49d50ea13a701b9
2026-01-04T17:46:28.976145Z
false
skaes/time_bandits
https://github.com/skaes/time_bandits/blob/6354956aa25040d2b68d21bdb49d50ea13a701b9/test/unit/database_test.rb
test/unit/database_test.rb
require_relative '../test_helper' require 'active_record' require 'time_bandits/monkey_patches/active_record' class DatabaseTest < Test::Unit::TestCase def setup TimeBandits.time_bandits = [] TimeBandits.add TimeBandits::TimeConsumers::Database TimeBandits.reset @old_logger = ActiveRecord::Base.logger ActiveRecord::Base.logger = Logger.new($stdout) ActiveRecord::Base.logger.level = Logger::DEBUG ActiveRecord::Base.establish_connection( adapter: "mysql2", username: "root", encoding: "utf8", host: ENV['MYSQL_HOST'] || "127.0.0.1", port: (ENV['MYSQL_PORT'] || 3601).to_i ) end def teardown ActiveRecord::Base.logger = @old_logger end test "getting metrics" do nothing_measured = { :db_time => 0, :db_calls => 0, :db_sql_query_cache_hits => 0 } assert_equal nothing_measured, TimeBandits.metrics assert_equal 0, TimeBandits.consumed assert_equal 0, TimeBandits.current_runtime end test "formatting" do metrics_store.runtime += 1.234 metrics_store.call_count += 3 metrics_store.query_cache_hits += 1 TimeBandits.consumed assert_equal "ActiveRecord: 1.234ms(3q,1h)", TimeBandits.runtime end test "accessing current runtime" do metrics_store.runtime += 1.234 assert_equal 1.234, metrics_store.runtime assert_equal 1.234, bandit.current_runtime assert_equal 1.234, TimeBandits.consumed assert_equal 0, metrics_store.runtime metrics_store.runtime += 4.0 assert_equal 5.234, bandit.current_runtime assert_equal "ActiveRecord: 1.234ms(0q,0h)", TimeBandits.runtime end test "sql can be executed" do event = mock('event') event.stubs(:payload).returns({name: "MURKS", sql: "SELECT 1"}) event.stubs(:duration).returns(0.1) ActiveRecord::Base.logger.expects(:debug) assert_nil log_subscriber.new.sql(event) end test "instrumentation records runtimes at log level debug" do ActiveRecord::Base.logger.stubs(:debug) ActiveRecord::Base.connection.execute "SELECT 1" bandit.consumed assert(bandit.current_runtime > 0) if ActiveRecord::VERSION::STRING >= Gem::Version.new("7.2.0") # registry ingores schema calls now assert_equal 1, bandit.calls else # 2 calls, because one configures the connection assert_equal 2, bandit.calls end assert_equal 0, bandit.sql_query_cache_hits end test "instrumentation records runtimes at log level error" do skip if Gem::Version.new(ActiveRecord::VERSION::STRING) < Gem::Version.new("7.1.0") ActiveRecord::Base.logger.level = Logger::ERROR ActiveRecord::LogSubscriber.expects(:sql).never assert_equal 0, bandit.calls ActiveRecord::Base.connection.execute "SELECT 1" bandit.consumed assert(bandit.current_runtime > 0) if ActiveRecord::VERSION::STRING >= Gem::Version.new("7.2.0") # registry ingores schema calls now assert_equal 1, bandit.calls else # 2 calls, because one configures the connection assert_equal 2, bandit.calls end assert_equal 0, bandit.sql_query_cache_hits end private def bandit TimeBandits::TimeConsumers::Database.instance end def metrics_store TimeBandits::TimeConsumers::Database.metrics_store end def log_subscriber ActiveRecord::LogSubscriber end end
ruby
MIT
6354956aa25040d2b68d21bdb49d50ea13a701b9
2026-01-04T17:46:28.976145Z
false
skaes/time_bandits
https://github.com/skaes/time_bandits/blob/6354956aa25040d2b68d21bdb49d50ea13a701b9/test/unit/sequel_test.rb
test/unit/sequel_test.rb
require_relative '../test_helper' require 'sequel' class SequelTest < Test::Unit::TestCase def setup TimeBandits.time_bandits = [] TimeBandits.add TimeBandits::TimeConsumers::Sequel TimeBandits.reset end test "getting metrics" do nothing_measured = { :db_time => 0, :db_calls => 0 } assert_equal nothing_measured, metrics assert_equal 0, TimeBandits.consumed assert_equal 0, TimeBandits.current_runtime end test "formatting" do bandit.calls = 3 assert_equal "Sequel: 0.000ms(3q)", TimeBandits.runtime end test "metrics" do (1..4).each { sequel['SELECT 1'].all } assert_equal 6, metrics[:db_calls] # +2 for set wait_timeout and set SQL_AUTO_IS_NULL=0 assert 0 < metrics[:db_time] assert_equal metrics[:db_time], TimeBandits.consumed end def mysql_port 3601 end def sequel @sequel ||= Sequel.mysql2(host: "127.0.0.1", port: mysql_port, user: "root") end def metrics TimeBandits.metrics end def bandit TimeBandits::TimeConsumers::Sequel.instance end end
ruby
MIT
6354956aa25040d2b68d21bdb49d50ea13a701b9
2026-01-04T17:46:28.976145Z
false
skaes/time_bandits
https://github.com/skaes/time_bandits/blob/6354956aa25040d2b68d21bdb49d50ea13a701b9/test/unit/duplicate_bandits.rb
test/unit/duplicate_bandits.rb
require_relative '../test_helper' class DuplicateBandits < Test::Unit::TestCase class FooConsumer < TimeBandits::TimeConsumers::BaseConsumer prefix :simple fields :time, :calls format "SimpleFoo: %.1fms(%d calls)", :time, :calls end class BarConsumer < TimeBandits::TimeConsumers::BaseConsumer prefix :simple fields :time, :calls format "SimpleBar: %.1fms(%d calls)", :time, :calls end def setup TimeBandits.time_bandits = [] TimeBandits.add FooConsumer TimeBandits.add BarConsumer TimeBandits.reset end test "nothing measured" do assert_equal({ :simple_time => 0, :simple_calls => 0 }, TimeBandits.metrics) end test "only one consumer measured sth (the one)" do FooConsumer.instance.calls = 3 FooConsumer.instance.time = 0.123 assert_equal({ :simple_time => 0.123, :simple_calls => 3 }, TimeBandits.metrics) end test "only one consumer measured sth (the other)" do BarConsumer.instance.calls = 2 BarConsumer.instance.time = 0.321 assert_equal({ :simple_time => 0.321, :simple_calls => 2 }, TimeBandits.metrics) end test "both consumer measured sth" do FooConsumer.instance.calls = 3 FooConsumer.instance.time = 0.123 BarConsumer.instance.calls = 2 BarConsumer.instance.time = 0.321 assert_equal({ :simple_time => 0.444, :simple_calls => 5 }, TimeBandits.metrics) end end
ruby
MIT
6354956aa25040d2b68d21bdb49d50ea13a701b9
2026-01-04T17:46:28.976145Z
false
skaes/time_bandits
https://github.com/skaes/time_bandits/blob/6354956aa25040d2b68d21bdb49d50ea13a701b9/test/unit/active_support_notifications_test.rb
test/unit/active_support_notifications_test.rb
require_relative '../test_helper' require 'active_support/notifications' require 'active_support/log_subscriber' require 'thread_variables/access' class ActiveSupportNotificationsTest < Test::Unit::TestCase class SimpleConsumer < TimeBandits::TimeConsumers::BaseConsumer prefix :simple fields :time, :calls format "Simple: %.1fms(%d calls)", :time, :calls class Subscriber < ActiveSupport::LogSubscriber def work(event) i = SimpleConsumer.instance i.time += event.duration i.calls += 1 end end Subscriber.attach_to :simple end def setup TimeBandits.time_bandits = [] TimeBandits.add SimpleConsumer TimeBandits.reset @bandit = SimpleConsumer.instance end test "getting metrics" do assert_equal({:simple_calls => 0, :simple_time => 0}, TimeBandits.metrics) assert_equal 0, TimeBandits.consumed assert_equal 0, TimeBandits.current_runtime end test "formatting" do assert_same @bandit, TimeBandits.time_bandits.first.instance @bandit.calls = 1 assert_equal "Simple: 0.0ms(1 calls)", TimeBandits.runtime end test "foreground work gets accounted for in milliseconds" do work check_work end test "background work is ignored" do Thread.new do work check_work end.join m = TimeBandits.metrics assert_equal 0, m[:simple_calls] assert_equal 0, m[:simple_time] end private def work 2.times do ActiveSupport::Notifications.instrument("work.simple") { sleep 0.1 } end end def check_work m = TimeBandits.metrics assert_equal 2, m[:simple_calls] assert 200 < m[:simple_time] assert 300 > m[:simple_time] assert_equal m[:simple_time], TimeBandits.consumed end end
ruby
MIT
6354956aa25040d2b68d21bdb49d50ea13a701b9
2026-01-04T17:46:28.976145Z
false
skaes/time_bandits
https://github.com/skaes/time_bandits/blob/6354956aa25040d2b68d21bdb49d50ea13a701b9/test/unit/gc_consumer_test.rb
test/unit/gc_consumer_test.rb
require_relative '../test_helper' class GCConsumerTest < Test::Unit::TestCase def setup TimeBandits.time_bandits = [] TimeBandits.add TimeBandits::TimeConsumers::GarbageCollection.instance TimeBandits.reset end test "getting metrics" do # example metrics hash: sample = { :gc_time => 0.5, :gc_calls => 0, :heap_growth => 0, :heap_size => 116103, :allocated_objects => 8, :allocated_bytes => 152, :live_data_set_size => 69437 } m = TimeBandits.metrics assert_equal sample.keys.sort, m.keys.sort assert_equal 0, TimeBandits.consumed assert_equal 0, TimeBandits.current_runtime end test "formatting" do # example runtime: # "GC: 0.000(0) | HP: 0(116101,6,0,69442)" gc, heap = TimeBandits.runtime.split(' | ') assert_equal "GC: 0.000(0)", gc match = /\AHP: \d+\(\d+,\d+,\d+,\d+\)/ assert(heap =~ match, "#{heap} does not match #{match}") end test "collecting GC stats" do work check_work end private def work TimeBandits.reset a = [] 10.times do |i| a << (i.to_s * 100) end end def check_work GC.start m = TimeBandits.metrics if GC.respond_to?(:time) assert_operator 0, :<, m[:gc_calls] assert_operator 0, :<, m[:gc_time] assert_instance_of Integer, m[:heap_growth] assert_operator 0, :<, m[:heap_size] assert_operator 0, :<, m[:allocated_objects] assert_operator 0, :<, m[:allocated_bytes] assert_operator 0, :<=, m[:live_data_set_size] else assert_operator 0, :<, m[:gc_calls] assert_operator 0, :<=, m[:gc_time] assert_instance_of Integer, m[:heap_growth] assert_operator 0, :<, m[:heap_size] assert_operator 0, :<, m[:allocated_objects] assert_operator 0, :<=, m[:allocated_bytes] assert_operator 0, :<, m[:live_data_set_size] end end end
ruby
MIT
6354956aa25040d2b68d21bdb49d50ea13a701b9
2026-01-04T17:46:28.976145Z
false
skaes/time_bandits
https://github.com/skaes/time_bandits/blob/6354956aa25040d2b68d21bdb49d50ea13a701b9/test/unit/base_test.rb
test/unit/base_test.rb
require_relative '../test_helper' class NoTimeBanditsTest < Test::Unit::TestCase def setup TimeBandits.time_bandits = [] end test "getting list of all time bandits" do assert_equal [], TimeBandits.time_bandits test_clean_state end test "reset" do assert_nothing_raised { TimeBandits.reset } test_clean_state end test "benchmarking" do logger = mock("logger") logger.expects(:info) TimeBandits.benchmark("foo", logger) { } test_clean_state end private def test_clean_state assert_equal Hash.new, TimeBandits.metrics assert_equal 0, TimeBandits.consumed assert_equal 0, TimeBandits.current_runtime assert_equal "", TimeBandits.runtime end end class DummyConsumerTest < Test::Unit::TestCase module DummyConsumer extend self def consumed; 1; end def current_runtime; 1; end def runtime; "Dummy: 0ms"; end def metrics; {:dummy_time => 1, :dummy_calls => 1}; end def reset; end end def setup TimeBandits.time_bandits = [] TimeBandits.add DummyConsumer end test "getting list of all time bandits" do assert_equal [DummyConsumer], TimeBandits.time_bandits end test "adding consumer a second time does not change the list of time bandits" do TimeBandits.add DummyConsumer assert_equal [DummyConsumer], TimeBandits.time_bandits end test "reset" do assert_nothing_raised { TimeBandits.reset } end test "consumed" do assert_equal 1, TimeBandits.consumed end test "current_runtime" do assert_equal 1, TimeBandits.current_runtime end test "current_runtime without DummyConsumer" do assert_equal 0, TimeBandits.current_runtime(DummyConsumer) end test "getting metrics" do assert_equal({:dummy_time => 1, :dummy_calls => 1}, TimeBandits.metrics) end end
ruby
MIT
6354956aa25040d2b68d21bdb49d50ea13a701b9
2026-01-04T17:46:28.976145Z
false
skaes/time_bandits
https://github.com/skaes/time_bandits/blob/6354956aa25040d2b68d21bdb49d50ea13a701b9/test/unit/memcached_test.rb
test/unit/memcached_test.rb
require_relative '../test_helper' class MemcachedTest < Test::Unit::TestCase def setup skip "memcached is currently not supported on Ruby #{RUBY_VERSION} as the gem does not compile" unless RUBY_VERSION < "3.3.0" TimeBandits.time_bandits = [] TimeBandits.add TimeBandits::TimeConsumers::Memcached TimeBandits.reset @cache = Memcached.new @bandit = TimeBandits::TimeConsumers::Memcached.instance end test "getting metrics" do nothing_measured = { :memcache_time => 0, :memcache_calls => 0, :memcache_misses => 0, :memcache_reads => 0, :memcache_writes => 0 } assert_equal nothing_measured, TimeBandits.metrics assert_equal 0, TimeBandits.consumed assert_equal 0, TimeBandits.current_runtime end test "formatting" do @bandit.calls = 3 assert_equal "MC: 0.000(0r,0m,0w,3c)", TimeBandits.runtime end test "foreground work gets accounted for" do work check_work end test "background work is ignored" do Thread.new do work check_work end.join m = TimeBandits.metrics assert_equal 0, m[:memcache_calls] assert_equal 0, m[:memcache_reads] assert_equal 0, m[:memcache_misses] assert_equal 0, m[:memcache_writes] assert_equal 0, m[:memcache_time] end private def work 2.times do @cache.get("foo") @cache.set("bar", 1) end end def check_work m = TimeBandits.metrics assert_equal 4, m[:memcache_calls] assert_equal 2, m[:memcache_reads] assert_equal 2, m[:memcache_misses] assert_equal 2, m[:memcache_writes] assert 0 < m[:memcache_time] assert_equal m[:memcache_time], TimeBandits.consumed end end
ruby
MIT
6354956aa25040d2b68d21bdb49d50ea13a701b9
2026-01-04T17:46:28.976145Z
false
skaes/time_bandits
https://github.com/skaes/time_bandits/blob/6354956aa25040d2b68d21bdb49d50ea13a701b9/test/unit/dalli_test.rb
test/unit/dalli_test.rb
require_relative '../test_helper' class DalliTest < Test::Unit::TestCase def setup TimeBandits.time_bandits = [] TimeBandits.add TimeBandits::TimeConsumers::Dalli TimeBandits.reset @cache = Rails.cache @bandit = TimeBandits::TimeConsumers::Dalli.instance end test "getting metrics" do nothing_measured = { :memcache_time => 0, :memcache_calls => 0, :memcache_misses => 0, :memcache_reads => 0, :memcache_writes => 0 } assert_equal nothing_measured, TimeBandits.metrics assert_equal 0, TimeBandits.consumed assert_equal 0, TimeBandits.current_runtime end test "formatting" do @bandit.calls = 3 assert_equal "Dalli: 0.000(0r,0m,0w,3c)", TimeBandits.runtime end test "foreground work gets accounted for" do work check_work end test "background work is ignored" do Thread.new do work check_work end.join m = TimeBandits.metrics assert_equal 0, m[:memcache_calls] assert_equal 0, m[:memcache_reads] assert_equal 0, m[:memcache_misses] assert_equal 0, m[:memcache_writes] assert_equal 0, m[:memcache_time] end private def work TimeBandits.reset 2.times do @cache.read("foo") @cache.write("bar", 1) end end def check_work m = TimeBandits.metrics assert_equal 4, m[:memcache_calls] assert_equal 2, m[:memcache_reads] assert_equal 2, m[:memcache_misses] assert_equal 2, m[:memcache_writes] assert 0 < m[:memcache_time] assert_equal m[:memcache_time], TimeBandits.consumed end end
ruby
MIT
6354956aa25040d2b68d21bdb49d50ea13a701b9
2026-01-04T17:46:28.976145Z
false
skaes/time_bandits
https://github.com/skaes/time_bandits/blob/6354956aa25040d2b68d21bdb49d50ea13a701b9/lib/time_bandits.rb
lib/time_bandits.rb
require 'logger' require 'active_support' require 'active_support/core_ext' require 'thread_variables' module TimeBandits module TimeConsumers autoload :Database, 'time_bandits/time_consumers/database' autoload :GarbageCollection, 'time_bandits/time_consumers/garbage_collection' autoload :JMX, 'time_bandits/time_consumers/jmx' autoload :MemCache, 'time_bandits/time_consumers/mem_cache' autoload :Memcached, 'time_bandits/time_consumers/memcached' autoload :Dalli, 'time_bandits/time_consumers/dalli' autoload :Redis, 'time_bandits/time_consumers/redis' autoload :Sequel, 'time_bandits/time_consumers/sequel' autoload :Beetle, 'time_bandits/time_consumers/beetle' end require 'time_bandits/railtie' if defined?(Rails::Railtie) require 'time_bandits/time_consumers/base_consumer' mattr_accessor :time_bandits self.time_bandits = [] def self.add(bandit) self.time_bandits << bandit unless self.time_bandits.include?(bandit) end def self.reset time_bandits.each{|b| b.reset} end def self.consumed time_bandits.map{|b| b.consumed}.sum end def self.current_runtime(except = []) except = Array(except) time_bandits.map{|b| except.include?(b) ? 0 : b.current_runtime}.sum end def self.runtimes time_bandits.map{|b| b.runtime}.reject{|t| t.blank?} end def self.runtime runtimes.join(" | ") end def self.metrics metrics = Hash.new(0) time_bandits.each do |bandit| bandit.metrics.each do |k,v| metrics[k] += v end end metrics end def self.benchmark(title="Completed in", logger=Rails.logger) reset result = nil e = nil seconds = Benchmark.realtime do begin result = yield rescue Exception => e logger.error "Exception: #{e.class}(#{e.message}):\n#{e.backtrace[0..5].join("\n")}" end end consumed # needs to be called for DB time consumer rc = e ? "500 Internal Server Error" : "200 OK" logger.info "#{title} #{sprintf("%.3f", seconds * 1000)}ms (#{runtime}) | #{rc}" raise e if e result end end
ruby
MIT
6354956aa25040d2b68d21bdb49d50ea13a701b9
2026-01-04T17:46:28.976145Z
false
skaes/time_bandits
https://github.com/skaes/time_bandits/blob/6354956aa25040d2b68d21bdb49d50ea13a701b9/lib/time_bandits/version.rb
lib/time_bandits/version.rb
module TimeBandits VERSION = "0.15.2" end
ruby
MIT
6354956aa25040d2b68d21bdb49d50ea13a701b9
2026-01-04T17:46:28.976145Z
false
skaes/time_bandits
https://github.com/skaes/time_bandits/blob/6354956aa25040d2b68d21bdb49d50ea13a701b9/lib/time_bandits/railtie.rb
lib/time_bandits/railtie.rb
module TimeBandits module Rack autoload :Logger, 'time_bandits/rack/logger' end class Railtie < Rails::Railtie initializer "time_bandits" do |app| app.config.middleware.insert_after(Rails::Rack::Logger, TimeBandits::Rack::Logger) app.config.middleware.delete(Rails::Rack::Logger) ActiveSupport.on_load(:action_controller) do require 'time_bandits/monkey_patches/action_controller' # Rails 5 may trigger the on_load event several times. next if included_modules.include?(ActionController::TimeBanditry) # For some magic reason, the test above is always false, but I'll leave it in # here, should the Rails team ever decide to change this behavior. include ActionController::TimeBanditry # make sure TimeBandits.reset is called in test environment as middlewares are not executed if Rails.env.test? require 'action_controller/test_case' # Rails 5 fires on_load events multiple times, so we need to protect against endless recursion here next if ActionController::TestCase::Behavior.instance_methods.include?(:process_without_time_bandits) module ActionController::TestCase::Behavior def process_with_time_bandits(action, **opts) TimeBandits.reset process_without_time_bandits(action, **opts) end alias_method :process_without_time_bandits, :process alias_method :process, :process_with_time_bandits end end end ActiveSupport.on_load(:active_record) do require 'time_bandits/monkey_patches/active_record' # TimeBandits.add is idempotent, so no need to protect against on_load fired multiple times. TimeBandits.add TimeBandits::TimeConsumers::Database end # Reset statistics info, so that for example the time for the first request handled # by the dispatcher is correct. Also: install GC time bandit here, as we want it to # be the last one in the log line. app.config.after_initialize do TimeBandits.add TimeBandits::TimeConsumers::GarbageCollection.instance if GC.respond_to? :enable_stats TimeBandits.reset end end end end
ruby
MIT
6354956aa25040d2b68d21bdb49d50ea13a701b9
2026-01-04T17:46:28.976145Z
false
skaes/time_bandits
https://github.com/skaes/time_bandits/blob/6354956aa25040d2b68d21bdb49d50ea13a701b9/lib/time_bandits/monkey_patches/active_record.rb
lib/time_bandits/monkey_patches/active_record.rb
if Gem::Version.new(ActiveRecord::VERSION::STRING) < Gem::Version.new("7.1.0") require_relative "active_record/log_subscriber" else require_relative "active_record/runtime_registry" end require_relative "active_record/railties/controller_runtime"
ruby
MIT
6354956aa25040d2b68d21bdb49d50ea13a701b9
2026-01-04T17:46:28.976145Z
false
skaes/time_bandits
https://github.com/skaes/time_bandits/blob/6354956aa25040d2b68d21bdb49d50ea13a701b9/lib/time_bandits/monkey_patches/redis.rb
lib/time_bandits/monkey_patches/redis.rb
require 'redis' if Redis::VERSION < "5.0" class Redis class Client alias :old_logging :logging def logging(commands, &block) ActiveSupport::Notifications.instrument('request.redis', commands: commands) do old_logging(commands, &block) end end end end else module TimeBandits module RedisInstrumentation def call(command, redis_config) ActiveSupport::Notifications.instrument("request.redis", commands: [command]) do super end end def call_pipelined(commands, redis_config) ActiveSupport::Notifications.instrument("request.redis", commands: commands) do super end end end end RedisClient.register(TimeBandits::RedisInstrumentation) end
ruby
MIT
6354956aa25040d2b68d21bdb49d50ea13a701b9
2026-01-04T17:46:28.976145Z
false
skaes/time_bandits
https://github.com/skaes/time_bandits/blob/6354956aa25040d2b68d21bdb49d50ea13a701b9/lib/time_bandits/monkey_patches/sequel.rb
lib/time_bandits/monkey_patches/sequel.rb
require 'sequel' major, minor, _ = Sequel.version.split('.').map(&:to_i) if major < 4 || (major == 4 && minor < 15) raise "time_bandits Sequel monkey patch is not compatible with your sequel version" end Sequel::Database.class_eval do if instance_methods.include?(:log_connection_yield) alias :_orig_log_connection_yield :log_connection_yield def log_connection_yield(*args, &block) begin start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC) _orig_log_connection_yield(*args, &block) ensure end_time = Process.clock_gettime(Process::CLOCK_MONOTONIC) ActiveSupport::Notifications.instrument('duration.sequel', durationInSeconds: end_time - start_time) end end else alias :_orig_log_yield :log_yield def log_yield(*args, &block) begin start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC) _orig_log_yield(*args, &block) ensure end_time = Process.clock_gettime(Process::CLOCK_MONOTONIC) ActiveSupport::Notifications.instrument('duration.sequel', durationInSeconds: end_time - start_time) end end end end
ruby
MIT
6354956aa25040d2b68d21bdb49d50ea13a701b9
2026-01-04T17:46:28.976145Z
false
skaes/time_bandits
https://github.com/skaes/time_bandits/blob/6354956aa25040d2b68d21bdb49d50ea13a701b9/lib/time_bandits/monkey_patches/memcached.rb
lib/time_bandits/monkey_patches/memcached.rb
# Add this line to your ApplicationController (app/controllers/application_controller.rb) # to enable logging for memcached: # time_bandit TimeBandits::TimeConsumers::Memcached require 'memcached' raise "Memcached needs to be loaded before monkey patching it" unless defined?(Memcached) class Memcached def get_with_benchmark(key, marshal = true) ActiveSupport::Notifications.instrument("get.memcached") do |payload| if key.is_a?(Array) payload[:reads] = (num_keys = key.size) results = [] begin results = get_without_benchmark(key, marshal) rescue Memcached::NotFound end payload[:misses] = num_keys - results.size results else val = nil payload[:reads] = 1 begin val = get_without_benchmark(key, marshal) rescue Memcached::NotFound end payload[:misses] = val.nil? ? 1 : 0 val end end end alias_method :get_without_benchmark, :get alias_method :get, :get_with_benchmark def set_with_benchmark(*args) ActiveSupport::Notifications.instrument("set.memcached") do set_without_benchmark(*args) end end alias_method :set_without_benchmark, :set alias_method :set, :set_with_benchmark end
ruby
MIT
6354956aa25040d2b68d21bdb49d50ea13a701b9
2026-01-04T17:46:28.976145Z
false
skaes/time_bandits
https://github.com/skaes/time_bandits/blob/6354956aa25040d2b68d21bdb49d50ea13a701b9/lib/time_bandits/monkey_patches/action_controller.rb
lib/time_bandits/monkey_patches/action_controller.rb
module ActionController #:nodoc: require 'action_controller/metal/instrumentation' module Instrumentation def cleanup_view_runtime #:nodoc: consumed_before_rendering = TimeBandits.consumed runtime = yield consumed_during_rendering = TimeBandits.consumed - consumed_before_rendering runtime - consumed_during_rendering end private module ClassMethods # patch to log rendering time with more precision def log_process_action(payload) #:nodoc: messages, view_runtime = [], payload[:view_runtime] messages << ("Views: %.3fms" % view_runtime.to_f) if view_runtime messages end end end require 'action_controller/log_subscriber' class LogSubscriber # the original method logs the completed line. # but we do it in the middleware, unless we're in test mode. don't ask. def process_action(event) payload = event.payload additions = ActionController::Base.log_process_action(payload) Thread.current.thread_variable_set( :time_bandits_completed_info, [ event.duration, additions, payload[:view_runtime], "#{payload[:controller]}##{payload[:action]}" ] ) end end # this gets included in ActionController::Base in the time_bandits railtie module TimeBanditry #:nodoc: extend ActiveSupport::Concern module ClassMethods def log_process_action(payload) #:nodoc: # need to call this to compute DB time/calls TimeBandits.consumed super.concat(TimeBandits.runtimes) end end end end
ruby
MIT
6354956aa25040d2b68d21bdb49d50ea13a701b9
2026-01-04T17:46:28.976145Z
false
skaes/time_bandits
https://github.com/skaes/time_bandits/blob/6354956aa25040d2b68d21bdb49d50ea13a701b9/lib/time_bandits/monkey_patches/memcache-client.rb
lib/time_bandits/monkey_patches/memcache-client.rb
# Add this line to your ApplicationController (app/controllers/application.rb) # to enable logging for memcache-client: # time_bandit MemCache require 'memcache' raise "MemCache needs to be loaded before monkey patching it" unless defined?(MemCache) class MemCache def get_with_benchmark(key, raw = false) ActiveSupport::Notifications.instrument("get.memcache") do |payload| val = get_without_benchmark(key, raw) payload[:misses] = val.nil? ? 1 : 0 val end end alias_method :get_without_benchmark, :get alias_method :get, :get_with_benchmark def get_multi_with_benchmark(*keys) ActiveSupport::Notifications.instrument("get.memcache") do |payload| results = get_multi_without_benchmark(*keys) payload[:misses] = keys.size - results.size results end end alias_method :get_multi_without_benchmark, :get_multi alias_method :get_multi, :get_multi_with_benchmark end
ruby
MIT
6354956aa25040d2b68d21bdb49d50ea13a701b9
2026-01-04T17:46:28.976145Z
false
skaes/time_bandits
https://github.com/skaes/time_bandits/blob/6354956aa25040d2b68d21bdb49d50ea13a701b9/lib/time_bandits/monkey_patches/active_record/log_subscriber.rb
lib/time_bandits/monkey_patches/active_record/log_subscriber.rb
# This file monkey patches class ActiveRecord::LogSubscriber to count # the number of sql statements being executed and the number of query # cache hits, but is only used for Rails versions before 7.1.0. require "active_record/log_subscriber" module ActiveRecord class LogSubscriber IGNORE_PAYLOAD_NAMES = ["SCHEMA", "EXPLAIN"] unless defined?(IGNORE_PAYLOAD_NAMES) def self.call_count=(value) Thread.current.thread_variable_set(:active_record_sql_call_count, value) end def self.call_count Thread.current.thread_variable_get(:active_record_sql_call_count) || Thread.current.thread_variable_set(:active_record_sql_call_count, 0) end def self.query_cache_hits=(value) Thread.current.thread_variable_set(:active_record_sql_query_cache_hits, value) end def self.query_cache_hits Thread.current.thread_variable_get(:active_record_sql_query_cache_hits) || Thread.current.thread_variable_set(:active_record_sql_query_cache_hits, 0) end def self.reset_call_count calls = call_count self.call_count = 0 calls end def self.reset_query_cache_hits hits = query_cache_hits self.query_cache_hits = 0 hits end remove_method :sql def sql(event) payload = event.payload self.class.runtime += event.duration self.class.call_count += 1 self.class.query_cache_hits += 1 if payload[:cached] || payload[:name] == "CACHE" return unless logger.debug? return if IGNORE_PAYLOAD_NAMES.include?(payload[:name]) log_sql_statement(payload, event) end private def log_sql_statement(payload, event) name = "#{payload[:name]} (#{event.duration.round(1)}ms)" name = "CACHE #{name}" if payload[:cached] sql = payload[:sql] binds = nil unless (payload[:binds] || []).empty? casted_params = type_casted_binds(payload[:type_casted_binds]) binds = " " + payload[:binds].zip(casted_params).map { |attr, value| render_bind(attr, value) }.inspect end name = colorize_payload_name(name, payload[:name]) sql = color(sql, sql_color(sql), true) debug " #{name} #{sql}#{binds}" end end end
ruby
MIT
6354956aa25040d2b68d21bdb49d50ea13a701b9
2026-01-04T17:46:28.976145Z
false
skaes/time_bandits
https://github.com/skaes/time_bandits/blob/6354956aa25040d2b68d21bdb49d50ea13a701b9/lib/time_bandits/monkey_patches/active_record/runtime_registry.rb
lib/time_bandits/monkey_patches/active_record/runtime_registry.rb
# This file monkey patches class ActiveRecord::RuntimeRegistry to # additionally store call counts and cache hits and subscribes an # event listener to manage those counters. It is used if the active # record version is 7.1.0 or higher. require "active_record/runtime_registry" module ActiveRecord module RuntimeRegistry if respond_to?(:queries_count) alias_method :call_count, :queries_count alias_method :call_count=, :queries_count= else def self.call_count ActiveSupport::IsolatedExecutionState[:active_record_sql_call_count] ||= 0 end def self.call_count=(value) ActiveSupport::IsolatedExecutionState[:active_record_sql_call_count] = value end end if respond_to?(:cached_queries_count) alias_method :query_cache_hits, :cached_queries_count alias_method :query_cache_hits=, :cached_queries_count= else def self.query_cache_hits ActiveSupport::IsolatedExecutionState[:active_record_sql_query_cache_hits] ||= 0 end def self.query_cache_hits=(value) ActiveSupport::IsolatedExecutionState[:active_record_sql_query_cache_hits] = value end end if respond_to?(:reset_runtimes) alias_method :reset_runtime, :reset_runtimes else alias_method :reset_runtime, :reset end alias_method :runtime, :sql_runtime alias_method :runtime=, :sql_runtime= def self.reset_call_count calls = call_count self.call_count = 0 calls end def self.reset_query_cache_hits hits = query_cache_hits self.query_cache_hits = 0 hits end end end # Rails 7.2 already collects query counts and cache hits, so we no # longer need our own event handler. unless ActiveRecord::RuntimeRegistry.respond_to?(:queries_count) require "active_support/notifications" ActiveSupport::Notifications.monotonic_subscribe("sql.active_record") do |event| ActiveRecord::RuntimeRegistry.call_count += 1 ActiveRecord::RuntimeRegistry.query_cache_hits += 1 if event.payload[:cached] end end
ruby
MIT
6354956aa25040d2b68d21bdb49d50ea13a701b9
2026-01-04T17:46:28.976145Z
false
skaes/time_bandits
https://github.com/skaes/time_bandits/blob/6354956aa25040d2b68d21bdb49d50ea13a701b9/lib/time_bandits/monkey_patches/active_record/railties/controller_runtime.rb
lib/time_bandits/monkey_patches/active_record/railties/controller_runtime.rb
require "active_record/railties/controller_runtime" module ActiveRecord module Railties module ControllerRuntime remove_method :cleanup_view_runtime def cleanup_view_runtime # this method has been redefined to do nothing for activerecord on purpose super end remove_method :append_info_to_payload def append_info_to_payload(payload) super if ActiveRecord::Base.connected? payload[:db_runtime] = TimeBandits::TimeConsumers::Database.instance.consumed end end module ClassMethods # this method has been redefined to do nothing for activerecord on purpose remove_method :log_process_action def log_process_action(payload) super end end end end end
ruby
MIT
6354956aa25040d2b68d21bdb49d50ea13a701b9
2026-01-04T17:46:28.976145Z
false
skaes/time_bandits
https://github.com/skaes/time_bandits/blob/6354956aa25040d2b68d21bdb49d50ea13a701b9/lib/time_bandits/rack/logger.rb
lib/time_bandits/rack/logger.rb
require 'active_support/core_ext/time/conversions' require 'active_support/core_ext/object/blank' require 'active_support/log_subscriber' require 'action_dispatch/http/request' require 'rack/body_proxy' module TimeBandits module Rack # Sets log tags, logs the request, calls the app, and flushes the logs. class Logger < ActiveSupport::LogSubscriber def initialize(app, taggers = nil) @app = app @taggers = taggers || Rails.application.config.log_tags || [] @instrumenter = ActiveSupport::Notifications.instrumenter @use_to_default_s = Gem::Version.new(Rails::VERSION::STRING) < Gem::Version.new("7.1.0") end def call(env) request = ActionDispatch::Request.new(env) if logger.respond_to?(:tagged) && !@taggers.empty? logger.tagged(compute_tags(request)) { call_app(request, env) } else call_app(request, env) end end protected def call_app(request, env) start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC) start(request, Time.now) resp = @app.call(env) resp[2] = ::Rack::BodyProxy.new(resp[2]) { finish(request) } resp rescue finish(request) raise ensure end_time = Process.clock_gettime(Process::CLOCK_MONOTONIC) completed(request, (end_time - start_time) * 1000, resp) ActiveSupport::LogSubscriber.flush_all! end # Started GET "/session/new" for 127.0.0.1 at 2012-09-26 14:51:42 -0700 def started_request_message(request, start_time = Time.now) start_time_str = @use_to_default_s ? start_time.to_default_s : start_time.to_s 'Started %s "%s" for %s at %s' % [ request.request_method, request.filtered_path, request.ip, start_time_str ] end def compute_tags(request) @taggers.collect do |tag| case tag when Proc tag.call(request) when Symbol request.send(tag) else tag end end end private def start(request, start_time) TimeBandits.reset Thread.current.thread_variable_set(:time_bandits_completed_info, nil) @instrumenter.start 'action_dispatch.request', request: request logger.debug "" logger.info started_request_message(request, start_time) end def completed(request, run_time, resp) status = resp ? resp.first.to_i : 500 completed_info = Thread.current.thread_variable_get(:time_bandits_completed_info) additions = completed_info[1] if completed_info message = "Completed #{status} #{::Rack::Utils::HTTP_STATUS_CODES[status]} in %.1fms" % run_time message << " (#{additions.join(' | ')})" unless additions.blank? logger.info message end def finish(request) @instrumenter.finish 'action_dispatch.request', request: request end def logger @logger ||= Rails.logger end end end end
ruby
MIT
6354956aa25040d2b68d21bdb49d50ea13a701b9
2026-01-04T17:46:28.976145Z
false
skaes/time_bandits
https://github.com/skaes/time_bandits/blob/6354956aa25040d2b68d21bdb49d50ea13a701b9/lib/time_bandits/time_consumers/beetle.rb
lib/time_bandits/time_consumers/beetle.rb
# a time consumer implementation for beetle publishing # install into application_controller.rb with the line # # time_bandit TimeBandits::TimeConsumers::Beetle # module TimeBandits module TimeConsumers class Beetle < BaseConsumer prefix :amqp fields :time, :calls format "Beetle: %.3f(%d)", :time, :calls class Subscriber < ActiveSupport::LogSubscriber def publish(event) i = Beetle.instance i.time += event.duration i.calls += 1 return unless logger.debug? debug "%s (%.2fms)" % ["Beetle publish", event.duration] end end Subscriber.attach_to(:beetle) end end end
ruby
MIT
6354956aa25040d2b68d21bdb49d50ea13a701b9
2026-01-04T17:46:28.976145Z
false
skaes/time_bandits
https://github.com/skaes/time_bandits/blob/6354956aa25040d2b68d21bdb49d50ea13a701b9/lib/time_bandits/time_consumers/dalli.rb
lib/time_bandits/time_consumers/dalli.rb
module TimeBandits::TimeConsumers class Dalli < BaseConsumer prefix :memcache fields :time, :calls, :misses, :reads, :writes format "Dalli: %.3f(%dr,%dm,%dw,%dc)", :time, :reads, :misses, :writes, :calls class Subscriber < ActiveSupport::LogSubscriber # cache events are: read write fetch_hit generate delete read_multi increment decrement clear def cache_read(event) i = cache(event) i.reads += 1 i.misses += 1 unless event.payload[:hit] end def cache_read_multi(event) i = cache(event) i.reads += event.payload[:key].size end def cache_write(event) i = cache(event) i.writes += 1 end def cache_increment(event) i = cache(event) i.writes += 1 end def cache_decrement(event) i = cache(event) i.writes += 1 end def cache_delete(event) i = cache(event) i.writes += 1 end private def cache(event) i = Dalli.instance i.time += event.duration i.calls += 1 i end end Subscriber.attach_to :active_support end end
ruby
MIT
6354956aa25040d2b68d21bdb49d50ea13a701b9
2026-01-04T17:46:28.976145Z
false
skaes/time_bandits
https://github.com/skaes/time_bandits/blob/6354956aa25040d2b68d21bdb49d50ea13a701b9/lib/time_bandits/time_consumers/redis.rb
lib/time_bandits/time_consumers/redis.rb
# a time consumer implementation for redis # install into application_controller.rb with the line # # time_bandit TimeBandits::TimeConsumers::Redis # require 'time_bandits/monkey_patches/redis' module TimeBandits module TimeConsumers class Redis < BaseConsumer prefix :redis fields :time, :calls format "Redis: %.3f(%d)", :time, :calls class Subscriber < ActiveSupport::LogSubscriber def request(event) i = Redis.instance i.time += event.duration i.calls += 1 # count redis round trips, not calls return unless logger.debug? name = "%s (%.2fms)" % ["Redis", event.duration] cmds = event.payload[:commands] # output = " #{color(name, CYAN, true)}" output = " #{name}" cmds.each do |cmd, *args| if args.present? logged_args = args.map do |a| case when a.respond_to?(:inspect) then a.inspect when a.respond_to?(:to_s) then a.to_s else # handle poorly-behaved descendants of BasicObject klass = a.instance_exec { (class << self; self end).superclass } "\#<#{klass}:#{a.__id__}>" end end output << " [ #{cmd.to_s.upcase} #{logged_args.join(" ")} ]" else output << " [ #{cmd.to_s.upcase} ]" end end debug output end end Subscriber.attach_to(:redis) end end end
ruby
MIT
6354956aa25040d2b68d21bdb49d50ea13a701b9
2026-01-04T17:46:28.976145Z
false
skaes/time_bandits
https://github.com/skaes/time_bandits/blob/6354956aa25040d2b68d21bdb49d50ea13a701b9/lib/time_bandits/time_consumers/sequel.rb
lib/time_bandits/time_consumers/sequel.rb
# a time consumer implementation for sequel # install into application_controller.rb with the line # # time_bandit TimeBandits::TimeConsumers::Sequel # require 'time_bandits/monkey_patches/sequel' module TimeBandits module TimeConsumers class Sequel < BaseConsumer prefix :db fields :time, :calls format "Sequel: %.3fms(%dq)", :time, :calls class Subscriber < ActiveSupport::LogSubscriber def duration(event) i = Sequel.instance i.time += (event.payload[:durationInSeconds] * 1000) i.calls += 1 end end Subscriber.attach_to(:sequel) end end end
ruby
MIT
6354956aa25040d2b68d21bdb49d50ea13a701b9
2026-01-04T17:46:28.976145Z
false
skaes/time_bandits
https://github.com/skaes/time_bandits/blob/6354956aa25040d2b68d21bdb49d50ea13a701b9/lib/time_bandits/time_consumers/memcached.rb
lib/time_bandits/time_consumers/memcached.rb
# a time consumer implementation for memchached # install into application_controller.rb with the line # # time_bandit TimeBandits::TimeConsumers::Memcached # require 'time_bandits/monkey_patches/memcached' module TimeBandits module TimeConsumers class Memcached < BaseConsumer prefix :memcache fields :time, :calls, :misses, :reads, :writes format "MC: %.3f(%dr,%dm,%dw,%dc)", :time, :reads, :misses, :writes, :calls class Subscriber < ActiveSupport::LogSubscriber def get(event) i = Memcached.instance i.time += event.duration i.calls += 1 payload = event.payload i.reads += payload[:reads] i.misses += payload[:misses] end def set(event) i = Memcached.instance i.time += event.duration i.calls += 1 i.writes += 1 end end Subscriber.attach_to :memcached end end end
ruby
MIT
6354956aa25040d2b68d21bdb49d50ea13a701b9
2026-01-04T17:46:28.976145Z
false
skaes/time_bandits
https://github.com/skaes/time_bandits/blob/6354956aa25040d2b68d21bdb49d50ea13a701b9/lib/time_bandits/time_consumers/mem_cache.rb
lib/time_bandits/time_consumers/mem_cache.rb
# a time consumer implementation for memchache # install into application_controller.rb with the line # # time_bandit TimeBandits::TimeConsumers::MemCache # require 'time_bandits/monkey_patches/memcache-client' module TimeBandits module TimeConsumers class Memcache < BaseConsumer prefix :memcache fields :time, :calls, :misses format "MC: %.3f(%dr,%dm)", :time, :calls, :misses class Subscriber < ActiveSupport::LogSubscriber def get(event) i = Memcache.instance i.time += event.duration i.calls += 1 i.misses += event.payload[:misses] end end Subscriber.attach_to :memcache end end end
ruby
MIT
6354956aa25040d2b68d21bdb49d50ea13a701b9
2026-01-04T17:46:28.976145Z
false
skaes/time_bandits
https://github.com/skaes/time_bandits/blob/6354956aa25040d2b68d21bdb49d50ea13a701b9/lib/time_bandits/time_consumers/base_consumer.rb
lib/time_bandits/time_consumers/base_consumer.rb
module TimeBandits::TimeConsumers class BaseConsumer class << self def instance Thread.current.thread_variable_get(key) || Thread.current.thread_variable_set(key, new) end def key @key ||= name.to_sym end def prefix(sym) @metrics_prefix = sym end # first symbol is used as time measurement def fields(*symbols) @struct = Struct.new(*(symbols.map{|s| "#{@metrics_prefix}_#{s}".to_sym})) symbols.each do |name| class_eval(<<-"EVA", __FILE__, __LINE__ + 1) def #{name}; @counters.#{@metrics_prefix}_#{name}; end def #{name}=(v); @counters.#{@metrics_prefix}_#{name} = v; end EVA end end def format(f, *keys) @runtime_format = f @runtime_keys = keys.map{|s| "#{@metrics_prefix}_#{s}".to_sym} end attr_reader :metrics_prefix, :struct, :timer_name, :runtime_format, :runtime_keys def method_missing(m, *args) (i = instance).respond_to?(m) ? i.send(m,*args) : super end end def initialize @counters = self.class.struct.new reset end def reset @counters.length.times{|i| @counters[i] = 0} end def metrics @counters.members.each_with_object({}){|m,h| h[m] = @counters.send(m)} end def consumed @counters[0] end alias_method :current_runtime, :consumed def runtime values = metrics.values_at(*self.class.runtime_keys) if values.all?{|v|v==0} "" else self.class.runtime_format % values end end end end
ruby
MIT
6354956aa25040d2b68d21bdb49d50ea13a701b9
2026-01-04T17:46:28.976145Z
false
skaes/time_bandits
https://github.com/skaes/time_bandits/blob/6354956aa25040d2b68d21bdb49d50ea13a701b9/lib/time_bandits/time_consumers/jmx.rb
lib/time_bandits/time_consumers/jmx.rb
# a time consumer implementation for jruby, using jmx # # the gc counts and times reported are summed over all the garbage collectors # heap_growth reflects changes in the committed size of the java heap # heap_size is the committed size of the java heap # allocated_size reflects changes in the active (used) part of the java heap # java non-heap memory is not reported require 'jmx' if defined? JRUBY_VERSION module TimeBandits module TimeConsumers class JMX def initialize @server = ::JMX::MBeanServer.new @memory_bean = @server["java.lang:type=Memory"] @collectors = @server.query_names "java.lang:type=GarbageCollector,*" reset end private :initialize def self.instance @instance ||= new end def consumed 0.0 end def gc_time @collectors.to_array.map {|gc| @server[gc].collection_time}.sum end def gc_collections @collectors.to_array.map {|gc| @server[gc].collection_count}.sum end def heap_size @memory_bean.heap_memory_usage.committed end def heap_usage @memory_bean.heap_memory_usage.used end def reset @consumed = gc_time @collections = gc_collections @heap_committed = heap_size @heap_used = heap_usage end def collections_delta gc_collections - @collections end def gc_time_delta (gc_time - @consumed).to_f end def heap_growth heap_size - @heap_committed end def usage_growth heap_usage - @heap_used end def allocated_objects 0 end def runtime "GC: %.3f(%d), HP: %d(%d,%d,%d)" % [gc_time_delta, collections_delta, heap_growth, heap_size, allocated_objects, usage_growth] end end end end
ruby
MIT
6354956aa25040d2b68d21bdb49d50ea13a701b9
2026-01-04T17:46:28.976145Z
false
skaes/time_bandits
https://github.com/skaes/time_bandits/blob/6354956aa25040d2b68d21bdb49d50ea13a701b9/lib/time_bandits/time_consumers/garbage_collection.rb
lib/time_bandits/time_consumers/garbage_collection.rb
# a time consumer implementation for garbage collection module TimeBandits module TimeConsumers class GarbageCollection @@heap_dumps_enabled = false def self.heap_dumps_enabled=(v) @@heap_dumps_enabled = v end def initialize enable_stats reset end private :initialize def self.instance @instance ||= new end def enable_stats return unless GC.respond_to? :enable_stats GC.enable_stats if defined?(PhusionPassenger) PhusionPassenger.on_event(:starting_worker_process) do |forked| GC.enable_stats if forked end end end if GC.respond_to?(:time) def _get_gc_time; GC.time; end elsif GC.respond_to?(:total_time) def _get_gc_time; GC.total_time / 1000; end else def _get_gc_time; 0; end end def _get_collections; GC.count; end def _get_allocated_objects; GC.stat(:total_allocated_objects); end if GC.respond_to?(:total_malloced_bytes) def _get_allocated_size; GC.total_malloced_bytes; end else # this will wrap around :malloc_increase_bytes_limit so is not really correct def _get_allocated_size; GC.stat(:malloc_increase_bytes); end end if GC.respond_to?(:heap_slots) def _get_heap_slots; GC.heap_slots; end else def _get_heap_slots; GC.stat(:heap_live_slots) + GC.stat(:heap_free_slots) + GC.stat(:heap_final_slots); end end if GC.respond_to?(:heap_slots_live_after_last_gc) def live_data_set_size; GC.heap_slots_live_after_last_gc; end else def live_data_set_size; GC.stat(:heap_live_slots); end end def reset @consumed = _get_gc_time @collections = _get_collections @allocated_objects = _get_allocated_objects @allocated_size = _get_allocated_size @heap_slots = _get_heap_slots end def consumed 0.0 end alias_method :current_runtime, :consumed def consumed_gc_time # ms (_get_gc_time - @consumed).to_f / 1000 end def collections _get_collections - @collections end def allocated_objects _get_allocated_objects - @allocated_objects end def allocated_size new_size = _get_allocated_size old_size = @allocated_size new_size <= old_size ? new_size : new_size - old_size end def heap_growth _get_heap_slots - @heap_slots end GCFORMAT = "GC: %.3f(%d) | HP: %d(%d,%d,%d,%d)" def runtime heap_slots = _get_heap_slots heap_growth = self.heap_growth allocated_objects = self.allocated_objects allocated_size = self.allocated_size GCHacks.heap_dump if heap_growth > 0 && @@heap_dumps_enabled && defined?(GCHacks) GCFORMAT % [consumed_gc_time, collections, heap_growth, heap_slots, allocated_objects, allocated_size, live_data_set_size] end def metrics { :gc_time => consumed_gc_time, :gc_calls => collections, :heap_growth => heap_growth, :heap_size => _get_heap_slots, :allocated_objects => allocated_objects, :allocated_bytes => allocated_size, :live_data_set_size => live_data_set_size } end end end end
ruby
MIT
6354956aa25040d2b68d21bdb49d50ea13a701b9
2026-01-04T17:46:28.976145Z
false
skaes/time_bandits
https://github.com/skaes/time_bandits/blob/6354956aa25040d2b68d21bdb49d50ea13a701b9/lib/time_bandits/time_consumers/database.rb
lib/time_bandits/time_consumers/database.rb
# this consumer gets installed automatically by the plugin # if this were not so # # TimeBandit.add TimeBandits::TimeConsumers::Database # # would do the job module TimeBandits module TimeConsumers # provide a time consumer interface to ActiveRecord class Database < TimeBandits::TimeConsumers::BaseConsumer prefix :db fields :time, :calls, :sql_query_cache_hits format "ActiveRecord: %.3fms(%dq,%dh)", :time, :calls, :sql_query_cache_hits class << self if Gem::Version.new(ActiveRecord::VERSION::STRING) >= Gem::Version.new("7.1.0") def metrics_store ActiveRecord::RuntimeRegistry end else def metrics_store ActiveRecord::LogSubscriber end end end def reset reset_stats super end def consumed time, calls, hits = reset_stats i = Database.instance i.sql_query_cache_hits += hits i.calls += calls i.time += time end def current_runtime Database.instance.time + self.class.metrics_store.runtime end private def reset_stats s = self.class.metrics_store hits = s.reset_query_cache_hits calls = s.reset_call_count time = s.reset_runtime [time, calls, hits] end end end end
ruby
MIT
6354956aa25040d2b68d21bdb49d50ea13a701b9
2026-01-04T17:46:28.976145Z
false
tomdalling/value_semantics
https://github.com/tomdalling/value_semantics/blob/209069ad7b3ad42f3bdbc9c4ed556dac21693f3d/benchmarks/initialize.rb
benchmarks/initialize.rb
require 'allocation_tracer' require 'pp' require 'benchmark/ips' require 'value_semantics' module StringCoercer def self.call(obj) if obj.is_a?(Symbol) obj.to_s else obj end end end class VSPerson include ValueSemantics.for_attributes { name String, coerce: StringCoercer age Integer, default: nil born_at default_generator: Time.method(:now) a4 default: nil } end class ManualPerson attr_reader :name, :age def initialize(name:, age: nil, born_at: nil, a4: nil) @name = if name.is_a?(Symbol) name.to_s elsif name.is_a?(String) name else raise ArgumentError end @age = if age.is_a?(Integer) age else raise ArgumentError end @born_at = born_at || Time.now @a4 = a4 end end Benchmark.ips do |x| x.report("VS") do |times| i = 0 while i < times VSPerson.new(name: 'Jim', age: 5) i += 1 end end x.report("Manual") do |times| i = 0 while i < times ManualPerson.new(name: 'Jim', age: 5) i += 1 end end x.compare! end puts 'Memory Allocations'.ljust(40, '-') pp ObjectSpace::AllocationTracer.trace { i = 0 while i < 1000 VSPerson.new(name: 'Jim', age: 5) i += 1 end }
ruby
MIT
209069ad7b3ad42f3bdbc9c4ed556dac21693f3d
2026-01-04T17:46:31.511345Z
false
tomdalling/value_semantics
https://github.com/tomdalling/value_semantics/blob/209069ad7b3ad42f3bdbc9c4ed556dac21693f3d/spec/either_spec.rb
spec/either_spec.rb
RSpec.describe ValueSemantics::Either do subject { described_class.new([Integer, String]) } it 'matches any of the subvalidators' do is_expected.to be === 5 is_expected.to be === 'hello' end it 'does not match anything else' do expect(subject === nil).to be(false) expect(subject === [1,2,3]).to be(false) end it 'is frozen' do is_expected.to be_frozen end end
ruby
MIT
209069ad7b3ad42f3bdbc9c4ed556dac21693f3d
2026-01-04T17:46:31.511345Z
false
tomdalling/value_semantics
https://github.com/tomdalling/value_semantics/blob/209069ad7b3ad42f3bdbc9c4ed556dac21693f3d/spec/pattern_matching_spec.rb
spec/pattern_matching_spec.rb
# Only works in Ruby 2.7+ RSpec.describe ValueSemantics, 'pattern matching integration' do shared_examples 'pattern matching' do it 'deconstructs to a hash' do case subject in { name:, age: Integer => age } expect(name).to eq('Tom') expect(age).to eq(69) else fail "Hash deconstruction not implemented properly" end end end context 'class with ValueSemantics included' do include_examples 'pattern matching' subject do Class.new do include ValueSemantics.for_attributes { name String age Integer } end.new(name: 'Tom', age: 69) end end context 'ValueSemantics::Struct class' do include_examples 'pattern matching' subject do ValueSemantics::Struct.new do name String age Integer end.new(name: 'Tom', age: 69) end end end
ruby
MIT
209069ad7b3ad42f3bdbc9c4ed556dac21693f3d
2026-01-04T17:46:31.511345Z
false
tomdalling/value_semantics
https://github.com/tomdalling/value_semantics/blob/209069ad7b3ad42f3bdbc9c4ed556dac21693f3d/spec/dsl_spec.rb
spec/dsl_spec.rb
RSpec.describe ValueSemantics::DSL do subject { described_class.new } it 'turns method calls into attributes' do subject.fOO(Integer, default: 3, coerce: 'hi') expect(subject.__attributes.first).to have_attributes( name: :fOO, validator: Integer, coercer: 'hi', ) expect(subject.__attributes.first.default_generator.call).to eq(3) end it 'does not interfere with existing methods' do expect(subject.respond_to?(:Float, true)).to be(true) expect(subject.respond_to?(:Float)).to be(false) end it 'disallows methods that begin with capitals' do expect { subject.Hello }.to raise_error(NoMethodError) expect(subject.respond_to?(:Wigwam)).to be(false) expect(subject.respond_to?(:Wigwam, true)).to be(false) end it 'has a built-in Either matcher' do validator = subject.Either(String, Integer) expect(validator).to be === 5 end it 'has a built-in Anything matcher' do validator = subject.Anything expect(validator).to be === RSpec end it 'has a built-in Bool matcher' do validator = subject.Bool expect(validator).to be === false end it 'has a built-in ArrayOf matcher' do validator = subject.ArrayOf(String) expect(validator).to be === %w(1 2 3) end context 'built-in HashOf matcher' do it 'matches hashes' do validator = subject.HashOf(Symbol => Integer) expect(validator).to be === {a: 2, b:2} end it 'raises ArgumentError if the argument is wrong' do expect { subject.HashOf({a: 1, b: 2}) }.to raise_error(ArgumentError, "HashOf() takes a hash with one key and one value", ) end end it 'has a built-in RangeOf matcher' do validator = subject.RangeOf(Integer) expect(validator).to be === (1..10) end it 'has a built-in ArrayCoercer coercer' do coercer = subject.ArrayCoercer(:to_i.to_proc) expect(coercer.(%w(1 2 3))).to eq([1, 2, 3]) end it 'provides a way to define methods whose names are invalid Ruby syntax' do subject.def_attr(:else) expect(subject.__attributes.first.name).to eq(:else) end context 'built-in HashCoercer coercer' do it 'allows anything for keys/values by default' do coercer = subject.HashCoercer() expect(coercer.({whatever: 42})).to eq({whatever: 42}) end it 'can take coercers for keys and values' do coercer = subject.HashCoercer( keys: ->(x) { x.to_sym }, values: ->(x) { x.to_i }, ) expect(coercer.({'x' => '1'})).to eq({x: 1}) end end it "produces a frozen recipe with DSL.run" do recipe = described_class.run { whatever } expect(recipe).to be_a(ValueSemantics::Recipe) expect(recipe).to be_frozen expect(recipe.attributes).to be_frozen expect(recipe.attributes.first).to be_frozen expect(recipe.attributes.first.name).to eq(:whatever) end it 'allows attributes to end with punctuation' do subject.qmark? subject.bang! expect(subject.__attributes.map(&:name)).to eq([:qmark?, :bang!]) end it 'does not return anything when defining attributes' do expect(subject.foo).to be(nil) end end
ruby
MIT
209069ad7b3ad42f3bdbc9c4ed556dac21693f3d
2026-01-04T17:46:31.511345Z
false
tomdalling/value_semantics
https://github.com/tomdalling/value_semantics/blob/209069ad7b3ad42f3bdbc9c4ed556dac21693f3d/spec/array_coercer_spec.rb
spec/array_coercer_spec.rb
RSpec.describe ValueSemantics::ArrayCoercer do it 'is frozen' do is_expected.to be_frozen end it 'calls #to_a on objects that respond to it' do expect(subject.(double(to_a: ['yep']))).to eq(['yep']) end it 'does not affect objects that dont respond to #to_a' do expect(subject.(111)).to eq(111) end context 'with an element coercer' do subject { described_class.new(:join.to_proc) } it 'applies the element coercer to each element' do expect(subject.({a:1, b:2})).to eq(['a1', 'b2']) end end end
ruby
MIT
209069ad7b3ad42f3bdbc9c4ed556dac21693f3d
2026-01-04T17:46:31.511345Z
false
tomdalling/value_semantics
https://github.com/tomdalling/value_semantics/blob/209069ad7b3ad42f3bdbc9c4ed556dac21693f3d/spec/struct_spec.rb
spec/struct_spec.rb
RSpec.describe ValueSemantics::Struct do subject do described_class.new do attr1 Array, default: [4,5,6] attr2 end end it "returns a value class, like Struct.new does" do expect(subject).to be_a(Class) expect(subject.value_semantics).to be_a(ValueSemantics::Recipe) expect(subject.new(attr2: nil)).to be_a(subject) end it "makes instances that work like normal ValueSemantics objects" do instance = subject.new(attr2: 2) expect(instance.attr1).to eq([4,5,6]) expect(instance.attr2).to eq(2) end end
ruby
MIT
209069ad7b3ad42f3bdbc9c4ed556dac21693f3d
2026-01-04T17:46:31.511345Z
false
tomdalling/value_semantics
https://github.com/tomdalling/value_semantics/blob/209069ad7b3ad42f3bdbc9c4ed556dac21693f3d/spec/range_of_spec.rb
spec/range_of_spec.rb
RSpec.describe ValueSemantics::RangeOf do subject { described_class.new(Integer) } it 'matches ranges using the given subvalidator' do is_expected.to be === (1..10) end it 'does not match ranges whose `begin` does not match the subvalidator' do expect(subject === (1.0..10)).to be(false) end it 'does not match ranges whose `end` does not match the subvalidator' do expect(subject === (1..10.0)).to be(false) end it 'does not match objects that are not ranges' do expect(subject === 'hello').to be(false) end end
ruby
MIT
209069ad7b3ad42f3bdbc9c4ed556dac21693f3d
2026-01-04T17:46:31.511345Z
false
tomdalling/value_semantics
https://github.com/tomdalling/value_semantics/blob/209069ad7b3ad42f3bdbc9c4ed556dac21693f3d/spec/value_semantics_spec.rb
spec/value_semantics_spec.rb
require "pp" RSpec.describe ValueSemantics do around do |example| # this is necessary for mutation testing to work properly with_constant(:Doggums, dog_class) { example.run } end let(:dog_class) do Class.new do include ValueSemantics.for_attributes { name trained? } end end describe 'initialization' do it "supports keyword arguments" do dog = Doggums.new(name: 'Fido', trained?: true) expect(dog).to have_attributes(name: 'Fido', trained?: true) end it "supports Hash arguments" do dog = Doggums.new({ name: 'Rufus', trained?: true }) expect(dog).to have_attributes(name: 'Rufus', trained?: true) end it "supports any value that responds to #to_h" do arg = double(to_h: { name: 'Rex', trained?: true }) dog = Doggums.new(arg) expect(dog).to have_attributes(name: 'Rex', trained?: true) end it "does not mutate hash arguments" do attrs = { name: 'Kipper', trained?: true } expect { Doggums.new(attrs) }.not_to change { attrs } end it "can not be constructed with attributes missing" do expect { Doggums.new }.to raise_error( ValueSemantics::MissingAttributes, "Some attributes required by `Doggums` are missing: `name`, `trained?`", ) end it "can not be constructed with undefined attributes" do expect { Doggums.new(name: 'Fido', trained?: true, meow: 'cattt', moo: 'cowww') }.to raise_error( ValueSemantics::UnrecognizedAttributes, "`Doggums` does not define attributes: `:meow`, `:moo`", ) end it "gives precedence to `UnrecognizedAttributes` over `MissingAttributes`" do expect { Doggums.new(nayme: 'Fiydo', tentacles: 8) } .to raise_error(ValueSemantics::UnrecognizedAttributes, /tentacles/) end it "can not be constructed with an object that does not respond to #to_h" do expect { dog_class.new(double) }.to raise_error(TypeError, <<~END_MESSAGE.strip.split.join(' ') Can not initialize a `Doggums` with a `RSpec::Mocks::Double` object. This argument is typically a `Hash` of attributes, but can be any object that responds to `#to_h`. END_MESSAGE ) end it "does not intercept errors raised from calling #to_h" do arg = double allow(arg).to receive(:to_h).and_raise("this implementation sucks") expect { dog_class.new(arg) }.to raise_error("this implementation sucks") end end describe 'basic usage' do it "has attr readers and ivars" do dog = Doggums.new(name: 'Fido', trained?: true) expect(dog).to have_attributes(name: 'Fido', trained?: true) expect(dog.instance_variable_get(:@name)).to eq('Fido') expect(dog.instance_variable_get(:@trained)).to eq(true) end it "does not define attr writers" do dog = Doggums.new(name: 'Fido', trained?: true) expect{ dog.name = 'Goofy' }.to raise_error(NoMethodError, /name=/) expect{ dog.trained = false }.to raise_error(NoMethodError, /trained=/) end it "has square brackets as a variable attr reader" do dog = Doggums.new(name: 'Fido', trained?: true) expect(dog[:name]).to eq('Fido') expect { dog[:fins] }.to raise_error( ValueSemantics::UnrecognizedAttributes, "`Doggums` has no attribute named `:fins`" ) end it "can do non-destructive updates" do sally = Doggums.new(name: 'Sally', trained?: false) bob = sally.with(name: 'Bob') expect(bob).to have_attributes(name: 'Bob', trained?: false) end it "can be converted to a hash of attributes" do dog = Doggums.new(name: 'Fido', trained?: false) expect(dog.to_h).to eq({ name: 'Fido', trained?: false }) end it "has a human-friendly #inspect string" do dog = Doggums.new(name: 'Fido', trained?: true) expect(dog.inspect).to eq('#<Doggums name="Fido" trained?=true>') end it "has nice pp output" do output = StringIO.new dog = Doggums.new(name: "Fido", trained?: true) PP.pp(dog, output, 3) expect(output.string).to eq(<<~END_PP) #<Doggums name="Fido" trained?=true> END_PP end it "has a human-friendly module name" do mod = Doggums.ancestors[1] expect(mod.name).to eq("Doggums::ValueSemantics_Attributes") end end describe 'default values' do let(:cat) do Class.new do include ValueSemantics.for_attributes { name default: 'Kitty' scratch_proc default: ->{ "scratch" } born_at default_generator: ->{ Time.now } } end end it "uses the default if no value is given" do expect(cat.new.name).to eq('Kitty') end it "allows the default to be overriden" do expect(cat.new(name: 'Tomcat').name).to eq('Tomcat') end it "does not override nil" do expect(cat.new(name: nil).name).to be_nil end it "allows procs as default values" do expect(cat.new.scratch_proc.call).to eq("scratch") end it "can generate defaults with a proc" do expect(cat.new.born_at).to be_a(Time) end end describe 'validation' do module WingValidator def self.===(value) case value when 'feathery flappers' then true when 'smooth feet' then false else fail 'wut?' end end end class Birb include ValueSemantics.for_attributes { wings WingValidator i Integer } end it "accepts values that pass the validator" do expect{ Birb.new(wings: 'feathery flappers', i: 0) }.not_to raise_error end it "rejects values that fail the validator" do expect{ Birb.new(wings: 'smooth feet', i: 0.0) }.to raise_error( ValueSemantics::InvalidValue, <<~END_ERROR Some attributes of `Birb` are invalid: - wings: "smooth feet" - i: 0.0 END_ERROR ) end it "does not validate missing attributes" do expect{ Birb.new(i: 0) }.to raise_error(ValueSemantics::MissingAttributes) end end describe "equality" do let(:puppy_class) { Class.new(Doggums) } let(:dog1) { Doggums.new(name: 'Fido', trained?: true) } let(:dog2) { Doggums.new(name: 'Fido', trained?: true) } let(:different) { Doggums.new(name: 'Brutus', trained?: false) } let(:child) { puppy_class.new(name: 'Fido', trained?: true) } it "defines loose equality between subclasses with #===" do expect(dog1).to eq(dog2) expect(dog1).not_to eq(different) expect(dog1).not_to eq("hello") expect(dog1).to eq(child) expect(child).to eq(dog1) end it "defines strict equality with #eql?" do expect(dog1.eql?(dog2)).to be(true) expect(dog1.eql?(different)).to be(false) expect(dog1.eql?(child)).to be(false) expect(child.eql?(dog1)).to be(false) end it "allows objects to be used as keys in Hash objects" do expect(dog1.hash).to eq(dog2.hash) expect(dog1.hash).not_to eq(different.hash) hash_key_test = { dog1 => 'woof', different => 'diff' }.merge(dog2 => 'bark') expect(hash_key_test).to eq({ dog1 => 'bark', different => 'diff' }) end it "hashes differently depending on class" do expect(dog1.hash).not_to eq(child.hash) end end describe 'coercion' do module Callable def self.call(x) "callable: #{x}" end end class CoercionTest include ValueSemantics.for_attributes { no_coercion String, default: "" with_true String, coerce: true, default: "" with_callable String, coerce: Callable, default: "" double_it String, coerce: ->(x) { x * 2 }, default: "42" } private def self.coerce_with_true(value) "class_method: #{value}" end def self.coerce_no_coercion(value) fail "Should never get here" end end it "does not call coercion methods by default" do subject = CoercionTest.new(no_coercion: 'dinklage') expect(subject.no_coercion).to eq('dinklage') end it "calls a class method when coerce: true" do subject = CoercionTest.new(with_true: 'peter') expect(subject.with_true).to eq('class_method: peter') end it "calls obj.call when coerce: obj" do subject = CoercionTest.new(with_callable: 'daenerys') expect(subject.with_callable).to eq('callable: daenerys') end it "coerces default values" do subject = CoercionTest.new expect(subject.double_it).to eq('4242') end it "performs coercion before validation" do expect { CoercionTest.new(double_it: 6) }.to raise_error( ValueSemantics::InvalidValue, <<~END_ERROR Some attributes of `CoercionTest` are invalid: - double_it: 12 END_ERROR ) end it "provides a class method for coercing hashes into value objects" do value = CoercionTest.coercer.([['no_coercion', 'wario']]) expect(value.no_coercion).to eq('wario') end end context 'when attr readers are `protected` or `private`' do subject do Class.new do include ValueSemantics.for_attributes { pubby protecty privvy } protected :protecty private :privvy end.new(pubby: 1, protecty: 2, privvy: 3) end it "doesn't affect public attrs" do expect(subject.pubby).to eq(1) end it "raises NoMethodError when attempting to access non-public attrs" do expect { subject.protecty }.to raise_error(NoMethodError, /protected/) expect { subject[:protecty] }.to raise_error(NoMethodError, /protected/) expect { subject.privvy }.to raise_error(NoMethodError, /private/) expect { subject[:privvy] }.to raise_error(NoMethodError, /private/) end it "allows `protected` and `private` attr readers to be called from the inside" do expect(subject.send(:protecty)).to eq(2) expect(subject.send(:privvy)).to eq(3) end # # From https://github.com/zverok/good-value-object : # # > Always try to provide `#to_h`, it is really good for serialization: # > # > - `#to_h` should probably return hash with symbolic keys, containing # > exactly all the structural elements of value object and nothing more; # > # > - If value object's constructor uses keyword arguments, # > `ValueType.new(**value.to_h) == value` should be always `true` # it 'still returns all attributes from `#to_h`' do expect(subject.to_h).to eq({pubby: 1, protecty: 2, privvy: 3}) end # If they can be passed to `#initialize`, then it makes sense they can also # be passed to `#with`. it 'allows all attrs to be updated via #with' do updated = subject.with(pubby: 11, protecty: 22, privvy: 33) expect(updated.pubby).to eq(11) expect(updated.send(:protecty)).to eq(22) expect(updated.send(:privvy)).to eq(33) end it 'does not break other methods' do clone = subject.with({}) expect(subject).not_to be(clone) expect(subject).to eq(clone) expect(subject).to eql(clone) expect(subject.hash).not_to be_nil expect(subject.inspect).to include('pubby', 'protecty', 'privvy') expect(subject.deconstruct_keys(nil)).to eq(subject.to_h) end end it "has a version number" do expect(ValueSemantics::VERSION).not_to be_empty end end
ruby
MIT
209069ad7b3ad42f3bdbc9c4ed556dac21693f3d
2026-01-04T17:46:31.511345Z
false
tomdalling/value_semantics
https://github.com/tomdalling/value_semantics/blob/209069ad7b3ad42f3bdbc9c4ed556dac21693f3d/spec/range_of_endless_spec.rb
spec/range_of_endless_spec.rb
# Only works in Ruby 2.6+ RSpec.describe ValueSemantics::RangeOf do subject { described_class.new(Integer) } it 'matches beginless ranges' do is_expected.to be === (1..) end it 'matches endless ranges' do is_expected.to be === (..10) end end
ruby
MIT
209069ad7b3ad42f3bdbc9c4ed556dac21693f3d
2026-01-04T17:46:31.511345Z
false
tomdalling/value_semantics
https://github.com/tomdalling/value_semantics/blob/209069ad7b3ad42f3bdbc9c4ed556dac21693f3d/spec/value_object_coercer_spec.rb
spec/value_object_coercer_spec.rb
RSpec.describe ValueSemantics::ValueObjectCoercer do subject { described_class.new(Seal) } class Seal include ValueSemantics.for_attributes { name String d Integer, default: 1 } end it "converts hashes to an instance of the given value class" do expect(subject.(name: 'Jim')).to eq(Seal.new(name: 'Jim', d: 1)) end it "allows extraneous keys" do expect(subject.(name: 'x', age: 10)).to eq(Seal.new(name: 'x', d: 1)) end it "allows keys to be strings" do expect(subject.('name' => 'y')).to eq(Seal.new(name: 'y', d: 1)) end it "takes symbol keys before string keys" do expect(subject.(name: 'a', 'name' => 'b')).to eq(Seal.new(name: 'a', d: 1)) end it "allows hashable objects" do hashable = double(to_h: { 'name' => 'z' }) expect(subject.(hashable)).to eq(Seal.new(name: 'z', d: 1)) end it "ignores non-hashable objects" do non_hashable = double expect(subject.(non_hashable)).to equal(non_hashable) end end
ruby
MIT
209069ad7b3ad42f3bdbc9c4ed556dac21693f3d
2026-01-04T17:46:31.511345Z
false
tomdalling/value_semantics
https://github.com/tomdalling/value_semantics/blob/209069ad7b3ad42f3bdbc9c4ed556dac21693f3d/spec/hash_coercer_spec.rb
spec/hash_coercer_spec.rb
RSpec.describe ValueSemantics::HashCoercer do subject do described_class.new( key_coercer: ->(x) { x.to_sym }, value_coercer: ->(x) { x.to_i }, ) end it { is_expected.to be_frozen } it 'coerces hash-like objects to hashes' do hashlike = double(to_h: {a: 1}) expect(subject.(hashlike)).to eq({a: 1}) end it 'returns non-hash-like objects, unchanged' do expect(subject.(5)).to eq(5) end it 'allows empty hashes' do expect(subject.({})).to eq({}) end it 'coerces hash keys' do expect(subject.({'a' => 1})).to eq({a: 1}) end it 'coerces hash values' do expect(subject.({a: '1'})).to eq({a: 1}) end end
ruby
MIT
209069ad7b3ad42f3bdbc9c4ed556dac21693f3d
2026-01-04T17:46:31.511345Z
false
tomdalling/value_semantics
https://github.com/tomdalling/value_semantics/blob/209069ad7b3ad42f3bdbc9c4ed556dac21693f3d/spec/attribute_spec.rb
spec/attribute_spec.rb
RSpec.describe ValueSemantics::Attribute do context 'defined with no options in particular' do subject { described_class.define(:whatever) } it 'raises if attempting to use missing default attribute' do expect { subject.default_generator.call }.to raise_error( "Attribute does not have a default value" ) end it 'has default attributes' do expect(subject).to have_attributes( name: :whatever, validator: be(ValueSemantics::Anything), coercer: nil, default_generator: be(ValueSemantics::Attribute::NO_DEFAULT_GENERATOR), ) end it { is_expected.to be_frozen } it { is_expected.not_to be_optional } end context 'initialized with no options in particular' do subject { described_class.new(name: :whatever) } it 'has default attributes' do expect(subject).to have_attributes( name: :whatever, validator: be(ValueSemantics::Anything), coercer: nil, default_generator: be(ValueSemantics::Attribute::NO_DEFAULT_GENERATOR), ) end end context 'with a name ending in "?"' do subject { described_class.new(name: :x?) } it 'does not include the "?" in the instance variable name' do is_expected.to have_attributes(instance_variable: '@x') end end context 'with a name ending in "!"' do subject { described_class.new(name: :x!) } it 'does not include the "!" in the instance variable name' do is_expected.to have_attributes(instance_variable: '@x') end end context 'with a string name' do subject { described_class.new(name: 'x') } it 'converts the string to a symbol' do is_expected.to have_attributes(name: :x) end end context 'defined with a validator' do subject { described_class.define(:x, Integer) } it 'uses the validator in `validate?`' do expect(subject.validate?(5)).to be(true) expect(subject.validate?(:x)).to be(false) end end context 'defined with a `true` coercer' do subject { described_class.define(:x, coerce: true) } it 'calls a class method to do coercion' do klass = double allow(klass).to receive(:coerce_x).with(5).and_return(66) expect(subject.coerce(5, klass)).to eq(66) end end context 'defined with a callable coercer' do subject { described_class.define(:x, coerce: ->(v) { v + 100 }) } it 'calls the coercer with the given value' do expect(subject.coerce(1, nil)).to eq(101) end end context 'defined with a default' do subject { described_class.define(:x, default: 88) } it { is_expected.to be_optional } it 'returns the default value from default_generator' do expect(subject.default_generator.()).to eq(88) end end context 'defined with a default generator' do subject { described_class.define(:x, default_generator: ->() { 77 }) } it { is_expected.to be_optional } it 'sets default_generator' do expect(subject.default_generator.()).to eq(77) end end context 'defined with both a default and a default generator' do subject { described_class.define(:x, default: 5, default_generator: 5) } it 'raises an error' do expect { subject }.to raise_error(ArgumentError, "Attribute `x` can not have both a `:default` and a `:default_generator`" ) end end context 'deprecated #determine_from!' do subject do described_class.new( name: :x, validator: Integer, **attrs, ) end let(:attrs) { {} } class Penguin def self.coerce_x(x) x * 2 end end it 'returns a [name, value] tuple on success' do expect(subject.determine_from!({ x: 3 }, Penguin)).to eq([:x, 3]) end it 'raises MissingAttributes if the attr cant be found' do expect { subject.determine_from!({}, Penguin) }.to raise_error( ValueSemantics::MissingAttributes, 'Attribute `Penguin#x` has no value', ) end it 'raises InvalidValue when a validator fails' do expect { subject.determine_from!({ x: 'no' }, Penguin) }.to raise_error( ValueSemantics::InvalidValue, 'Attribute `Penguin#x` is invalid: "no"', ) end context 'with a default_generator' do before { attrs[:default_generator] = ->(){ 100 } } it 'calls the default_generator' do expect(subject.determine_from!({}, Penguin)).to eq([:x, 100]) end end context 'with coercer: true' do before { attrs[:coercer] = true } it 'calls the coercion class method' do expect(subject.determine_from!({x: 4}, Penguin)).to eq([:x, 8]) end end end end
ruby
MIT
209069ad7b3ad42f3bdbc9c4ed556dac21693f3d
2026-01-04T17:46:31.511345Z
false
tomdalling/value_semantics
https://github.com/tomdalling/value_semantics/blob/209069ad7b3ad42f3bdbc9c4ed556dac21693f3d/spec/array_of_spec.rb
spec/array_of_spec.rb
require 'set' RSpec.describe ValueSemantics::ArrayOf do subject { described_class.new(Integer) } it 'uses the subvalidator for each element in the array' do is_expected.to be === [1,2,3] is_expected.to be === [] end it 'does not match anything else' do expect(subject === nil).to be(false) expect(subject === 'hello').to be(false) expect(subject === %i(1 2 3)).to be(false) expect(subject === Set.new([1, 2, 3])).to be(false) end it 'is frozen' do is_expected.to be_frozen end end
ruby
MIT
209069ad7b3ad42f3bdbc9c4ed556dac21693f3d
2026-01-04T17:46:31.511345Z
false
tomdalling/value_semantics
https://github.com/tomdalling/value_semantics/blob/209069ad7b3ad42f3bdbc9c4ed556dac21693f3d/spec/hash_of_spec.rb
spec/hash_of_spec.rb
RSpec.describe ValueSemantics::HashOf do subject { described_class.new(Integer, Float) } it 'matches empty hashes' do is_expected.to be === {} end it 'matches hashes where the key and value validators also match' do is_expected.to be === { 1 => 1.2, 2 => 2.4 } end it 'does not match hashes where the key validator does not match' do expect(subject === { a: 1.2 }).to be(false) end it 'does not match hashes where the value validator does not match' do expect(subject === { 1 => 'no' }).to be(false) end it 'does not match anything else' do expect(subject === nil).to be(false) expect(subject === 'hello').to be(false) expect(subject === [1, 1.2, 2, 2.4]).to be(false) expect(subject === [[1, 1.2], [2, 2.4]]).to be(false) end it 'is frozen' do is_expected.to be_frozen end end
ruby
MIT
209069ad7b3ad42f3bdbc9c4ed556dac21693f3d
2026-01-04T17:46:31.511345Z
false
tomdalling/value_semantics
https://github.com/tomdalling/value_semantics/blob/209069ad7b3ad42f3bdbc9c4ed556dac21693f3d/spec/monkey_patch_spec.rb
spec/monkey_patch_spec.rb
RSpec.describe ValueSemantics, '.monkey_patch!' do after(:each) do undo_monkey_patch! if monkey_patched? Object.send(:remove_const, :Munkey) if Object.const_defined?(:Munkey) end def monkey_patched? Class.respond_to?(:value_semantics, true) end def undo_monkey_patch! Class.class_eval do public :value_semantics remove_method :value_semantics end end def define_munkey! eval <<~END_CODE class Munkey value_semantics do age Integer end end END_CODE end specify "we can patch an unpatch reliably" do 2.times do expect(monkey_patched?).to be_falsey ValueSemantics.monkey_patch! expect(monkey_patched?).to be_truthy undo_monkey_patch! expect(monkey_patched?).to be_falsey end end shared_examples "monkey-patched `value_semantics` class method" do it "is disabled by default" do expect { define_munkey! } .to raise_error(NameError, /undefined method `value_semantics'/) end context 'when enabled' do before do install_monkey_patch! end it "makes `value_semantics` class method available to all classes" do define_munkey! expect(Munkey.new(age: 1)).to have_attributes(age: 1) end it "is class-private" do expect { Integer.value_semantics } .to raise_error(NoMethodError, /private method `value_semantics' called/) end it "is replaced by the class-public recipe getter after being called" do define_munkey! expect(Munkey.value_semantics).to be_a(ValueSemantics::Recipe) end it "can not be called twice" do define_munkey! expect { define_munkey! }.to raise_error( RuntimeError, '`Munkey` has already included ValueSemantics', ) end it "does not affect modules" do expect do Module.new do extend self value_semantics do name String end end end.to raise_error(NameError, /undefined method `value_semantics'/) end it "does nothing if enabled multiple times" do 3.times { install_monkey_patch! } define_munkey! expect(Munkey.new(age: 99)).to have_attributes(age: 99) end end end context 'using `ValueSemantics.monkey_patch!`' do include_examples "monkey-patched `value_semantics` class method" def install_monkey_patch! ValueSemantics.monkey_patch! end end context "using `require 'value_semantics/monkey_patched'`" do include_examples "monkey-patched `value_semantics` class method" def install_monkey_patch! # allow `require` to load the file multiple times $LOADED_FEATURES.reject! do |path| path.end_with?('value_semantics/monkey_patched.rb') end require 'value_semantics/monkey_patched' end end end
ruby
MIT
209069ad7b3ad42f3bdbc9c4ed556dac21693f3d
2026-01-04T17:46:31.511345Z
false
tomdalling/value_semantics
https://github.com/tomdalling/value_semantics/blob/209069ad7b3ad42f3bdbc9c4ed556dac21693f3d/spec/bool_spec.rb
spec/bool_spec.rb
RSpec.describe ValueSemantics::Bool do it 'matches true and false' do is_expected.to be === true is_expected.to be === false end it 'does not match nil or other values' do expect(subject === nil).to be(false) expect(subject === 5).to be(false) end end
ruby
MIT
209069ad7b3ad42f3bdbc9c4ed556dac21693f3d
2026-01-04T17:46:31.511345Z
false
tomdalling/value_semantics
https://github.com/tomdalling/value_semantics/blob/209069ad7b3ad42f3bdbc9c4ed556dac21693f3d/spec/spec_helper.rb
spec/spec_helper.rb
require "bundler/setup" require "delegate" require "super_diff/rspec" require "value_semantics" require "byebug" module SpecHelperMethods def with_constant(const_name, const_value) Object.const_set(const_name, const_value) yield ensure Object.send(:remove_const, const_name) end end RSpec.configure do |config| config.include SpecHelperMethods # Enable flags like --only-failures and --next-failure config.example_status_persistence_file_path = ".rspec_status" # Disable RSpec exposing methods globally on `Module` and `main` config.disable_monkey_patching! config.expect_with :rspec do |c| c.syntax = :expect end end
ruby
MIT
209069ad7b3ad42f3bdbc9c4ed556dac21693f3d
2026-01-04T17:46:31.511345Z
false
tomdalling/value_semantics
https://github.com/tomdalling/value_semantics/blob/209069ad7b3ad42f3bdbc9c4ed556dac21693f3d/lib/value_semantics.rb
lib/value_semantics.rb
%w( anything array_coercer array_of attribute bool class_methods dsl either hash_of hash_coercer instance_methods range_of recipe struct value_object_coercer version ).each do |filename| require_relative "value_semantics/#{filename}" end module ValueSemantics class Error < StandardError; end class UnrecognizedAttributes < Error; end class MissingAttributes < Error; end class InvalidValue < ArgumentError; end # @deprecated Use {Attribute::NOT_SPECIFIED} instead NOT_SPECIFIED = Attribute::NOT_SPECIFIED # @deprecated Use {Attribute#optional?} to check if there is a default or not class NoDefaultValue < Error; end # # Creates a module via the DSL # # @yield The block containing the DSL # @return [Module] # # @see DSL # @see InstanceMethods # def self.for_attributes(&block) recipe = DSL.run(&block) bake_module(recipe) end # # Creates a module from a {Recipe} # # @param recipe [Recipe] # @return [Module] # def self.bake_module(recipe) Module.new do const_set(:VALUE_SEMANTICS_RECIPE__, recipe) include(InstanceMethods) # define the attr readers recipe.attributes.each do |attr| module_eval("def #{attr.name}; #{attr.instance_variable}; end") end def self.included(base) base.const_set(:ValueSemantics_Attributes, self) base.extend(ClassMethods) end end end # # Makes the +.value_semantics+ convenience method available to all classes # # +.value_semantics+ is a shortcut for {.for_attributes}. Instead of: # # class Person # include ValueSemantics.for_attributes { # name String # } # end # # You can just write: # # class Person # value_semantics do # name String # end # end # # Alternatively, you can +require 'value_semantics/monkey_patched'+, which # will call this method automatically. # def self.monkey_patch! Class.class_eval do # @!visibility private def value_semantics(&block) include ValueSemantics.for_attributes(&block) end private :value_semantics end end end
ruby
MIT
209069ad7b3ad42f3bdbc9c4ed556dac21693f3d
2026-01-04T17:46:31.511345Z
false
tomdalling/value_semantics
https://github.com/tomdalling/value_semantics/blob/209069ad7b3ad42f3bdbc9c4ed556dac21693f3d/lib/value_semantics/recipe.rb
lib/value_semantics/recipe.rb
module ValueSemantics # # Contains all the configuration necessary to bake a ValueSemantics module # # @see ValueSemantics.bake_module # @see ClassMethods#value_semantics # @see DSL.run # class Recipe attr_reader :attributes def initialize(attributes:) @attributes = attributes freeze end end end
ruby
MIT
209069ad7b3ad42f3bdbc9c4ed556dac21693f3d
2026-01-04T17:46:31.511345Z
false
tomdalling/value_semantics
https://github.com/tomdalling/value_semantics/blob/209069ad7b3ad42f3bdbc9c4ed556dac21693f3d/lib/value_semantics/version.rb
lib/value_semantics/version.rb
module ValueSemantics VERSION = "3.6.1" end
ruby
MIT
209069ad7b3ad42f3bdbc9c4ed556dac21693f3d
2026-01-04T17:46:31.511345Z
false
tomdalling/value_semantics
https://github.com/tomdalling/value_semantics/blob/209069ad7b3ad42f3bdbc9c4ed556dac21693f3d/lib/value_semantics/struct.rb
lib/value_semantics/struct.rb
module ValueSemantics # # ValueSemantics equivalent of the Struct class from the Ruby standard # library # class Struct # # Creates a new Class with ValueSemantics mixed in # # @yield a block containing ValueSemantics DSL # @return [Class] the newly created class # def self.new(&block) klass = Class.new klass.include(ValueSemantics.for_attributes(&block)) klass end end end
ruby
MIT
209069ad7b3ad42f3bdbc9c4ed556dac21693f3d
2026-01-04T17:46:31.511345Z
false
tomdalling/value_semantics
https://github.com/tomdalling/value_semantics/blob/209069ad7b3ad42f3bdbc9c4ed556dac21693f3d/lib/value_semantics/class_methods.rb
lib/value_semantics/class_methods.rb
module ValueSemantics # # All the class methods available on ValueSemantics classes # # When a ValueSemantics module is included into a class, # the class is extended by this module. # module ClassMethods # # @return [Recipe] the recipe used to build the ValueSemantics module that # was included into this class. # def value_semantics if block_given? # caller is trying to use the monkey-patched Class method raise "`#{self}` has already included ValueSemantics" end self::VALUE_SEMANTICS_RECIPE__ end # # A coercer object for the value class # # This is mostly useful when nesting value objects inside each other. # # @return [#call] A callable object that can be used as a coercer # @see ValueObjectCoercer # def coercer ValueObjectCoercer.new(self) end end end
ruby
MIT
209069ad7b3ad42f3bdbc9c4ed556dac21693f3d
2026-01-04T17:46:31.511345Z
false
tomdalling/value_semantics
https://github.com/tomdalling/value_semantics/blob/209069ad7b3ad42f3bdbc9c4ed556dac21693f3d/lib/value_semantics/bool.rb
lib/value_semantics/bool.rb
module ValueSemantics # # Validator that only matches `true` and `false` # module Bool # @return [Boolean] def self.===(value) true.equal?(value) || false.equal?(value) end end end
ruby
MIT
209069ad7b3ad42f3bdbc9c4ed556dac21693f3d
2026-01-04T17:46:31.511345Z
false
tomdalling/value_semantics
https://github.com/tomdalling/value_semantics/blob/209069ad7b3ad42f3bdbc9c4ed556dac21693f3d/lib/value_semantics/monkey_patched.rb
lib/value_semantics/monkey_patched.rb
require 'value_semantics' ValueSemantics.monkey_patch!
ruby
MIT
209069ad7b3ad42f3bdbc9c4ed556dac21693f3d
2026-01-04T17:46:31.511345Z
false
tomdalling/value_semantics
https://github.com/tomdalling/value_semantics/blob/209069ad7b3ad42f3bdbc9c4ed556dac21693f3d/lib/value_semantics/attribute.rb
lib/value_semantics/attribute.rb
module ValueSemantics # # Represents a single attribute of a value class # class Attribute NOT_SPECIFIED = Object.new.freeze NO_DEFAULT_GENERATOR = lambda do raise NoDefaultValue, "Attribute does not have a default value" end attr_reader :name, :validator, :coercer, :default_generator, :instance_variable, :optional alias_method :optional?, :optional def initialize( name:, default_generator: NO_DEFAULT_GENERATOR, validator: Anything, coercer: nil ) @name = name.to_sym @default_generator = default_generator @validator = validator @coercer = coercer @instance_variable = '@' + name.to_s.chomp('!').chomp('?') @optional = !default_generator.equal?(NO_DEFAULT_GENERATOR) freeze end def self.define( name, validator=Anything, default: NOT_SPECIFIED, default_generator: nil, coerce: nil ) # TODO: change how defaults are specified: # # - default: either a value, or a callable # - default_value: always a value # - default_generator: always a callable # # This would not be a backwards compatible change. generator = begin if default_generator && !default.equal?(NOT_SPECIFIED) raise ArgumentError, "Attribute `#{name}` can not have both a `:default` and a `:default_generator`" elsif default_generator default_generator elsif !default.equal?(NOT_SPECIFIED) ->{ default } else NO_DEFAULT_GENERATOR end end new( name: name, validator: validator, default_generator: generator, coercer: coerce, ) end # @deprecated Use a combination of the other instance methods instead def determine_from!(attr_hash, value_class) raw_value = attr_hash.fetch(name) do if default_generator.equal?(NO_DEFAULT_GENERATOR) raise MissingAttributes, "Attribute `#{value_class}\##{name}` has no value" else default_generator.call end end coerced_value = coerce(raw_value, value_class) if validate?(coerced_value) [name, coerced_value] else raise InvalidValue, "Attribute `#{value_class}\##{name}` is invalid: #{coerced_value.inspect}" end end def coerce(attr_value, value_class) return attr_value unless coercer # coercion not enabled if coercer.equal?(true) value_class.public_send(coercion_method, attr_value) else coercer.call(attr_value) end end def validate?(value) validator === value end def coercion_method "coerce_#{name}" end end end
ruby
MIT
209069ad7b3ad42f3bdbc9c4ed556dac21693f3d
2026-01-04T17:46:31.511345Z
false
tomdalling/value_semantics
https://github.com/tomdalling/value_semantics/blob/209069ad7b3ad42f3bdbc9c4ed556dac21693f3d/lib/value_semantics/either.rb
lib/value_semantics/either.rb
module ValueSemantics # # Validator that matches if any of the given subvalidators matches # class Either attr_reader :subvalidators def initialize(subvalidators) @subvalidators = subvalidators freeze end # @return [Boolean] def ===(value) subvalidators.any? { |sv| sv === value } end end end
ruby
MIT
209069ad7b3ad42f3bdbc9c4ed556dac21693f3d
2026-01-04T17:46:31.511345Z
false
tomdalling/value_semantics
https://github.com/tomdalling/value_semantics/blob/209069ad7b3ad42f3bdbc9c4ed556dac21693f3d/lib/value_semantics/range_of.rb
lib/value_semantics/range_of.rb
module ValueSemantics class RangeOf attr_reader :subvalidator def initialize(subvalidator) @subvalidator = subvalidator end def ===(obj) return false unless Range === obj # begin or end can be nil, if the range is beginless or endless [obj.begin, obj.end].compact.all? do |element| subvalidator === element end end end end
ruby
MIT
209069ad7b3ad42f3bdbc9c4ed556dac21693f3d
2026-01-04T17:46:31.511345Z
false
tomdalling/value_semantics
https://github.com/tomdalling/value_semantics/blob/209069ad7b3ad42f3bdbc9c4ed556dac21693f3d/lib/value_semantics/hash_of.rb
lib/value_semantics/hash_of.rb
module ValueSemantics # # Validator that matches +Hash+es with homogeneous keys and values # class HashOf attr_reader :key_validator, :value_validator def initialize(key_validator, value_validator) @key_validator, @value_validator = key_validator, value_validator freeze end # @return [Boolean] def ===(value) Hash === value && value.all? do |key, value| key_validator === key && value_validator === value end end end end
ruby
MIT
209069ad7b3ad42f3bdbc9c4ed556dac21693f3d
2026-01-04T17:46:31.511345Z
false
tomdalling/value_semantics
https://github.com/tomdalling/value_semantics/blob/209069ad7b3ad42f3bdbc9c4ed556dac21693f3d/lib/value_semantics/dsl.rb
lib/value_semantics/dsl.rb
module ValueSemantics # # Builds a {Recipe} via DSL methods # # DSL blocks are <code>instance_eval</code>d against an object of this class. # # @see Recipe # @see ValueSemantics.for_attributes # class DSL # TODO: this should maybe inherit from BasicObject so that method_missing # doesn't find methods on Kernel. This might have undesirable consequences # tho, and we will probably need to do some const_missing stuff to get it # working smoothly. Evaluate the feasability of this before the next major # version bump, because it would be a backwards-incompatible change. # # Builds a {Recipe} from a DSL block # # @yield to the block containing the DSL # @return [Recipe] def self.run(&block) dsl = new dsl.instance_eval(&block) Recipe.new(attributes: dsl.__attributes.freeze) end attr_reader :__attributes def initialize @__attributes = [] end def Bool Bool end def Either(*subvalidators) Either.new(subvalidators) end def Anything Anything end def ArrayOf(element_validator) ArrayOf.new(element_validator) end def HashOf(key_validator_to_value_validator) unless key_validator_to_value_validator.size.equal?(1) raise ArgumentError, "HashOf() takes a hash with one key and one value" end HashOf.new( key_validator_to_value_validator.keys.first, key_validator_to_value_validator.values.first, ) end def RangeOf(subvalidator) RangeOf.new(subvalidator) end def ArrayCoercer(element_coercer) ArrayCoercer.new(element_coercer) end IDENTITY_COERCER = :itself.to_proc def HashCoercer(keys: IDENTITY_COERCER, values: IDENTITY_COERCER) HashCoercer.new(key_coercer: keys, value_coercer: values) end # # Defines one attribute. # # This is the method that gets called under the hood, when defining # attributes the typical +#method_missing+ way. # # You can use this method directly if your attribute name results in invalid # Ruby syntax. For example, if you want an attribute named +then+, you # can do: # # include ValueSemantics.for_attributes { # # Does not work: # then String, default: "whatever" # #=> SyntaxError: syntax error, unexpected `then' # # # Works: # def_attr :then, String, default: "whatever" # } # # def def_attr(*args, **kwargs) __attributes << Attribute.define(*args, **kwargs) nil end def method_missing(name, *args, **kwargs) if respond_to_missing?(name) def_attr(name, *args, **kwargs) else super end end def respond_to_missing?(method_name, _include_private=nil) first_letter = method_name.to_s.each_char.first first_letter.eql?(first_letter.downcase) end end end
ruby
MIT
209069ad7b3ad42f3bdbc9c4ed556dac21693f3d
2026-01-04T17:46:31.511345Z
false
tomdalling/value_semantics
https://github.com/tomdalling/value_semantics/blob/209069ad7b3ad42f3bdbc9c4ed556dac21693f3d/lib/value_semantics/instance_methods.rb
lib/value_semantics/instance_methods.rb
module ValueSemantics # # All the instance methods available on ValueSemantics objects # module InstanceMethods # # Creates a value object based on a hash of attributes # # @param attributes [#to_h] A hash of attribute values by name. Typically a # +Hash+, but can be any object that responds to +#to_h+. # # @raise [UnrecognizedAttributes] if given_attrs contains keys that are not # attributes # @raise [MissingAttributes] if given_attrs is missing any attributes that # do not have defaults # @raise [InvalidValue] if any attribute values do no pass their validators # @raise [TypeError] if the argument does not respond to +#to_h+ # def initialize(attributes = nil) attributes_hash = if attributes.respond_to?(:to_h) attributes.to_h else raise TypeError, <<-END_MESSAGE.strip.gsub(/\s+/, ' ') Can not initialize a `#{self.class}` with a `#{attributes.class}` object. This argument is typically a `Hash` of attributes, but can be any object that responds to `#to_h`. END_MESSAGE end remaining_attrs = attributes_hash.keys missing_attrs = nil invalid_attrs = nil self.class.value_semantics.attributes.each do |attr| if remaining_attrs.delete(attr.name) value = attributes_hash.fetch(attr.name) elsif attr.optional? value = attr.default_generator.() else missing_attrs ||= [] missing_attrs << attr.name next end coerced_value = attr.coerce(value, self.class) if attr.validate?(coerced_value) instance_variable_set(attr.instance_variable, coerced_value) else invalid_attrs ||= {} invalid_attrs[attr.name] = coerced_value end end # TODO: aggregate all exceptions raised from #initialize into one big # exception that explains everything that went wrong, instead of multiple # smaller exceptions. Unfortunately, this would not be backwards # compatible. unless remaining_attrs.empty? raise UnrecognizedAttributes.new( "`#{self.class}` does not define attributes: " + remaining_attrs.map { |k| '`' + k.inspect + '`' }.join(', ') ) end if missing_attrs raise MissingAttributes.new( "Some attributes required by `#{self.class}` are missing: " + missing_attrs.map { |a| "`#{a}`" }.join(', ') ) end if invalid_attrs raise InvalidValue.new( "Some attributes of `#{self.class}` are invalid:\n" + invalid_attrs.map { |k,v| " - #{k}: #{v.inspect}" }.join("\n") + "\n" ) end end # # Returns the value for the given attribute name # # @param attr_name [Symbol] The name of the attribute. Can not be a +String+. # @return The value of the attribute # # @raise [UnrecognizedAttributes] if the attribute does not exist # def [](attr_name) attr = self.class.value_semantics.attributes.find do |attr| attr.name.equal?(attr_name) end if attr public_send(attr_name) else raise UnrecognizedAttributes, "`#{self.class}` has no attribute named `#{attr_name.inspect}`" end end # # Creates a copy of this object, with the given attributes changed (non-destructive update) # # @param new_attrs [Hash] the attributes to change # @return A new object, with the attribute changes applied # def with(new_attrs) self.class.new(to_h.merge(new_attrs)) end # # @return [Hash] all of the attributes # def to_h self.class.value_semantics.attributes .map { |attr| [attr.name, __send__(attr.name)] } .to_h end # # Loose equality # # @return [Boolean] whether all attributes are equal, and the object # classes are ancestors of eachother in any way # def ==(other) (other.is_a?(self.class) || is_a?(other.class)) && other.to_h.eql?(to_h) end # # Strict equality # # @return [Boolean] whether all attribuets are equal, and both objects # has the exact same class # def eql?(other) other.class.equal?(self.class) && other.to_h.eql?(to_h) end # # Unique-ish integer, based on attributes and class of the object # def hash to_h.hash ^ self.class.hash end def inspect attrs = to_h .map { |key, value| "#{key}=#{value.inspect}" } .join(" ") "#<#{self.class} #{attrs}>" end def pretty_print(pp) pp.object_group(self) do to_h.each do |attr, value| pp.breakable pp.text("#{attr}=") pp.pp(value) end end end def deconstruct_keys(_) to_h end end end
ruby
MIT
209069ad7b3ad42f3bdbc9c4ed556dac21693f3d
2026-01-04T17:46:31.511345Z
false
tomdalling/value_semantics
https://github.com/tomdalling/value_semantics/blob/209069ad7b3ad42f3bdbc9c4ed556dac21693f3d/lib/value_semantics/hash_coercer.rb
lib/value_semantics/hash_coercer.rb
module ValueSemantics class HashCoercer attr_reader :key_coercer, :value_coercer def initialize(key_coercer:, value_coercer:) @key_coercer, @value_coercer = key_coercer, value_coercer freeze end def call(obj) hash = coerce_to_hash(obj) return obj unless hash {}.tap do |result| hash.each do |key, value| r_key = key_coercer.(key) r_value = value_coercer.(value) result[r_key] = r_value end end end private def coerce_to_hash(obj) return nil unless obj.respond_to?(:to_h) obj.to_h end end end
ruby
MIT
209069ad7b3ad42f3bdbc9c4ed556dac21693f3d
2026-01-04T17:46:31.511345Z
false
tomdalling/value_semantics
https://github.com/tomdalling/value_semantics/blob/209069ad7b3ad42f3bdbc9c4ed556dac21693f3d/lib/value_semantics/array_of.rb
lib/value_semantics/array_of.rb
module ValueSemantics # # Validator that matches arrays if each element matches a given subvalidator # class ArrayOf attr_reader :element_validator def initialize(element_validator) @element_validator = element_validator freeze end # @return [Boolean] def ===(value) Array === value && value.all? { |element| element_validator === element } end end end
ruby
MIT
209069ad7b3ad42f3bdbc9c4ed556dac21693f3d
2026-01-04T17:46:31.511345Z
false
tomdalling/value_semantics
https://github.com/tomdalling/value_semantics/blob/209069ad7b3ad42f3bdbc9c4ed556dac21693f3d/lib/value_semantics/anything.rb
lib/value_semantics/anything.rb
module ValueSemantics # # Validator that matches any and all values # module Anything # @return [true] def self.===(_) true end end end
ruby
MIT
209069ad7b3ad42f3bdbc9c4ed556dac21693f3d
2026-01-04T17:46:31.511345Z
false
tomdalling/value_semantics
https://github.com/tomdalling/value_semantics/blob/209069ad7b3ad42f3bdbc9c4ed556dac21693f3d/lib/value_semantics/array_coercer.rb
lib/value_semantics/array_coercer.rb
module ValueSemantics class ArrayCoercer attr_reader :element_coercer def initialize(element_coercer = nil) @element_coercer = element_coercer freeze end def call(obj) if obj.respond_to?(:to_a) array = obj.to_a if element_coercer array.map { |element| element_coercer.call(element) } else array end else obj end end end end
ruby
MIT
209069ad7b3ad42f3bdbc9c4ed556dac21693f3d
2026-01-04T17:46:31.511345Z
false
tomdalling/value_semantics
https://github.com/tomdalling/value_semantics/blob/209069ad7b3ad42f3bdbc9c4ed556dac21693f3d/lib/value_semantics/value_object_coercer.rb
lib/value_semantics/value_object_coercer.rb
module ValueSemantics # # A coercer for converting hashes into instances of value classes # # The coercer will coerce hash-like values into an instance of the value # class, using the hash for attribute values. It will return non-hash-like # values unchanged. It will also return hash-like values unchanged if they do # not contain all required attributes of the value class. # class ValueObjectCoercer attr_reader :value_class def initialize(value_class) @value_class = value_class end def call(obj) attrs = coerce_to_attr_hash(obj) if attrs value_class.new(attrs) else obj end end private NOT_FOUND = Object.new.freeze def coerce_to_attr_hash(obj) # TODO: this coerces nil to an empty hash, which is probably not ideal. # It should not coerce nil so that Either(X, nil) validator works as # expected. This is a backwards-incomptible change, so save it for a # major version bump return nil unless obj.respond_to?(:to_h) obj_hash = obj.to_h {}.tap do |attrs| value_class.value_semantics.attributes.each do |attr_def| name = attr_def.name value = obj_hash.fetch(name) do obj_hash.fetch(name.to_s, NOT_FOUND) end attrs[name] = value unless value.equal?(NOT_FOUND) end end end end end
ruby
MIT
209069ad7b3ad42f3bdbc9c4ed556dac21693f3d
2026-01-04T17:46:31.511345Z
false
testdouble/maybe_later
https://github.com/testdouble/maybe_later/blob/6fb75606869cbc278811c131dca49e3e66cf6662/test/test_helper.rb
test/test_helper.rb
$LOAD_PATH.unshift File.expand_path("../lib", __dir__) require "maybe_later" require "minitest/autorun"
ruby
MIT
6fb75606869cbc278811c131dca49e3e66cf6662
2026-01-04T17:46:35.630042Z
false
testdouble/maybe_later
https://github.com/testdouble/maybe_later/blob/6fb75606869cbc278811c131dca49e3e66cf6662/test/maybe_later_test.rb
test/maybe_later_test.rb
require "test_helper" require "rack" class MaybeLaterTest < Minitest::Test i_suck_and_my_tests_are_order_dependent! def setup MaybeLater.config do |config| config.after_each = nil config.on_error = nil config.inline_by_default = false config.max_threads = 5 config.invoke_even_if_server_is_unsupported = false end end def test_that_it_has_a_version_number refute_nil ::MaybeLater::VERSION end def test_a_couple_callbacks chores = [] call_count = 0 errors_encountered = [] MaybeLater.config do |config| config.after_each = -> { call_count += 1 } config.on_error = ->(e) { errors_encountered << e } end MaybeLater.run { chores << :laundry } callback_that_will_error = -> { raise "a stink" } MaybeLater.run(&callback_that_will_error) MaybeLater.run { chores << :tidy } _, headers, _ = invoke_middleware! assert_equal 0, call_count # <-- nothing could have happened yet! sleep 0.01 # <- let threads do stuff assert_includes chores, :laundry assert_includes chores, :tidy assert_equal 3, call_count assert_equal 1, errors_encountered.size error = errors_encountered.first assert_equal "a stink", error.message assert_nil headers["Connection"] # No inline runs end def test_inline_runs called = false MaybeLater.run(inline: true) { called = true } _, headers, _ = invoke_middleware! assert called assert_equal "close", headers["Connection"] end def test_inline_by_default MaybeLater.config.inline_by_default = true called = false MaybeLater.run { called = true } invoke_middleware! assert called end def test_inline_by_default_still_allows_async MaybeLater.config.inline_by_default = true called = false MaybeLater.run(inline: false) { called = true } invoke_middleware! refute called # unpossible if async! end def test_only_callsback_once call_count = 0 MaybeLater.run { call_count += 1 } invoke_middleware! invoke_middleware! invoke_middleware! invoke_middleware! sleep 0.01 # <- let threads do stuff assert_equal 1, call_count end def test_that_a_callable_is_required e = assert_raises { MaybeLater.run } assert_kind_of MaybeLater::Error, e assert_equal "No block was passed to MaybeLater.run", e.message end def test_with_server_that_doesnt_support_rack_after_reply called = false MaybeLater.run(inline: true) { called = true } stderr = with_fake_stderr do invoke_middleware!(supports_after_reply: false) end refute called assert_equal <<~ERR, stderr.read This server may not support 'rack.after_reply' callbacks. To ensure that your tasks are executed, consider enabling: config.invoke_even_if_server_is_unsupported = true Note that this option, when combined with `inline: true` can result in delayed flushing of HTTP responses by the server (defeating the purpose of the gem. ERR end def test_unsupported_server_that_calls_anyway MaybeLater.config do |config| config.invoke_even_if_server_is_unsupported = true end called = false MaybeLater.run(inline: true) { called = true } invoke_middleware!(supports_after_reply: false) assert called end private def invoke_middleware!(supports_after_reply: true) env = Rack::MockRequest.env_for if supports_after_reply env[MaybeLater::Middleware::RACK_AFTER_REPLY] ||= [] end subject = MaybeLater::Middleware.new(->(env) { [200, {}, "success"] }) result = subject.call(env) # The server will do this env[MaybeLater::Middleware::RACK_AFTER_REPLY]&.first&.call result end def with_fake_stderr(&blk) og_stderr = $stderr fake_stderr = StringIO.new $stderr = fake_stderr blk.call $stderr = og_stderr fake_stderr.rewind fake_stderr end end
ruby
MIT
6fb75606869cbc278811c131dca49e3e66cf6662
2026-01-04T17:46:35.630042Z
false
testdouble/maybe_later
https://github.com/testdouble/maybe_later/blob/6fb75606869cbc278811c131dca49e3e66cf6662/lib/maybe_later.rb
lib/maybe_later.rb
require_relative "maybe_later/version" require_relative "maybe_later/config" require_relative "maybe_later/middleware" require_relative "maybe_later/queues_callback" require_relative "maybe_later/runs_callbacks" require_relative "maybe_later/invokes_callback" require_relative "maybe_later/store" require_relative "maybe_later/thread_pool" require_relative "maybe_later/railtie" if defined?(Rails) module MaybeLater class Error < StandardError; end def self.run(inline: nil, &blk) QueuesCallback.new.call(callable: blk, inline: inline) end def self.config(&blk) (@config ||= Config.new).tap { |config| blk&.call(config) } end end
ruby
MIT
6fb75606869cbc278811c131dca49e3e66cf6662
2026-01-04T17:46:35.630042Z
false
testdouble/maybe_later
https://github.com/testdouble/maybe_later/blob/6fb75606869cbc278811c131dca49e3e66cf6662/lib/maybe_later/version.rb
lib/maybe_later/version.rb
module MaybeLater VERSION = "0.0.4" end
ruby
MIT
6fb75606869cbc278811c131dca49e3e66cf6662
2026-01-04T17:46:35.630042Z
false
testdouble/maybe_later
https://github.com/testdouble/maybe_later/blob/6fb75606869cbc278811c131dca49e3e66cf6662/lib/maybe_later/queues_callback.rb
lib/maybe_later/queues_callback.rb
module MaybeLater Callback = Struct.new(:inline, :callable, keyword_init: true) class QueuesCallback def call(callable:, inline:) raise Error.new("No block was passed to MaybeLater.run") if callable.nil? inline = MaybeLater.config.inline_by_default if inline.nil? Store.instance.add_callback(Callback.new( inline: inline, callable: callable )) end end end
ruby
MIT
6fb75606869cbc278811c131dca49e3e66cf6662
2026-01-04T17:46:35.630042Z
false
testdouble/maybe_later
https://github.com/testdouble/maybe_later/blob/6fb75606869cbc278811c131dca49e3e66cf6662/lib/maybe_later/middleware.rb
lib/maybe_later/middleware.rb
module MaybeLater class Middleware RACK_AFTER_REPLY = "rack.after_reply" def initialize(app) @app = app end def call(env) config = MaybeLater.config status, headers, body = @app.call(env) if Store.instance.callbacks.any? if env.key?(RACK_AFTER_REPLY) env[RACK_AFTER_REPLY] << -> { RunsCallbacks.new.call } elsif !config.invoke_even_if_server_is_unsupported warn <<~MSG This server may not support '#{RACK_AFTER_REPLY}' callbacks. To ensure that your tasks are executed, consider enabling: config.invoke_even_if_server_is_unsupported = true Note that this option, when combined with `inline: true` can result in delayed flushing of HTTP responses by the server (defeating the purpose of the gem. MSG else RunsCallbacks.new.call end if Store.instance.callbacks.any? { |cb| cb.inline } headers["Connection"] = "close" end end [status, headers, body] end end end
ruby
MIT
6fb75606869cbc278811c131dca49e3e66cf6662
2026-01-04T17:46:35.630042Z
false
testdouble/maybe_later
https://github.com/testdouble/maybe_later/blob/6fb75606869cbc278811c131dca49e3e66cf6662/lib/maybe_later/store.rb
lib/maybe_later/store.rb
module MaybeLater class Store def self.instance Thread.current[:maybe_later_store] ||= new end attr_reader :callbacks def initialize @callbacks = [] end def add_callback(callable) @callbacks << callable end def clear_callbacks! @callbacks = [] end end end
ruby
MIT
6fb75606869cbc278811c131dca49e3e66cf6662
2026-01-04T17:46:35.630042Z
false
testdouble/maybe_later
https://github.com/testdouble/maybe_later/blob/6fb75606869cbc278811c131dca49e3e66cf6662/lib/maybe_later/railtie.rb
lib/maybe_later/railtie.rb
module MaybeLater class Railtie < ::Rails::Railtie initializer "maybe_later.middleware" do config.app_middleware.use Middleware end end end
ruby
MIT
6fb75606869cbc278811c131dca49e3e66cf6662
2026-01-04T17:46:35.630042Z
false
testdouble/maybe_later
https://github.com/testdouble/maybe_later/blob/6fb75606869cbc278811c131dca49e3e66cf6662/lib/maybe_later/runs_callbacks.rb
lib/maybe_later/runs_callbacks.rb
module MaybeLater class RunsCallbacks def initialize @invokes_callback = InvokesCallback.new end def call store = Store.instance store.callbacks.each do |callback| if callback.inline @invokes_callback.call(callback) else ThreadPool.instance.run(callback) end end store.clear_callbacks! end end end
ruby
MIT
6fb75606869cbc278811c131dca49e3e66cf6662
2026-01-04T17:46:35.630042Z
false
testdouble/maybe_later
https://github.com/testdouble/maybe_later/blob/6fb75606869cbc278811c131dca49e3e66cf6662/lib/maybe_later/invokes_callback.rb
lib/maybe_later/invokes_callback.rb
module MaybeLater class InvokesCallback def call(callback) config = MaybeLater.config callback.callable.call rescue => e config.on_error&.call(e) ensure config.after_each&.call end end end
ruby
MIT
6fb75606869cbc278811c131dca49e3e66cf6662
2026-01-04T17:46:35.630042Z
false
testdouble/maybe_later
https://github.com/testdouble/maybe_later/blob/6fb75606869cbc278811c131dca49e3e66cf6662/lib/maybe_later/thread_pool.rb
lib/maybe_later/thread_pool.rb
module MaybeLater class ThreadPool def self.instance @instance ||= new end # The only time this is invoked by the gem will be when an Async task runs # As a result, the max thread config will be locked after responding to the # first relevant request, since the pool will have been created def initialize @pool = Concurrent::FixedThreadPool.new(MaybeLater.config.max_threads) @invokes_callback = InvokesCallback.new end def run(callback) @pool.post do @invokes_callback.call(callback) end end end end
ruby
MIT
6fb75606869cbc278811c131dca49e3e66cf6662
2026-01-04T17:46:35.630042Z
false
testdouble/maybe_later
https://github.com/testdouble/maybe_later/blob/6fb75606869cbc278811c131dca49e3e66cf6662/lib/maybe_later/config.rb
lib/maybe_later/config.rb
module MaybeLater class Config attr_accessor :after_each, :on_error, :inline_by_default, :max_threads, :invoke_even_if_server_is_unsupported def initialize @after_each = nil @on_error = nil @inline_by_default = false @max_threads = 5 @invoke_even_if_server_is_unsupported = false end end end
ruby
MIT
6fb75606869cbc278811c131dca49e3e66cf6662
2026-01-04T17:46:35.630042Z
false
jeremy/rack-ratelimit
https://github.com/jeremy/rack-ratelimit/blob/2fd0b190950e559c2b1d7032a71c16c294d686ac/test/ratelimit_test.rb
test/ratelimit_test.rb
require 'rubygems' require 'bundler/setup' require 'minitest/autorun' require 'rack/ratelimit' require 'stringio' require 'json' require 'dalli' require 'redis' module RatelimitTests def setup @app = ->(env) { [200, {}, []] } @logger = Logger.new(@out = StringIO.new) @limited = build_ratelimiter(@app, name: :one, rate: [1, 10]) @two_limits = build_ratelimiter(@limited, name: :two, rate: [1, 10]) end def test_name_defaults_to_HTTP app = build_ratelimiter(@app) assert_match '"name":"HTTP"', app.call({})[1]['X-Ratelimit'] end def test_sets_informative_header_when_rate_limit_isnt_exceeded status, headers, body = @limited.call({}) assert_equal 200, status assert_match %r({"name":"one","period":10,"limit":1,"remaining":0,"until":".*"}), headers['X-Ratelimit'] assert_equal [], body assert_equal '', @out.string end def test_decrements_rate_limit_header_remaining_count app = build_ratelimiter(@app, rate: [3, 10]) remainings = 5.times.map { JSON.parse(app.call({})[1]['X-Ratelimit'])['remaining'] } assert_equal [2,1,0,0,0], remainings end def test_sets_multiple_informative_headers_for_each_rate_limiter status, headers, body = @two_limits.call({}) assert_equal 200, status info = headers['X-Ratelimit'].split("\n") assert_equal 2, info.size assert_match %r({"name":"one","period":10,"limit":1,"remaining":0,"until":".*"}), info.first assert_match %r({"name":"two","period":10,"limit":1,"remaining":0,"until":".*"}), info.last assert_equal [], body assert_equal '', @out.string end def test_responds_with_429_if_request_rate_exceeds_limit timestamp = Time.now.to_f epoch = 10 * (timestamp / 10).ceil retry_after = (epoch - timestamp).ceil assert_equal 200, @limited.call('limit-by' => 'key', 'ratelimit.timestamp' => timestamp).first status, headers, body = @limited.call('limit-by' => 'key', 'ratelimit.timestamp' => timestamp) assert_equal 429, status assert_equal retry_after.to_s, headers['Retry-After'] assert_match '0', headers['X-Ratelimit'] assert_match %r({"name":"one","period":10,"limit":1,"remaining":0,"until":".*"}), headers['X-Ratelimit'] assert_equal "one rate limit exceeded. Please wait #{retry_after} seconds then retry your request.", body.first assert_match %r{one: classification exceeded 1 request limit for}, @out.string end def test_optional_response_status app = build_ratelimiter(@app, status: 503) assert_equal 200, app.call('limit-by' => 'key').first assert_equal 503, app.call('limit-by' => 'key').first end def test_doesnt_log_on_subsequent_rate_limited_requests assert_equal 200, @limited.call('limit-by' => 'key').first assert_equal 429, @limited.call('limit-by' => 'key').first out = @out.string.dup assert_equal 429, @limited.call('limit-by' => 'key').first assert_equal out, @out.string end def test_classifier_is_optional app = build_ratelimiter(@app, no_classifier: true) assert_rate_limited app.call({}) end def test_classify_may_be_overridden app = build_ratelimiter(@app, no_classifier: true) def app.classify(env) env['limit-by'] end assert_equal 200, app.call('limit-by' => 'a').first assert_equal 200, app.call('limit-by' => 'b').first end def test_conditions_and_exceptions @limited.condition { |env| env['c1'] } @limited.condition { |env| env['c2'] } @limited.exception { |env| env['e1'] } @limited.exception { |env| env['e2'] } # Any exceptions exclude the request from rate limiting. assert_not_rate_limited @limited.call({ 'c1' => true, 'c2' => true, 'e1' => true }) assert_not_rate_limited @limited.call({ 'c1' => true, 'c2' => true, 'e2' => true }) # All conditions must be met to rate-limit the request. assert_not_rate_limited @limited.call({ 'c1' => true }) assert_not_rate_limited @limited.call({ 'c2' => true }) # If all conditions are met with no exceptions, rate limit. assert_rate_limited @limited.call({ 'c1' => true, 'c2' => true }) end def test_conditions_and_exceptions_as_config_options app = build_ratelimiter(@app, conditions: ->(env) { env['c1'] }) assert_rate_limited app.call('c1' => true) assert_not_rate_limited app.call('c1' => false) end def test_skip_rate_limiting_when_classifier_returns_nil app = build_ratelimiter(@app) { |env| env['c'] } assert_rate_limited app.call('c' => '1') assert_not_rate_limited app.call('c' => nil) end private def assert_not_rate_limited(response) assert_nil response[1]['X-Ratelimit'] end def assert_rate_limited(response) assert !response[1]['X-Ratelimit'].nil? end def build_ratelimiter(app, options = {}, &block) block ||= -> env { 'classification' } unless options.delete(:no_classifier) Rack::Ratelimit.new(app, ratelimit_options.merge(options), &block) end def ratelimit_options { rate: [1,10], logger: @logger } end end module RatelimitBackendExceptionTests def test_skip_tracking_on_backend_errors app = Rack::Ratelimit.new \ ->(env) { [200, {}, []] }, ratelimit_options.merge(rate: [1, 10], logger: Logger.new(StringIO.new)) stubbing_backend_error do remainings = 5.times.map { JSON.parse(app.call({})[1]['X-Ratelimit'])['remaining'] } assert_equal [1,1,1,1,1], remainings end end end class RequiredBackendTest < Minitest::Test def test_backend_is_required assert_raises ArgumentError do Rack::Ratelimit.new(nil, rate: [1,10]) end end end class MemcachedRatelimitTest < Minitest::Test include RatelimitTests, RatelimitBackendExceptionTests def setup @cache = Dalli::Client.new('localhost:11211').tap(&:flush) super end def teardown super @cache.close end private def ratelimit_options super.merge cache: @cache end def stubbing_backend_error @cache.stub :incr, ->(key, value) { raise Dalli::DalliError } do yield end end end class RedisRatelimitTest < Minitest::Test include RatelimitTests, RatelimitBackendExceptionTests def setup @redis = Redis.new(:host => 'localhost', :port => 6379, :db => 0).tap(&:flushdb) super end def teardown super @redis.quit end private def stubbing_backend_error @redis.stub :multi, -> { raise Redis::BaseError } do yield end end def ratelimit_options super.merge redis: @redis end end class CustomCounterRatelimitTest < Minitest::Test include RatelimitTests private def ratelimit_options super.merge counter: Counter.new end class Counter def initialize @counters = Hash.new do |classifications, name| classifications[name] = Hash.new do |timeslices, timestamp| timeslices[timestamp] = 0 end end end def increment(classification, timestamp) @counters[classification][timestamp] += 1 end end end
ruby
MIT
2fd0b190950e559c2b1d7032a71c16c294d686ac
2026-01-04T17:46:30.973090Z
false
jeremy/rack-ratelimit
https://github.com/jeremy/rack-ratelimit/blob/2fd0b190950e559c2b1d7032a71c16c294d686ac/lib/rack-ratelimit.rb
lib/rack-ratelimit.rb
require 'rack/ratelimit'
ruby
MIT
2fd0b190950e559c2b1d7032a71c16c294d686ac
2026-01-04T17:46:30.973090Z
false
jeremy/rack-ratelimit
https://github.com/jeremy/rack-ratelimit/blob/2fd0b190950e559c2b1d7032a71c16c294d686ac/lib/rack/ratelimit.rb
lib/rack/ratelimit.rb
require 'logger' require 'time' module Rack # = Ratelimit # # * Run multiple rate limiters in a single app # * Scope each rate limit to certain requests: API, files, GET vs POST, etc. # * Apply each rate limit by request characteristics: IP, subdomain, OAuth2 token, etc. # * Flexible time window to limit burst traffic vs hourly or daily traffic: # 100 requests per 10 sec, 500 req/minute, 10000 req/hour, etc. # * Fast, low-overhead implementation using counters per time window: # timeslice = window * ceiling(current time / window) # store.incr(timeslice) class Ratelimit # Takes a block that classifies requests for rate limiting. Given a # Rack env, return a string such as IP address, API token, etc. If the # block returns nil, the request won't be rate-limited. If a block is # not given, all requests get the same limits. # # Required configuration: # rate: an array of [max requests, period in seconds]: [500, 5.minutes] # and one of # cache: a Dalli::Client instance # redis: a Redis instance # counter: Your own custom counter. Must respond to # `#increment(classification_string, end_of_time_window_epoch_timestamp)` # and return the counter value after increment. # # Optional configuration: # name: name of the rate limiter. Defaults to 'HTTP'. Used in messages. # status: HTTP response code. Defaults to 429. # conditions: array of procs that take a rack env, all of which must # return true to rate-limit the request. # exceptions: array of procs that take a rack env, any of which may # return true to exclude the request from rate limiting. # logger: responds to #info(message). If provided, the rate limiter # logs the first request that hits the rate limit, but none of the # subsequently blocked requests. # error_message: the message returned in the response body when the rate # limit is exceeded. Defaults to "<name> rate limit exceeded. Please # wait %d seconds then retry your request." The number of seconds # until the end of the rate-limiting window is interpolated into the # message string, but the %d placeholder is optional if you wish to # omit it. # # Example: # # Rate-limit bursts of POST/PUT/DELETE by IP address, return 503: # use(Rack::Ratelimit, name: 'POST', # exceptions: ->(env) { env['REQUEST_METHOD'] == 'GET' }, # rate: [50, 10.seconds], # status: 503, # cache: Dalli::Client.new, # logger: Rails.logger) { |env| Rack::Request.new(env).ip } # # Rate-limit API traffic by user (set by Rack::Auth::Basic): # use(Rack::Ratelimit, name: 'API', # conditions: ->(env) { env['REMOTE_USER'] }, # rate: [1000, 1.hour], # redis: Redis.new(ratelimit_redis_config), # logger: Rails.logger) { |env| env['REMOTE_USER'] } def initialize(app, options, &classifier) @app, @classifier = app, classifier @classifier ||= lambda { |env| :request } @name = options.fetch(:name, 'HTTP') @max, @period = options.fetch(:rate) @status = options.fetch(:status, 429) @counter = if counter = options[:counter] raise ArgumentError, 'Counter must respond to #increment' unless counter.respond_to?(:increment) counter elsif cache = options[:cache] MemcachedCounter.new(cache, @name, @period) elsif redis = options[:redis] RedisCounter.new(redis, @name, @period) else raise ArgumentError, ':cache, :redis, or :counter is required' end @logger = options[:logger] @error_message = options.fetch(:error_message, "#{@name} rate limit exceeded. Please wait %d seconds then retry your request.") @conditions = Array(options[:conditions]) @exceptions = Array(options[:exceptions]) end # Add a condition that must be met before applying the rate limit. # Pass a block or a proc argument that takes a Rack env and returns # true if the request should be limited. def condition(predicate = nil, &block) @conditions << predicate if predicate @conditions << block if block_given? end # Add an exception that excludes requests from the rate limit. # Pass a block or a proc argument that takes a Rack env and returns # true if the request should be excluded from rate limiting. def exception(predicate = nil, &block) @exceptions << predicate if predicate @exceptions << block if block_given? end # Apply the rate limiter if none of the exceptions apply and all the # conditions are met. def apply_rate_limit?(env) @exceptions.none? { |e| e.call(env) } && @conditions.all? { |c| c.call(env) } end # Give subclasses an opportunity to specialize classification. def classify(env) @classifier.call env end # Handle a Rack request: # * Check whether the rate limit applies to the request. # * Classify the request by IP, API token, etc. # * Calculate the end of the current time window. # * Increment the counter for this classification and time window. # * If count exceeds limit, return a 429 response. # * If it's the first request that exceeds the limit, log it. # * If the count doesn't exceed the limit, pass through the request. def call(env) # Accept an optional start-of-request timestamp from the Rack env for # upstream timing and for testing. now = env.fetch('ratelimit.timestamp', Time.now).to_f if apply_rate_limit?(env) && classification = classify(env) # Increment the request counter. epoch = ratelimit_epoch(now) count = @counter.increment(classification, epoch) remaining = @max - count # If exceeded, return a 429 Rate Limit Exceeded response. if remaining < 0 # Only log the first hit that exceeds the limit. if @logger && remaining == -1 @logger.info '%s: %s exceeded %d request limit for %s' % [@name, classification, @max, format_epoch(epoch)] end retry_after = seconds_until_epoch(epoch) [ @status, { 'X-Ratelimit' => ratelimit_json(remaining, epoch), 'Retry-After' => retry_after.to_s }, [ @error_message % retry_after ] ] # Otherwise, pass through then add some informational headers. else @app.call(env).tap do |status, headers, body| amend_headers headers, 'X-Ratelimit', ratelimit_json(remaining, epoch) end end else @app.call(env) end end private # Calculate the end of the current rate-limiting window. def ratelimit_epoch(timestamp) @period * (timestamp / @period).ceil end def ratelimit_json(remaining, epoch) %({"name":"#{@name}","period":#{@period},"limit":#{@max},"remaining":#{remaining < 0 ? 0 : remaining},"until":"#{format_epoch(epoch)}"}) end def format_epoch(epoch) Time.at(epoch).utc.xmlschema end # Clamp negative durations in case we're in a new rate-limiting window. def seconds_until_epoch(epoch) sec = (epoch - Time.now.to_f).ceil sec = 0 if sec < 0 sec end def amend_headers(headers, name, value) headers[name] = [headers[name], value].compact.join("\n") end class MemcachedCounter def initialize(cache, name, period) @cache, @name, @period = cache, name, period end # Increment the request counter and return the current count. def increment(classification, epoch) key = 'rack-ratelimit/%s/%s/%i' % [@name, classification, epoch] # Try to increment the counter if it's present. if count = @cache.incr(key, 1) count.to_i # If not, add the counter and set expiry. elsif @cache.add(key, 1, @period, :raw => true) 1 # If adding failed, someone else added it concurrently. Increment. else @cache.incr(key, 1).to_i end rescue Dalli::DalliError 0 end end class RedisCounter def initialize(redis, name, period) @redis, @name, @period = redis, name, period end # Increment the request counter and return the current count. def increment(classification, epoch) key = 'rack-ratelimit/%s/%s/%i' % [@name, classification, epoch] # Returns [count, expire_ok] response for each multi command. # Return the first, the count. @redis.multi do |redis| redis.incr key redis.expire key, @period end.first rescue Redis::BaseError 0 end end end end
ruby
MIT
2fd0b190950e559c2b1d7032a71c16c294d686ac
2026-01-04T17:46:30.973090Z
false
aasmith/feed-normalizer
https://github.com/aasmith/feed-normalizer/blob/afa7765c08481d38729a71bd5dfd5ef95736f026/test/test_feednormalizer.rb
test/test_feednormalizer.rb
$LOAD_PATH.unshift(File.expand_path(File.join(File.dirname(__FILE__), '../lib'))) require 'test/unit' require 'feed-normalizer' require 'yaml' class FeedNormalizerTest < Test::Unit::TestCase XML_FILES = {} Fn = FeedNormalizer data_dir = File.dirname(__FILE__) + '/data' # Load up the xml files Dir.open(data_dir).each do |fn| next unless fn =~ /[.]xml$/ XML_FILES[File.basename(fn, File.extname(fn)).to_sym] = File.read(data_dir + "/#{fn}") end def test_basic_parse assert_kind_of Fn::Feed, FeedNormalizer::FeedNormalizer.parse(XML_FILES[:rss20]) end def test_force_parser assert_kind_of Fn::Feed, FeedNormalizer::FeedNormalizer.parse(XML_FILES[:rss20], :force_parser => Fn::RubyRssParser, :try_others => true) end def test_force_parser_exclusive assert_kind_of Fn::Feed, FeedNormalizer::FeedNormalizer.parse(XML_FILES[:rss20], :force_parser => Fn::RubyRssParser, :try_others => false) end def test_ruby_rss_parser assert_kind_of Fn::Feed, FeedNormalizer::FeedNormalizer.parse(XML_FILES[:rss20], :force_parser => Fn::RubyRssParser, :try_others => false) assert_kind_of Fn::Feed, FeedNormalizer::FeedNormalizer.parse(XML_FILES[:rdf10], :force_parser => Fn::RubyRssParser, :try_others => false) end def test_simple_rss_parser assert_kind_of Fn::Feed, FeedNormalizer::FeedNormalizer.parse(XML_FILES[:rss20], :force_parser => Fn::SimpleRssParser, :try_others => false) assert_kind_of Fn::Feed, FeedNormalizer::FeedNormalizer.parse(XML_FILES[:atom10], :force_parser => Fn::SimpleRssParser, :try_others => false) end def test_parser_failover_order assert_equal 'SimpleRSS', FeedNormalizer::FeedNormalizer.parse(XML_FILES[:atom10], :force_parser => Fn::RubyRssParser).parser end def test_force_parser_fail assert_nil FeedNormalizer::FeedNormalizer.parse(XML_FILES[:atom10], :force_parser => Fn::RubyRssParser, :try_others => false) end def test_all_parsers_fail assert_nil FeedNormalizer::FeedNormalizer.parse("This isn't RSS or Atom!") end def test_correct_parser_used assert_equal 'RSS::Parser', FeedNormalizer::FeedNormalizer.parse(XML_FILES[:rss20]).parser assert_equal 'SimpleRSS', FeedNormalizer::FeedNormalizer.parse(XML_FILES[:atom10]).parser end def test_rss feed = FeedNormalizer::FeedNormalizer.parse(XML_FILES[:rss20]) assert_equal "BBC News | Technology | UK Edition", feed.title assert_equal ["http://news.bbc.co.uk/go/rss/-/1/hi/technology/default.stm"], feed.urls assert_equal 15, feed.ttl assert_equal [6, 7, 8, 9, 10, 11], feed.skip_hours assert_equal ["Sunday"], feed.skip_days assert_equal "MP3 player court order overturned", feed.entries.last.title assert_equal "<b>SanDisk</b> puts its MP3 players back on display at a German electronics show after overturning a court injunction.", feed.entries.last.description assert_match(/test\d/, feed.entries.last.content) assert_instance_of Time, feed.entries.last.date_published end def test_simplerss feed = FeedNormalizer::FeedNormalizer.parse(XML_FILES[:atom10]) assert_equal "~:caboose", feed.title assert_equal "http://habtm.com/xml/atom10/feed.xml", feed.url assert_equal nil, feed.ttl assert_equal [], feed.skip_hours assert_equal [], feed.skip_days assert_equal "Starfish - Easy Distribution of Site Maintenance", feed.entries.last.title assert_equal "urn:uuid:6c028f36-f87a-4f53-b7e3-1f943d2341f0", feed.entries.last.id assert !feed.entries.last.description.include?("google fame") assert feed.entries.last.content.include?("google fame") end def test_sanity_check XML_FILES.keys.each do |xml_file| feed = FeedNormalizer::FeedNormalizer.parse(XML_FILES[xml_file]) assert [feed.parser, feed.title, feed.url, feed.entries.first.url].collect{|e| e.is_a?(String)}.all?, "Not everything was a String in #{xml_file}" end end def test_feed_equality assert_equal FeedNormalizer::FeedNormalizer.parse(XML_FILES[:rss20]), FeedNormalizer::FeedNormalizer.parse(XML_FILES[:rss20]) assert_equal FeedNormalizer::FeedNormalizer.parse(XML_FILES[:atom10]), FeedNormalizer::FeedNormalizer.parse(XML_FILES[:atom10]) assert_not_equal FeedNormalizer::FeedNormalizer.parse(XML_FILES[:atom03]), FeedNormalizer::FeedNormalizer.parse(XML_FILES[:atom10]) assert_not_equal FeedNormalizer::FeedNormalizer.parse(XML_FILES[:rss20]), FeedNormalizer::FeedNormalizer.parse(XML_FILES[:atom10]) assert_not_equal FeedNormalizer::FeedNormalizer.parse(XML_FILES[:rss20]), FeedNormalizer::FeedNormalizer.parse(XML_FILES[:rss20diff]) end def test_feed_diff feed = FeedNormalizer::FeedNormalizer.parse(XML_FILES[:rss20]) diff = feed.diff(FeedNormalizer::FeedNormalizer.parse(XML_FILES[:rss20diff])) diff_short = feed.diff(FeedNormalizer::FeedNormalizer.parse(XML_FILES[:rss20diff_short])) no_diff = feed.diff(feed) assert diff.keys.all? {|key| [:title, :items].include?(key)} assert_equal 3, diff[:items].size assert diff_short.keys.all? {|key| [:title, :items].include?(key)} assert_equal [3,2], diff_short[:items] assert no_diff.empty? end def test_marshal feed = FeedNormalizer::FeedNormalizer.parse(XML_FILES[:rss20]) assert_nothing_raised { Marshal.load(Marshal.dump(feed)) } end def test_yaml feed = FeedNormalizer::FeedNormalizer.parse(XML_FILES[:rss20]) assert_nothing_raised { YAML.load(YAML.dump(feed)) } end def test_method_missing assert_raise(NoMethodError) { FeedNormalizer::FeedNormalizer.parse(XML_FILES[:rss20]).nonexistent } # Another test of Singular's method_missing: sending :flatten to a 2-D array of FeedNormalizer::Entrys # causes :to_ary to be sent to the Entrys. assert_nothing_raised { [[Fn::Entry.new], [Fn::Entry.new]].flatten } end def test_clean feed = FeedNormalizer::FeedNormalizer.parse(XML_FILES[:atom10]) assert_match(/<plaintext>/, feed.entries.first.content) assert_match(/<plaintext>/, feed.entries.first.description) feed.clean! assert_no_match(/<plaintext>/, feed.entries.first.content) assert_no_match(/<plaintext>/, feed.entries.first.description) end def test_malformed_feed assert_nothing_raised { FeedNormalizer::FeedNormalizer.parse('<feed></feed>') } end def test_dublin_core_date_ruby_rss feed = FeedNormalizer::FeedNormalizer.parse(XML_FILES[:rdf10], :force_parser => Fn::RubyRssParser, :try_others => false) assert_instance_of Time, feed.entries.first.date_published end def test_dublin_core_date_simple_rss feed = FeedNormalizer::FeedNormalizer.parse(XML_FILES[:rdf10], :force_parser => Fn::SimpleRssParser, :try_others => false) assert_instance_of Time, feed.entries.first.date_published end def test_dublin_core_creator_ruby_rss feed = FeedNormalizer::FeedNormalizer.parse(XML_FILES[:rdf10], :force_parser => Fn::RubyRssParser, :try_others => false) assert_equal 'Jeff Hecht', feed.entries.last.author end def test_dublin_core_creator_simple_rss feed = FeedNormalizer::FeedNormalizer.parse(XML_FILES[:rdf10], :force_parser => Fn::SimpleRssParser, :try_others => false) assert_equal 'Jeff Hecht', feed.entries.last.author end def test_entry_categories_ruby_rss feed = FeedNormalizer::FeedNormalizer.parse(XML_FILES[:rss20], :force_parser => Fn::RubyRssParser, :try_others => false) assert_equal [['Click'],['Technology'],[]], feed.items.collect {|i|i.categories} end def test_entry_categories_simple_rss feed = FeedNormalizer::FeedNormalizer.parse(XML_FILES[:rss20], :force_parser => Fn::SimpleRssParser, :try_others => false) assert_equal [['Click'],['Technology'],[]], feed.items.collect {|i|i.categories} end def test_loose_categories_ruby_rss feed = FeedNormalizer::FeedNormalizer.parse(XML_FILES[:rss20], :force_parser => Fn::RubyRssParser, :try_others => false, :loose => true) assert_equal [1,2,0], feed.entries.collect{|e|e.categories.size} end def test_loose_categories_simple_rss feed = FeedNormalizer::FeedNormalizer.parse(XML_FILES[:rss20], :force_parser => Fn::SimpleRssParser, :try_others => false, :loose => true) assert_equal [1,1,0], feed.entries.collect{|e|e.categories.size} end def test_content_encoded_simple_rss feed = FeedNormalizer::FeedNormalizer.parse(XML_FILES[:rss20], :force_parser => Fn::SimpleRssParser, :try_others => false) feed.entries.each_with_index do |e, i| assert_match(/\s*<p>test#{i+1}<\/p>\s*/, e.content) end end def test_content_encoded_ruby_rss feed = FeedNormalizer::FeedNormalizer.parse(XML_FILES[:rss20], :force_parser => Fn::RubyRssParser, :try_others => false) feed.entries.each_with_index do |e, i| assert_match(/\s*<p>test#{i+1}<\/p>\s*/, e.content) end end def test_atom_content_contains_pluses feed = FeedNormalizer::FeedNormalizer.parse(XML_FILES[:atom10], :force_parser => Fn::SimpleRssParser, :try_others => false) assert_equal 2, feed.entries.last.content.scan(/\+/).size end # http://code.google.com/p/feed-normalizer/issues/detail?id=13 def test_times_are_reparsed feed = FeedNormalizer::FeedNormalizer.parse(XML_FILES[:rss20], :force_parser => Fn::RubyRssParser, :try_others => false) Time.class_eval "alias :old_to_s :to_s; def to_s(x=1); old_to_s; end" assert_equal Time.parse("Sat Sep 09 10:57:06 -0400 2006").to_s, feed.last_updated.to_s(:foo) assert_equal Time.parse("Sat Sep 09 08:45:35 -0400 2006").to_s, feed.entries.first.date_published.to_s(:foo) end def test_atom03_has_issued SimpleRSS.class_eval "@@item_tags.delete(:issued)" feed = FeedNormalizer::FeedNormalizer.parse(XML_FILES[:atom03], :force_parser => Fn::SimpleRssParser, :try_others => false) assert_nil feed.entries.first.date_published SimpleRSS.class_eval "@@item_tags << :issued" feed = FeedNormalizer::FeedNormalizer.parse(XML_FILES[:atom03], :force_parser => Fn::SimpleRssParser, :try_others => false) assert_equal "Tue Aug 29 02:31:03 UTC 2006", feed.entries.first.date_published.to_s end def test_html_should_be_escaped_by_default feed = FeedNormalizer::FeedNormalizer.parse(XML_FILES[:rss20], :force_parser => Fn::RubyRssParser, :try_others => false) assert_match "<b>SanDisk</b>", feed.items.last.description feed = FeedNormalizer::FeedNormalizer.parse(XML_FILES[:rss20], :force_parser => Fn::SimpleRssParser, :try_others => false) assert_match "<b>SanDisk</b>", feed.items.last.description end def test_relative_links_and_images_should_be_rewritten_with_url_base feed = FeedNormalizer::FeedNormalizer.parse(XML_FILES[:atom03]) assert_match '<a href="http://www.cheapstingybargains.com/link/tplclick?lid=41000000011334249&#038;pubid=21000000000053626"' + ' target=_"blank"><img src="http://www.cheapstingybargains.com/assets/images/product/productDetail/9990000058546711.jpg"' + ' width="150" height="150" border="0" style="float: right; margin: 0px 0px 5px 5px;" /></a>', feed.items.first.content end def test_last_updated_simple_rss feed = FeedNormalizer::FeedNormalizer.parse(XML_FILES[:atom10], :force_parser => Fn::SimpleRssParser, :try_others => false) assert_equal Time.parse("Wed Aug 16 09:59:44 -0700 2006"), feed.entries.first.last_updated end def test_last_updated_ruby_rss feed = FeedNormalizer::FeedNormalizer.parse(XML_FILES[:rss20], :force_parser => Fn::RubyRssParser, :try_others => false) assert_equal feed.entries.first.date_published, feed.entries.first.last_updated end def test_skip_empty_items feed = FeedNormalizer::FeedNormalizer.parse(XML_FILES[:rss20], :force_parser => Fn::RubyRssParser, :try_others => false) assert_not_nil feed.items.last.description feed = FeedNormalizer::FeedNormalizer.parse(XML_FILES[:rss20], :force_parser => Fn::SimpleRssParser, :try_others => false) assert_not_nil feed.items.last.description end end
ruby
BSD-3-Clause
afa7765c08481d38729a71bd5dfd5ef95736f026
2026-01-04T17:46:36.268985Z
false
aasmith/feed-normalizer
https://github.com/aasmith/feed-normalizer/blob/afa7765c08481d38729a71bd5dfd5ef95736f026/test/test_htmlcleaner.rb
test/test_htmlcleaner.rb
$LOAD_PATH.unshift(File.expand_path(File.join(File.dirname(__FILE__), '../lib'))) require 'test/unit' require 'html-cleaner' include FeedNormalizer class HtmlCleanerTest < Test::Unit::TestCase def test_unescape assert_equal "' ' &deg;", FeedNormalizer::HtmlCleaner.unescapeHTML("&apos; &#39; &deg;") assert_equal "\" &deg;", FeedNormalizer::HtmlCleaner.unescapeHTML("&quot; &deg;") assert_equal "\"\"\"\"", FeedNormalizer::HtmlCleaner.unescapeHTML("&#34;&#000000000000000000034;&#x22;&#x0000022;") assert_equal "heavily subnet&#8217;d network,", FeedNormalizer::HtmlCleaner.unescapeHTML("heavily subnet&#8217;d network,") end def test_add_entities assert_equal "", HtmlCleaner.add_entities(nil) assert_equal "x &gt; y", HtmlCleaner.add_entities("x > y") assert_equal "1 &amp; 2", HtmlCleaner.add_entities("1 & 2") assert_equal "&amp; &#123; &acute; &#x123;", HtmlCleaner.add_entities("& &#123; &acute; &#x123;") assert_equal "&amp; &#123; &ACUTE; &#X123A; &#x80f;", HtmlCleaner.add_entities("& &#123; &ACUTE; &#X123A; &#x80f;") assert_equal "heavily subnet&#8217;d network,", HtmlCleaner.add_entities("heavily subnet&#8217;d network,") end def test_html_clean assert_equal "", HtmlCleaner.clean("") assert_equal "<p>foo &gt; *</p>", HtmlCleaner.clean("<p>foo > *</p>") assert_equal "<p>foo &gt; *</p>", HtmlCleaner.clean("<p>foo &gt; *</p>") assert_equal "<p>para</p>", HtmlCleaner.clean("<p foo=bar>para</p>") assert_equal "<p>para</p> outsider", HtmlCleaner.clean("<p foo=bar>para</p> outsider") assert_equal "<p>para</p>", HtmlCleaner.clean("<p>para</p></notvalid>") assert_equal "<p>para</p>", HtmlCleaner.clean("<p>para</p></body>") assert_equal "<p>para</p>", HtmlCleaner.clean("<p>para</p><plaintext>") assert_equal "<p>para</p>", HtmlCleaner.clean("<p>para</p><object><param></param></object>") assert_equal "<p>para</p>", HtmlCleaner.clean("<p>para</p><iframe src='http://evil.example.org'></iframe>") assert_equal "<p>para</p>", HtmlCleaner.clean("<p>para</p><iframe src='http://evil.example.org'>") assert_equal "<p>para</p>", HtmlCleaner.clean("<p>para</p><invalid>invalid</invalid>") assert_equal "<a href=\"http://example.org\">para</a>", HtmlCleaner.clean("<a href='http://example.org'>para</a>") assert_equal "<a href=\"http://example.org/proc?a&amp;b\">para</a>", HtmlCleaner.clean("<a href='http://example.org/proc?a&b'>para</a>") assert_equal "<p>two</p>", HtmlCleaner.clean("<p>para</p><body><p>two</p></body>") assert_equal "<p>two</p>", HtmlCleaner.clean("<p>para</p><body><p>two</p>") assert_equal "<p>para</p>&lt;bo /dy&gt;<p>two</p>", HtmlCleaner.clean("<p>para</p><bo /dy><p>two</p></body>") assert_equal "<p>para</p>&lt;bo\\/dy&gt;<p>two</p>", HtmlCleaner.clean("<p>para</p><bo\\/dy><p>two</p></body>") assert_equal "<p>two</p>", HtmlCleaner.clean("<p>para</p><body/><p>two</p></body>") assert_equal "<p>one &amp; two</p>", HtmlCleaner.clean(HtmlCleaner.clean("<p>one & two</p>")) assert_equal "<p id=\"p\">para</p>", HtmlCleaner.clean("<p id=\"p\" ignore=\"this\">para</p>") assert_equal "<p id=\"p\">para</p>", HtmlCleaner.clean("<p id=\"p\" onclick=\"this\">para</p>") assert_equal "<img src=\"http://example.org/pic\" />", HtmlCleaner.clean("<img src=\"http://example.org/pic\" />") assert_equal "<img />", HtmlCleaner.clean("<img src=\"jav a script:call()\" />") assert_equal "what's new", HtmlCleaner.clean("what&#000039;s new") assert_equal "&quot;what's new?&quot;", HtmlCleaner.clean("\"what&apos;s new?\"") assert_equal "&quot;what's new?&quot;", HtmlCleaner.clean("&quot;what&apos;s new?&quot;") # Real-world examples from selected feeds assert_equal "I have a heavily subnet&#8217;d/vlan&#8217;d network,", HtmlCleaner.clean("I have a heavily subnet&#8217;d/vlan&#8217;d network,") assert_equal "<pre><blockquote>&lt;%= start_form_tag :action =&gt; &quot;create&quot; %&gt;</blockquote></pre>", HtmlCleaner.clean("<pre><blockquote>&lt;%= start_form_tag :action => \"create\" %></blockquote></pre>") assert_equal "<a href=\"http://www.mcall.com/news/local/all-smashedmachine1107-cn,0,1574203.story?coll=all-news-hed\">[link]</a><a href=\"http://reddit.com/info/pyhc/comments\">[more]</a>", HtmlCleaner.clean("&lt;a href=\"http://www.mcall.com/news/local/all-smashedmachine1107-cn,0,1574203.story?coll=all-news-hed\"&gt;[link]&lt;/a&gt;&lt;a href=\"http://reddit.com/info/pyhc/comments\"&gt;[more]&lt;/a&gt;") # Various exploits from the past assert_equal "", HtmlCleaner.clean("<_img foo=\"<IFRAME width='80%' height='400' src='http://alive.znep.com/~marcs/passport/grabit.html'></IFRAME>\" >") assert_equal "<a href=\"https://bugzilla.mozilla.org/attachment.cgi?id=&amp;action=force_internal_error&lt;script&gt;alert(document.cookie)&lt;/script&gt;\">link</a>", HtmlCleaner.clean("<a href=\"https://bugzilla.mozilla.org/attachment.cgi?id=&action=force_internal_error<script>alert(document.cookie)</script>\">link</a>") assert_equal "<img src=\"doesntexist.jpg\" />", HtmlCleaner.clean("<img src='doesntexist.jpg' onerror='alert(document.cookie)'/>") assert_equal "<img src=\"'doesntexist.jpg\" />", HtmlCleaner.clean("<img src=\"'doesntexist.jpg\" onmouseover=\"alert('img-ob-11');''\"/>") assert_equal "&lt;IMG &quot;&quot;&quot;&gt;&quot;&gt;", HtmlCleaner.clean("<IMG \"\"\"><SCRIPT>alert(\"XSS\")</SCRIPT>\">") # This doesnt come out as I would like, but the result is still safe. # (Apparently, this would work in Gecko.) assert HtmlCleaner.clean("<p onclick!\#$%&()*~+-_.,:;?@[/|\\]^=alert(\"XSS\")>para</p>") !~ /\<\>/ assert_equal "&lt;SCRIPT/XSS SRC=&quot;http://ha.ckers.org/xss.js&quot;&gt;", HtmlCleaner.clean("<SCRIPT/XSS SRC=\"http://ha.ckers.org/xss.js\"></SCRIPT>") assert_equal "", HtmlCleaner.clean("<!--[if gte IE 4]><SCRIPT>alert('XSS');</SCRIPT><![endif]-->") assert_equal "<p></p>", HtmlCleaner.clean("<p><!--[if gte IE 4]><SCRIPT>alert('XSS');</SCRIPT><![endif]--></p>") assert_equal "<p>hi</p><p></p>", HtmlCleaner.clean("<p>hi</p><p><!--[if gte IE 4]><SCRIPT>alert('XSS');</SCRIPT><![endif]--></p>") assert_equal "<p>hello</p>", HtmlCleaner.clean("<p>h<!-- hoho -->ell<!-- hoho -->o</p>") end def test_html_flatten assert_equal "", HtmlCleaner.flatten("") assert_equal "hello", HtmlCleaner.flatten("hello") assert_equal "hello world", HtmlCleaner.flatten("hello\nworld") assert_equal "A &gt; B : C", HtmlCleaner.flatten("A > B : C") assert_equal "what's new", HtmlCleaner.flatten("what&#39;s new") assert_equal "&quot;what's new?&quot;", HtmlCleaner.flatten("\"what&apos;s new?\"") assert_equal "we&#8217;ve got &lt;a hre", HtmlCleaner.flatten("we&#8217;ve got <a hre") assert_equal "http://example.org", HtmlCleaner.flatten("http://example.org") assert_equal "http://example.org/proc?a&amp;b", HtmlCleaner.flatten("http://example.org/proc?a&b") assert_equal "&quot;what's new?&quot;", HtmlCleaner.flatten(HtmlCleaner.flatten("\"what&apos;s new?\"")) end def test_dodgy_uri # All of these javascript urls work in IE6. assert HtmlCleaner.dodgy_uri?("javascript:alert('HI');") assert HtmlCleaner.dodgy_uri?(" &#106;&#97;&#118;&#97;&#115;&#99;&#114;&#105;&#112;&#116; \n :alert('HI');") assert HtmlCleaner.dodgy_uri?("JaVaScRiPt:alert('HI');") assert HtmlCleaner.dodgy_uri?("JaV \naSc\nRiPt:alert('HI');") # entities lacking ending ';' # This only works if they're all packed together without spacing. assert HtmlCleaner.dodgy_uri?("&#106&#97&#118&#97&#115&#99&#114&#105&#112&#116&#58&#97&#108&#101&#114&#116&#40&#39&#105&#109&#103&#45&#111&#98&#45&#50&#39&#41") assert HtmlCleaner.dodgy_uri?("&#106&#97&#118&#97&#115&#99&#114&#105&#112&#116&#58&#97&#108&#101&#114&#116&#40&#39&#105&#109&#103&#45&#111&#98&#45&#50&#39 &#41 ; ") # catch extra spacing anyway.. support for this is possible, depending where the spaces are. assert HtmlCleaner.dodgy_uri?("&#106 &#97 &#118 &#97 &#115 &#99 &#114 &#105 &#112 &#116 &#58 &#97 &#108 &#101 &#114 &#116 &#40 &#39 &#105 &#109 &#103 &#45 &#111 &#98 &#45 &#50 &#39 &#41 ; ") assert HtmlCleaner.dodgy_uri?("&#x06a &#97 &#118 &#97 &#115 &#99 &#114 &#105 &#112 &#116 &#58 &#97 &#108 &#101 &#114 &#116 &#40 &#39 &#105 &#109 &#103 &#45 &#111 &#98 &#45 &#50 &#39 &#41 ; ") assert HtmlCleaner.dodgy_uri?("&#106avascript") assert HtmlCleaner.dodgy_uri?("&#x06a;avascript") # url-encoded assert HtmlCleaner.dodgy_uri?("%6A%61%76%61%73%63%72%69%70%74%3A%61%6C%65%72%74%28%27%69%6D%67%2D%6F%62%2D%33%27%29") # Other evil schemes assert HtmlCleaner.dodgy_uri?("vbscript:MsgBox(\"hi\")") assert HtmlCleaner.dodgy_uri?("mocha:alert('hi')") assert HtmlCleaner.dodgy_uri?("livescript:alert('hi')") assert HtmlCleaner.dodgy_uri?("data:text/html;base64,PHNjcmlwdD5hbGVydCgnWFNTJyk8L3NjcmlwdD4K") # Various non-printing chars assert HtmlCleaner.dodgy_uri?("javas\0cript:foo()") assert HtmlCleaner.dodgy_uri?(" &#14; javascript:foo()") assert HtmlCleaner.dodgy_uri?("jav&#x0A;ascript:foo()") assert HtmlCleaner.dodgy_uri?("jav&#x09;ascript:foo()") assert HtmlCleaner.dodgy_uri?("jav\tascript:foo()") # The Good assert_nil HtmlCleaner.dodgy_uri?(nil) assert_nil HtmlCleaner.dodgy_uri?("http://example.org") assert_nil HtmlCleaner.dodgy_uri?("http://example.org/foo.html") assert_nil HtmlCleaner.dodgy_uri?("http://example.org/foo.cgi?x=y&a=b") assert_nil HtmlCleaner.dodgy_uri?("http://example.org/foo.cgi?x=y&amp;a=b") assert_nil HtmlCleaner.dodgy_uri?("http://example.org/foo.cgi?x=y&#38;a=b") assert_nil HtmlCleaner.dodgy_uri?("http://example.org/foo.cgi?x=y&#x56;a=b") end end
ruby
BSD-3-Clause
afa7765c08481d38729a71bd5dfd5ef95736f026
2026-01-04T17:46:36.268985Z
false
aasmith/feed-normalizer
https://github.com/aasmith/feed-normalizer/blob/afa7765c08481d38729a71bd5dfd5ef95736f026/lib/html-cleaner.rb
lib/html-cleaner.rb
require 'rubygems' require 'hpricot' require 'cgi' module FeedNormalizer # Various methods for cleaning up HTML and preparing it for safe public # consumption. # # Documents used for refrence: # - http://www.w3.org/TR/html4/index/attributes.html # - http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references # - http://feedparser.org/docs/html-sanitization.html # - http://code.whytheluckystiff.net/hpricot/wiki class HtmlCleaner # allowed html elements. HTML_ELEMENTS = %w( a abbr acronym address area b bdo big blockquote br button caption center cite code col colgroup dd del dfn dir div dl dt em fieldset font h1 h2 h3 h4 h5 h6 hr i img ins kbd label legend li map menu ol optgroup p pre q s samp small span strike strong sub sup table tbody td tfoot th thead tr tt u ul var ) # allowed attributes. HTML_ATTRS = %w( abbr accept accept-charset accesskey align alt axis border cellpadding cellspacing char charoff charset checked cite class clear cols colspan color compact coords datetime dir disabled for frame headers height href hreflang hspace id ismap label lang longdesc maxlength media method multiple name nohref noshade nowrap readonly rel rev rows rowspan rules scope selected shape size span src start summary tabindex target title type usemap valign value vspace width ) # allowed attributes, but they can contain URIs, extra caution required. # NOTE: That means this doesnt list *all* URI attrs, just the ones that are allowed. HTML_URI_ATTRS = %w( href src cite usemap longdesc ) DODGY_URI_SCHEMES = %w( javascript vbscript mocha livescript data ) class << self # Does this: # - Unescape HTML # - Parse HTML into tree # - Find 'body' if present, and extract tree inside that tag, otherwise parse whole tree # - Each tag: # - remove tag if not whitelisted # - escape HTML tag contents # - remove all attributes not on whitelist # - extra-scrub URI attrs; see dodgy_uri? # # Extra (i.e. unmatched) ending tags and comments are removed. def clean(str) str = unescapeHTML(str) doc = Hpricot(str, :fixup_tags => true) doc = subtree(doc, :body) # get all the tags in the document # Somewhere near hpricot 0.4.92 "*" starting to return all elements, # including text nodes instead of just tagged elements. tags = (doc/"*").inject([]) { |m,e| m << e.name if(e.respond_to?(:name) && e.name =~ /^\w+$/) ; m }.uniq # Remove tags that aren't whitelisted. remove_tags!(doc, tags - HTML_ELEMENTS) remaining_tags = tags & HTML_ELEMENTS # Remove attributes that aren't on the whitelist, or are suspicious URLs. (doc/remaining_tags.join(",")).each do |element| next if element.raw_attributes.nil? || element.raw_attributes.empty? element.raw_attributes.reject! do |attr,val| !HTML_ATTRS.include?(attr) || (HTML_URI_ATTRS.include?(attr) && dodgy_uri?(val)) end element.raw_attributes = element.raw_attributes.build_hash {|a,v| [a, add_entities(v)]} end unless remaining_tags.empty? doc.traverse_text do |t| t.swap(add_entities(t.to_html)) end # Return the tree, without comments. Ugly way of removing comments, # but can't see a way to do this in Hpricot yet. doc.to_s.gsub(/<\!--.*?-->/mi, '') end # For all other feed elements: # - Unescape HTML. # - Parse HTML into tree (taking 'body' as root, if present) # - Takes text out of each tag, and escapes HTML. # - Returns all text concatenated. def flatten(str) str.gsub!("\n", " ") str = unescapeHTML(str) doc = Hpricot(str, :xhtml_strict => true) doc = subtree(doc, :body) out = [] doc.traverse_text {|t| out << add_entities(t.to_html)} return out.join end # Returns true if the given string contains a suspicious URL, # i.e. a javascript link. # # This method rejects javascript, vbscript, livescript, mocha and data URLs. # It *could* be refined to only deny dangerous data URLs, however. def dodgy_uri?(uri) uri = uri.to_s # special case for poorly-formed entities (missing ';') # if these occur *anywhere* within the string, then throw it out. return true if (uri =~ /&\#(\d+|x[0-9a-f]+)[^;\d]/mi) # Try escaping as both HTML or URI encodings, and then trying # each scheme regexp on each [unescapeHTML(uri), CGI.unescape(uri)].each do |unesc_uri| DODGY_URI_SCHEMES.each do |scheme| regexp = "#{scheme}:".gsub(/./) do |char| "([\000-\037\177\s]*)#{char}" end # regexp looks something like # /\A([\000-\037\177\s]*)j([\000-\037\177\s]*)a([\000-\037\177\s]*)v([\000-\037\177\s]*)a([\000-\037\177\s]*)s([\000-\037\177\s]*)c([\000-\037\177\s]*)r([\000-\037\177\s]*)i([\000-\037\177\s]*)p([\000-\037\177\s]*)t([\000-\037\177\s]*):/mi return true if (unesc_uri =~ %r{\A#{regexp}}mi) end end nil end # unescapes HTML. If xml is true, also converts XML-only named entities to HTML. def unescapeHTML(str, xml = true) CGI.unescapeHTML(xml ? str.gsub("&apos;", "&#39;") : str) end # Adds entities where possible. # Works like CGI.escapeHTML, but will not escape existing entities; # i.e. &#123; will NOT become &amp;#123; # # This method could be improved by adding a whitelist of html entities. def add_entities(str) str.to_s.gsub(/\"/n, '&quot;').gsub(/>/n, '&gt;').gsub(/</n, '&lt;').gsub(/&(?!(\#\d+|\#x([0-9a-f]+)|\w{2,8});)/nmi, '&amp;') end private # Everything below elment, or the just return the doc if element not present. def subtree(doc, element) doc.at("//#{element}/*") || doc end def remove_tags!(doc, tags) (doc/tags.join(",")).remove unless tags.empty? end end end end module Enumerable #:nodoc: def build_hash result = {} self.each do |elt| key, value = yield elt result[key] = value end result end end
ruby
BSD-3-Clause
afa7765c08481d38729a71bd5dfd5ef95736f026
2026-01-04T17:46:36.268985Z
false
aasmith/feed-normalizer
https://github.com/aasmith/feed-normalizer/blob/afa7765c08481d38729a71bd5dfd5ef95736f026/lib/feed-normalizer.rb
lib/feed-normalizer.rb
require 'structures' require 'html-cleaner' module FeedNormalizer # The root parser object. Every parser must extend this object. class Parser # Parser being used. def self.parser nil end # Parses the given feed, and returns a normalized representation. # Returns nil if the feed could not be parsed. def self.parse(feed, loose) nil end # Returns a number to indicate parser priority. # The lower the number, the more likely the parser will be used first, # and vice-versa. def self.priority 0 end protected # Some utility methods that can be used by subclasses. # sets value, or appends to an existing value def self.map_functions!(mapping, src, dest) mapping.each do |dest_function, src_functions| src_functions = [src_functions].flatten # pack into array src_functions.each do |src_function| value = if src.respond_to?(src_function) src.send(src_function) elsif src.respond_to?(:has_key?) src[src_function] end unless value.to_s.empty? append_or_set!(value, dest, dest_function) break end end end end def self.append_or_set!(value, object, object_function) if object.send(object_function).respond_to? :push object.send(object_function).push(value) else object.send(:"#{object_function}=", value) end end private # Callback that ensures that every parser gets registered. def self.inherited(subclass) ParserRegistry.register(subclass) end end # The parser registry keeps a list of current parsers that are available. class ParserRegistry @@parsers = [] def self.register(parser) @@parsers << parser end # Returns a list of currently registered parsers, in order of priority. def self.parsers @@parsers.sort_by { |parser| parser.priority } end end class FeedNormalizer # Parses the given xml and attempts to return a normalized Feed object. # Setting +force_parser+ to a suitable parser will mean that parser is # used first, and if +try_others+ is false, it is the only parser used, # otherwise all parsers in the ParserRegistry are attempted, in # order of priority. # # ===Available options # # * <tt>:force_parser</tt> - instruct feed-normalizer to try the specified # parser first. Takes a class, such as RubyRssParser, or SimpleRssParser. # # * <tt>:try_others</tt> - +true+ or +false+, defaults to +true+. # If +true+, other parsers will be used as described above. The option # is useful if combined with +force_parser+ to only use a single parser. # # * <tt>:loose</tt> - +true+ or +false+, defaults to +false+. # # Specifies parsing should be done loosely. This means that when # feed-normalizer would usually throw away data in order to meet # the requirement of keeping resulting feed outputs the same regardless # of the underlying parser, the data will instead be kept. This currently # affects the following items: # * <em>Categories:</em> RSS allows for multiple categories per feed item. # * <em>Limitation:</em> SimpleRSS can only return the first category # for an item. # * <em>Result:</em> When loose is true, the extra categories are kept, # of course, only if the parser is not SimpleRSS. def self.parse(xml, opts = {}) # Get a string ASAP, as multiple read()'s will start returning nil.. xml = xml.respond_to?(:read) ? xml.read : xml.to_s if opts[:force_parser] result = opts[:force_parser].parse(xml, opts[:loose]) return result if result return nil if opts[:try_others] == false end ParserRegistry.parsers.each do |parser| result = parser.parse(xml, opts[:loose]) return result if result end # if we got here, no parsers worked. return nil end end parser_dir = File.dirname(__FILE__) + '/parsers' # Load up the parsers Dir.open(parser_dir).each do |fn| next unless fn =~ /[.]rb$/ require "parsers/#{fn}" end end
ruby
BSD-3-Clause
afa7765c08481d38729a71bd5dfd5ef95736f026
2026-01-04T17:46:36.268985Z
false
aasmith/feed-normalizer
https://github.com/aasmith/feed-normalizer/blob/afa7765c08481d38729a71bd5dfd5ef95736f026/lib/structures.rb
lib/structures.rb
module FeedNormalizer module Singular # If the method being called is a singular (in this simple case, does not # end with an 's'), then it calls the plural method, and calls the first # element. We're assuming that plural methods provide an array. # # Example: # Object contains an array called 'alphas', which looks like [:a, :b, :c]. # Call object.alpha and :a is returned. def method_missing(name, *args) plural_name = :"#{name}s" return self.send(plural_name).first if respond_to?(plural_name) super(name, *args) end def respond_to?(x, y=false) self.class::ELEMENTS.include?(x) || self.class::ELEMENTS.include?(:"#{x}s") || super(x, y) end end module ElementEquality def eql?(other) self == (other) end def ==(other) other.equal?(self) || (other.instance_of?(self.class) && self.class::ELEMENTS.all?{ |el| self.send(el) == other.send(el)} ) end # Returns the difference between two Feed instances as a hash. # Any top-level differences in the Feed object as presented as: # # { :title => [content, other_content] } # # For differences at the items level, an array of hashes shows the diffs # on a per-entry basis. Only entries that differ will contain a hash: # # { :items => [ # {:title => ["An article tile", "A new article title"]}, # {:title => ["one title", "a different title"]} ]} # # If the number of items in each feed are different, then the count of each # is provided instead: # # { :items => [4,5] } # # This method can also be useful for human-readable feed comparison if # its output is dumped to YAML. def diff(other, elements = self.class::ELEMENTS) diffs = {} elements.each do |element| if other.respond_to?(element) self_value = self.send(element) other_value = other.send(element) next if self_value == other_value diffs[element] = if other_value.respond_to?(:diff) self_value.diff(other_value) elsif other_value.is_a?(Enumerable) && other_value.all?{|v| v.respond_to?(:diff)} if self_value.size != other_value.size [self_value.size, other_value.size] else enum_diffs = [] self_value.each_with_index do |val, index| enum_diffs << val.diff(other_value[index], val.class::ELEMENTS) end enum_diffs.reject{|h| h.empty?} end else [other_value, self_value] unless other_value == self_value end end end diffs end end module ElementCleaner # Recursively cleans all elements in place. # # Only allow tags in whitelist. Always parse the html with a parser and delete # all tags that arent on the list. # # For feed elements that can contain HTML: # - feed.(title|description) # - feed.entries[n].(title|description|content) # def clean! self.class::SIMPLE_ELEMENTS.each do |element| val = self.send(element) send("#{element}=", (val.is_a?(Array) ? val.collect{|v| HtmlCleaner.flatten(v.to_s)} : HtmlCleaner.flatten(val.to_s))) end self.class::HTML_ELEMENTS.each do |element| send("#{element}=", HtmlCleaner.clean(self.send(element).to_s)) end self.class::BLENDED_ELEMENTS.each do |element| self.send(element).collect{|v| v.clean!} end end end module TimeFix # Reparse any Time instances, due to RSS::Parser's redefinition of # certain aspects of the Time class that creates unexpected behaviour # when extending the Time class, as some common third party libraries do. # See http://code.google.com/p/feed-normalizer/issues/detail?id=13. def reparse(obj) @parsed ||= false if obj.is_a?(String) @parsed = true begin Time.at(obj) rescue Time.rfc2822(obj) rescue Time.parse(obj) rescue @parsed = false obj end else return obj if @parsed if obj.is_a?(Time) @parsed = true Time.at(obj) rescue obj end end end end module RewriteRelativeLinks def rewrite_relative_links(text, url) if host = url_host(url) text.to_s.gsub(/(href|src)=('|")\//, '\1=\2http://' + host + '/') else text end end private def url_host(url) URI.parse(url).host rescue nil end end # Represents a feed item entry. # Available fields are: # * content # * description # * title # * date_published # * urls / url # * id # * authors / author # * copyright # * categories class Entry include Singular, ElementEquality, ElementCleaner, TimeFix, RewriteRelativeLinks HTML_ELEMENTS = [:content, :description, :title] SIMPLE_ELEMENTS = [:date_published, :urls, :id, :authors, :copyright, :categories, :last_updated, :enclosures] BLENDED_ELEMENTS = [] ELEMENTS = HTML_ELEMENTS + SIMPLE_ELEMENTS + BLENDED_ELEMENTS attr_accessor(*ELEMENTS) def initialize @urls = [] @authors = [] @categories = [] @enclosures = [] @date_published, @content, @last_updated = nil end undef date_published def date_published @date_published = reparse(@date_published) end undef last_updated def last_updated @last_updated = reparse(@last_updated) end undef content def content @content = rewrite_relative_links(@content, url) end end # Represents the root element of a feed. # Available fields are: # * title # * description # * id # * last_updated # * copyright # * authors / author # * urls / url # * image # * generator # * items / channel class Feed include Singular, ElementEquality, ElementCleaner, TimeFix # Elements that can contain HTML fragments. HTML_ELEMENTS = [:title, :description] # Elements that contain 'plain' Strings, with HTML escaped. SIMPLE_ELEMENTS = [:id, :last_updated, :copyright, :authors, :urls, :image, :generator, :ttl, :skip_hours, :skip_days] # Elements that contain both HTML and escaped HTML. BLENDED_ELEMENTS = [:items] ELEMENTS = HTML_ELEMENTS + SIMPLE_ELEMENTS + BLENDED_ELEMENTS attr_accessor(*ELEMENTS) attr_accessor(:parser) alias :entries :items def initialize(wrapper) # set up associations (i.e. arrays where needed) @urls = [] @authors = [] @skip_hours = [] @skip_days = [] @items = [] @parser = wrapper.parser.to_s @last_updated = nil end undef last_updated def last_updated @last_updated = reparse(@last_updated) end def channel() self end end end
ruby
BSD-3-Clause
afa7765c08481d38729a71bd5dfd5ef95736f026
2026-01-04T17:46:36.268985Z
false
aasmith/feed-normalizer
https://github.com/aasmith/feed-normalizer/blob/afa7765c08481d38729a71bd5dfd5ef95736f026/lib/parsers/simple-rss.rb
lib/parsers/simple-rss.rb
require 'simple-rss' # Monkey patches for outstanding issues logged in the simple-rss project. # * Add support for issued time field: # http://rubyforge.org/tracker/index.php?func=detail&aid=13980&group_id=893&atid=3517 # * The '+' symbol is lost when escaping fields. # http://rubyforge.org/tracker/index.php?func=detail&aid=10852&group_id=893&atid=3517 # class SimpleRSS @@item_tags << :issued undef clean_content def clean_content(tag, attrs, content) content = content.to_s case tag when :pubDate, :lastBuildDate, :published, :updated, :expirationDate, :modified, :'dc:date', :issued Time.parse(content) rescue unescape(content) when :author, :contributor, :skipHours, :skipDays unescape(content.gsub(/<.*?>/,'')) else content.empty? && "#{attrs} " =~ /href=['"]?([^'"]*)['" ]/mi ? $1.strip : unescape(content) end end undef unescape def unescape(s) if s =~ /^\s*(<!\[CDATA\[|\]\]>)/ # Raw HTML is inside the CDATA, so just remove the CDATA wrapper. s.gsub(/(<!\[CDATA\[|\]\]>)/,'') elsif s =~ /[<>]/ # Already looks like HTML. s else # Make it HTML. FeedNormalizer::HtmlCleaner.unescapeHTML(s) end end end module FeedNormalizer # The SimpleRSS parser can handle both RSS and Atom feeds. class SimpleRssParser < Parser def self.parser SimpleRSS end def self.parse(xml, loose) begin atomrss = parser.parse(xml) rescue Exception => e #puts "Parser #{parser} failed because #{e.message.gsub("\n",', ')}" return nil end package(atomrss) end # Fairly low priority; a slower, liberal parser. def self.priority 900 end protected def self.package(atomrss) feed = Feed.new(self) # root elements feed_mapping = { :generator => :generator, :title => :title, :last_updated => [:updated, :lastBuildDate, :pubDate, :dc_date], :copyright => [:copyright, :rights], :authors => [:author, :webMaster, :managingEditor, :contributor], :urls => [:'link+alternate', :link], :description => [:description, :subtitle], :ttl => :ttl } map_functions!(feed_mapping, atomrss, feed) # custom channel elements feed.id = feed_id(atomrss) feed.image = image(atomrss) # entry elements entry_mapping = { :date_published => [:pubDate, :published, :dc_date, :issued], :urls => [:'link+alternate', :link], :enclosures => :enclosure, :description => [:description, :summary], :content => [:content, :content_encoded, :description], :title => :title, :authors => [:author, :contributor, :dc_creator], :categories => :category, :last_updated => [:updated, :dc_date, :pubDate] } atomrss.entries.each do |atomrss_entry| unless atomrss_entry.title.nil? && atomrss_entry.description.nil? # some feeds return empty items feed_entry = Entry.new map_functions!(entry_mapping, atomrss_entry, feed_entry) # custom entry elements feed_entry.id = atomrss_entry.guid || atomrss_entry[:id] # entries are a Hash.. # fall back to link for ID feed_entry.id ||= atomrss_entry.link if atomrss_entry.respond_to?(:link) && atomrss_entry.link feed_entry.copyright = atomrss_entry.copyright || (atomrss.respond_to?(:copyright) ? atomrss.copyright : nil) feed.entries << feed_entry end end feed end def self.image(parser) if parser.respond_to?(:image) && parser.image if parser.image =~ /<url>/ # RSS image contains an <url> spec parser.image.scan(/<url>(.*?)<\/url>/).to_s else parser.image # Atom contains just the url end elsif parser.respond_to?(:logo) && parser.logo parser.logo end end def self.feed_id(parser) overridden_value(parser, :id) || ("#{parser.link}" if parser.respond_to?(:link)) end # gets the value returned from the method if it overriden, otherwise nil. def self.overridden_value(object, method) object.class.public_instance_methods(false).include? method end end end
ruby
BSD-3-Clause
afa7765c08481d38729a71bd5dfd5ef95736f026
2026-01-04T17:46:36.268985Z
false
aasmith/feed-normalizer
https://github.com/aasmith/feed-normalizer/blob/afa7765c08481d38729a71bd5dfd5ef95736f026/lib/parsers/rss.rb
lib/parsers/rss.rb
require 'rss' # For some reason, this is only included in the RDF Item by default (in 0.1.6). unless RSS::Rss::Channel::Item.new.respond_to?(:content_encoded) class RSS::Rss::Channel::Item # :nodoc: include RSS::ContentModel end end # Add equality onto Enclosures. class RSS::Rss::Channel::Item::Enclosure def eql?(enc) instance_variables.all? do |iv| instance_variable_get(iv) == enc.instance_variable_get(iv) end end alias == eql? end module FeedNormalizer class RubyRssParser < Parser def self.parser RSS::Parser end def self.parse(xml, loose) begin rss = parser.parse(xml) rescue Exception => e #puts "Parser #{parser} failed because #{e.message.gsub("\n",', ')}" return nil end # check for channel to make sure we're only dealing with RSS. rss && rss.respond_to?(:channel) ? package(rss, loose) : nil end # Fairly high priority; a fast and strict parser. def self.priority 100 end protected def self.package(rss, loose) feed = Feed.new(self) # channel elements feed_mapping = { :generator => :generator, :title => :title, :urls => :link, :description => :description, :copyright => :copyright, :authors => :managingEditor, :last_updated => [:lastBuildDate, :pubDate, :dc_date], :id => :guid, :ttl => :ttl } # make two passes, to catch all possible root elements map_functions!(feed_mapping, rss, feed) map_functions!(feed_mapping, rss.channel, feed) # custom channel elements feed.image = rss.image ? rss.image.url : nil feed.skip_hours = skip(rss, :skipHours) feed.skip_days = skip(rss, :skipDays) # item elements item_mapping = { :date_published => [:pubDate, :dc_date], :urls => :link, :enclosures => :enclosure, :description => :description, :content => [:content_encoded, :description], :title => :title, :authors => [:author, :dc_creator], :last_updated => [:pubDate, :dc_date] # This is effectively an alias for date_published for this parser. } rss.items.each do |rss_item| unless rss_item.title.nil? && rss_item.description.nil? # some feeds return empty items feed_entry = Entry.new map_functions!(item_mapping, rss_item, feed_entry) # custom item elements feed_entry.id = rss_item.guid.content if rss_item.respond_to?(:guid) && rss_item.guid # fall back to link for ID feed_entry.id ||= rss_item.link if rss_item.respond_to?(:link) && rss_item.link feed_entry.copyright = rss.copyright if rss_item.respond_to? :copyright feed_entry.categories = loose ? rss_item.categories.collect{|c|c.content} : [rss_item.categories.first.content] rescue [] feed.entries << feed_entry end end feed end def self.skip(parser, attribute) case attribute when :skipHours then attributes = :hours when :skipDays then attributes = :days end channel = parser.channel return nil unless channel.respond_to?(attribute) && a = channel.send(attribute) a.send(attributes).collect{|e| e.content} end end end
ruby
BSD-3-Clause
afa7765c08481d38729a71bd5dfd5ef95736f026
2026-01-04T17:46:36.268985Z
false
open-uri-redirections/open_uri_redirections
https://github.com/open-uri-redirections/open_uri_redirections/blob/42828cdd98cabca60244d6b6e35943ec08c8bc8b/spec/redirections_spec.rb
spec/redirections_spec.rb
# -*- encoding: utf-8 -*- require File.join(File.dirname(__FILE__), '/spec_helper') class << OpenURI alias_method :open_uri_original__, :open_uri_original end describe 'OpenURI' do describe '#open' do describe 'Default settings' do it 'should disallow HTTP => HTTPS redirections' do expect { open('http://safe.com') }.to raise_error(RuntimeError, safe_forbidden_msg) end it 'should disallow HTTPS => HTTP redirections' do expect { open('https://unsafe.com') }.to raise_error(RuntimeError, unsafe_forbidden_msg) end end describe ':allow_redirections => :safe' do it 'should allow HTTP => HTTPS redirections' do expect { open('http://safe.com', :allow_redirections => :safe) }.to_not raise_error end it 'should disallow HTTPS => HTTP redirections' do expect { open('https://unsafe.com', :allow_redirections => :safe) }.to raise_error(RuntimeError, unsafe_forbidden_msg) end it 'should follow safe redirections' do expect( open('http://safe.com', :allow_redirections => :safe).read ).to eq('Hello, this is Safe.') end it 'should follow safe double redirections' do expect( open('http://safe2.com', :allow_redirections => :safe).read ).to eq('Hello, this is Safe.') end it 'should follow safe redirections with block' do expect { |b| open('http://safe.com', :allow_redirections => :safe, &b) }.to yield_control end end describe ':allow_redirections => :all' do it 'should allow HTTP => HTTPS redirections' do expect { open('http://safe.com', :allow_redirections => :all) }.to_not raise_error end it 'should allow HTTPS => HTTP redirections' do expect { open('https://unsafe.com', :allow_redirections => :all) }.to_not raise_error end it 'should follow safe redirections' do expect( open('http://safe.com', :allow_redirections => :all).read ).to eq('Hello, this is Safe.') end it 'should follow unsafe redirections' do expect( open('https://unsafe.com', :allow_redirections => :all).read ).to eq('Hello, this is Unsafe.') end it 'should follow safe redirections with block' do expect { |b| open('http://safe.com', :allow_redirections => :all, &b) }.to yield_control end it 'should follow unsafe redirections with block' do expect { |b| open('https://unsafe.com', :allow_redirections => :all, &b) }.to yield_control end end describe 'passing arguments down the stack' do it 'should disallow HTTP => HTTPS redirections' do expect { open('http://safe.com', 'r', 0444, 'User-Agent' => 'Mozilla/5.0') }.to raise_error(RuntimeError, safe_forbidden_msg) end it 'should allow HTTP => HTTPS redirections' do expect { open('http://safe.com', 'r', 0444, 'User-Agent' => 'Mozilla/5.0', :allow_redirections => :safe) }.to_not raise_error end it 'should pass the arguments down the stack' do expect(OpenURI).to receive(:open_uri_original).with(an_instance_of(URI::HTTP), 'r', 0444, { 'User-Agent' => 'Mozilla/5.0' }) open('http://safe.com', 'r', 0444, 'User-Agent' => 'Mozilla/5.0', :allow_redirections => :safe) end end describe 'threads' do it 'seems to work (could be false positive)' do allow(OpenURI).to receive(:open_uri_original) { |*a, &b| sleep rand; OpenURI.open_uri_original__ *a, &b } ts = [] Thread.abort_on_exception = true begin 100.times { ts << Thread.new { expect { open('http://safe.com') }.to raise_error(RuntimeError, safe_forbidden_msg) } ts << Thread.new { expect { open('http://safe.com', :allow_redirections => :safe) }.to_not raise_error } ts << Thread.new { expect { open('https://unsafe.com') }.to raise_error(RuntimeError, unsafe_forbidden_msg) } ts << Thread.new { expect { open('https://unsafe.com', :allow_redirections => :safe) }.to raise_error(RuntimeError, unsafe_forbidden_msg) } } ensure ts.each(&:join) end end end end private def safe_forbidden_msg 'redirection forbidden: http://safe.com -> https://safe.com/' end def unsafe_forbidden_msg 'redirection forbidden: https://unsafe.com -> http://unsafe.com/' end end
ruby
MIT
42828cdd98cabca60244d6b6e35943ec08c8bc8b
2026-01-04T17:46:36.376805Z
false
open-uri-redirections/open_uri_redirections
https://github.com/open-uri-redirections/open_uri_redirections/blob/42828cdd98cabca60244d6b6e35943ec08c8bc8b/spec/spec_helper.rb
spec/spec_helper.rb
# -*- encoding: utf-8 -*- $: << File.join(File.dirname(__FILE__), "/../lib") require 'open_uri_redirections' require 'fakeweb' FakeWeb.allow_net_connect = false $samples_dir = File.dirname(__FILE__) + '/samples' ####################### # Faked web responses # ####################### FakeWeb.register_uri(:get, "http://safe.com/", :response => open("#{$samples_dir}/http_safe.response").read) FakeWeb.register_uri(:get, "https://safe.com/", :response => open("#{$samples_dir}/https_safe.response").read) FakeWeb.register_uri(:get, "http://safe2.com/", :response => open("#{$samples_dir}/http_safe2.response").read) FakeWeb.register_uri(:get, "https://unsafe.com/", :response => open("#{$samples_dir}/https_unsafe.response").read) FakeWeb.register_uri(:get, "http://unsafe.com/", :response => open("#{$samples_dir}/http_unsafe.response").read)
ruby
MIT
42828cdd98cabca60244d6b6e35943ec08c8bc8b
2026-01-04T17:46:36.376805Z
false
open-uri-redirections/open_uri_redirections
https://github.com/open-uri-redirections/open_uri_redirections/blob/42828cdd98cabca60244d6b6e35943ec08c8bc8b/lib/open_uri_redirections.rb
lib/open_uri_redirections.rb
# -*- encoding: utf-8 -*- require 'open-uri' require File.expand_path(File.join(File.dirname(__FILE__), 'open-uri/redirections_patch'))
ruby
MIT
42828cdd98cabca60244d6b6e35943ec08c8bc8b
2026-01-04T17:46:36.376805Z
false
open-uri-redirections/open_uri_redirections
https://github.com/open-uri-redirections/open_uri_redirections/blob/42828cdd98cabca60244d6b6e35943ec08c8bc8b/lib/open_uri_redirections/version.rb
lib/open_uri_redirections/version.rb
module OpenUriRedirections VERSION = '0.2.1' end
ruby
MIT
42828cdd98cabca60244d6b6e35943ec08c8bc8b
2026-01-04T17:46:36.376805Z
false
open-uri-redirections/open_uri_redirections
https://github.com/open-uri-redirections/open_uri_redirections/blob/42828cdd98cabca60244d6b6e35943ec08c8bc8b/lib/open-uri/redirections_patch.rb
lib/open-uri/redirections_patch.rb
##### # Patch to allow open-uri to follow safe (http to https) # and unsafe redirections (https to http). # # Original gist URL: # https://gist.github.com/1271420 # # Relevant issue: # http://redmine.ruby-lang.org/issues/3719 # # Source here: # https://github.com/ruby/ruby/blob/trunk/lib/open-uri.rb # # Thread-safe implementation adapted from: # https://github.com/obfusk/open_uri_w_redirect_to_https # module OpenURI class <<self alias_method :open_uri_original, :open_uri alias_method :redirectable_cautious?, :redirectable? def redirectable?(uri1, uri2) case Thread.current[:__open_uri_redirections__] when :safe redirectable_safe? uri1, uri2 when :all redirectable_all? uri1, uri2 else redirectable_cautious? uri1, uri2 end end def redirectable_safe?(uri1, uri2) redirectable_cautious?(uri1, uri2) || http_to_https?(uri1, uri2) end def redirectable_all?(uri1, uri2) redirectable_safe?(uri1, uri2) || https_to_http?(uri1, uri2) end end ##### # Patches the original open_uri method, so that it accepts the # :allow_redirections argument with these options: # # * :safe will allow HTTP => HTTPS redirections. # * :all will allow HTTP => HTTPS and HTTPS => HTTP redirections. # # OpenURI::open can receive different kinds of arguments, like a string for # the mode or an integer for the permissions, and then a hash with options # like UserAgent, etc. # # To find the :allow_redirections option, we look for this options hash. # def self.open_uri(name, *rest, &block) Thread.current[:__open_uri_redirections__] = allow_redirections(rest) block2 = lambda do |io| Thread.current[:__open_uri_redirections__] = nil block[io] end begin open_uri_original name, *rest, &(block ? block2 : nil) ensure Thread.current[:__open_uri_redirections__] = nil end end private def self.allow_redirections(args) options = first_hash_argument(args) options.delete :allow_redirections if options end def self.first_hash_argument(arguments) arguments.select { |arg| arg.is_a? Hash }.first end def self.http_to_https?(uri1, uri2) schemes_from([uri1, uri2]) == %w(http https) end def self.https_to_http?(uri1, uri2) schemes_from([uri1, uri2]) == %w(https http) end def self.schemes_from(uris) uris.map { |u| u.scheme.downcase } end end
ruby
MIT
42828cdd98cabca60244d6b6e35943ec08c8bc8b
2026-01-04T17:46:36.376805Z
false
taylorthurlow/panda-motd
https://github.com/taylorthurlow/panda-motd/blob/d1cc6db9220243e83fbb1a2bbf91c6a143b9f559/spec/motd_spec.rb
spec/motd_spec.rb
# frozen_string_literal: true require "spec_helper" describe MOTD do subject(:motd) { create(:motd) } it "creates a new MOTD" do expect(motd).not_to be_nil end it "prints the MOTD" do allow(motd.components.first).to receive(:format_uptime).and_return("") expect(motd.to_s).not_to be_nil end context "when errors exist" do it "prints the errors" do component = create(:uptime) component.errors << ComponentError.new(component, "something broke") motd.instance_variable_set(:@components, [component]) expect(motd.to_s).to include "something broke" end end end
ruby
MIT
d1cc6db9220243e83fbb1a2bbf91c6a143b9f559
2026-01-04T17:46:36.398098Z
false
taylorthurlow/panda-motd
https://github.com/taylorthurlow/panda-motd/blob/d1cc6db9220243e83fbb1a2bbf91c6a143b9f559/spec/spec_helper.rb
spec/spec_helper.rb
# frozen_string_literal: true require "factory_bot" require "simplecov" require "fileutils" unless ENV["NO_COVERAGE"] SimpleCov.start do add_filter "/vendor" end end require "bundler/setup" Bundler.setup require "panda_motd" # and any other gems you need RSpec.configure do |config| # set up factory_bot config.include FactoryBot::Syntax::Methods # silence stdout and stderr original_stderr = $stderr original_stdout = $stdout config.before(:all) do unless defined?(Byebug) || defined?(Pry) $stderr = File.open(File::NULL, "w") $stdout = File.open(File::NULL, "w") end end config.after(:all) do $stderr = original_stderr $stdout = original_stdout end config.before(:suite) do FactoryBot.find_definitions # Make sure we have a tmp folder to save random crap to FileUtils.mkdir_p "tmp" end # remove all temp files after suite finished config.after(:suite) do Dir["tmp/**/*"].each { |f| File.delete(f) } end end # allow rspec mocks in factory_bot definitions FactoryBot::SyntaxRunner.class_eval do include RSpec::Mocks::ExampleMethods end Dir[File.dirname(__FILE__) + "/matchers/**/*.rb"].each { |file| require file } ##### # Helper methods ##### def instance_with_configuration(described_class, config_hash) config = instance_double("config", component_config: config_hash) motd = instance_double("motd", config: config) described_class.new(motd) end def stub_system_call(subject, with: nil, returns: command_output(subject.class)) if with allow(subject).to receive(:`).with(with).and_return(returns) else allow(subject).to receive(:`).and_return(returns) end end def command_output(component_class, file_name = "output") # class to string regex r = /(?<=[A-Z])(?=[A-Z][a-z])|(?<=[^A-Z])(?=[A-Z])|(?<=[A-Za-z])(?=[^A-Za-z])/ component_name = component_class.to_s.split(r).map(&:downcase).join("_") file_path = File.join( File.dirname(__dir__), "spec", "fixtures", "components", component_name, "#{file_name}.txt" ) File.read(file_path) end
ruby
MIT
d1cc6db9220243e83fbb1a2bbf91c6a143b9f559
2026-01-04T17:46:36.398098Z
false
taylorthurlow/panda-motd
https://github.com/taylorthurlow/panda-motd/blob/d1cc6db9220243e83fbb1a2bbf91c6a143b9f559/spec/component_spec.rb
spec/component_spec.rb
# frozen_string_literal: true require "spec_helper" describe Component do subject(:component) { motd = create(:motd) allow(motd.config).to receive(:component_config).with("name").and_return({}) described_class.new(motd, "name") } it "allows reading variables" do [:name, :errors, :results].each do |v| expect(component.respond_to?(v)).to be true end end context "#process" do it "raises an error" do expect { component.process }.to raise_error(NotImplementedError) end end context "#to_s" do it "raises an error" do expect { component.to_s }.to raise_error(NotImplementedError) end end context "#lines_before" do it "does not return nil" do expect(component.lines_before).not_to be_nil end end context "#lines_after" do it "does not return nil" do expect(component.lines_after).not_to be_nil end end end
ruby
MIT
d1cc6db9220243e83fbb1a2bbf91c6a143b9f559
2026-01-04T17:46:36.398098Z
false
taylorthurlow/panda-motd
https://github.com/taylorthurlow/panda-motd/blob/d1cc6db9220243e83fbb1a2bbf91c6a143b9f559/spec/factories/config_factory.rb
spec/factories/config_factory.rb
# frozen_string_literal: true require "yaml" FactoryBot.define do factory :config do skip_create config_number = SecureRandom.hex(10) transient do components { [] } end file_path { "tmp/config#{config_number}" } before(:create) do |_config, evaluator| if evaluator.components.any? component_hash = {} cfg = evaluator.components .map { |ec| "spec/fixtures/configs/#{ec}.yaml" } .map { |y| YAML.safe_load(File.read(y))["components"] } .reduce(&:merge) # merge configs into one yaml component_hash["components"] = cfg File.open("tmp/config#{config_number}", "w") do |f| f.write component_hash.to_yaml end end end initialize_with { new(file_path) } end end
ruby
MIT
d1cc6db9220243e83fbb1a2bbf91c6a143b9f559
2026-01-04T17:46:36.398098Z
false