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
coinbase/coinbase-exchange-ruby
https://github.com/coinbase/coinbase-exchange-ruby/blob/3e01d2ea5ade324bec82233ca29304c80b1058d2/lib/coinbase/exchange/websocket.rb
lib/coinbase/exchange/websocket.rb
module Coinbase module Exchange # Websocket client for Coinbase Exchange class Websocket def initialize(options = {}) @ws_url = options[:ws_url] || "wss://ws-feed.gdax.com" @product = options[:product_id] || 'BTC-USD' @keepalive = options[:keepalive] || false @message_cb = ->(_data) { nil } @received_cb = ->(_data) { nil } @open_cb = ->(_data) { nil } @match_cb = ->(_data) { nil } @change_cb = ->(_data) { nil } @done_cb = ->(_data) { nil } @error_cb = ->(_data) { nil } end def start! if EventMachine.reactor_running? @reactor_owner = false refresh! else @reactor_owner = true EM.run { refresh! } end end def stop! if @reactor_owner == true @socket.onclose = ->(_event) { EM.stop } else @socket.onclose = ->(_event) { nil } end @socket.close end def refresh! @socket = Faye::WebSocket::Client.new(@ws_url) @socket.onopen = method(:ws_opened) @socket.onmessage = method(:ws_received) @socket.onclose = method(:ws_closed) @socket.onerror = method(:ws_error) end def subscribe!(options = {}) product = options[:product_id] || @product @socket.send({ type: 'subscribe', product_id: product }.to_json) end def ping(options = {}) msg = options[:payload] || Time.now.to_s @socket.ping(msg) do |resp| yield(resp) if block_given? end end # Run this before processing every message def message(&block) @message_cb = block end def received(&block) @received_cb = block end def open(&block) @open_cb = block end def match(&block) @match_cb = block end def change(&block) @change_cb = block end def done(&block) @done_cb = block end def error(&block) @error_cb = block end private def ws_opened(_event) subscribe! end def ws_received(event) data = APIObject.new(JSON.parse(event.data)) @message_cb.call(data) case data['type'] when 'received' then @received_cb.call(data) when 'open' then @open_cb.call(data) when 'match' then @match_cb.call(data) when 'change' then @change_cb.call(data) when 'done' then @done_cb.call(data) when 'error' then @error_cb.call(data) end end def ws_closed(_event) if @keepalive refresh! else EM.stop end end def ws_error(event) fail WebsocketError, event.data end end end end
ruby
Apache-2.0
3e01d2ea5ade324bec82233ca29304c80b1058d2
2026-01-04T17:55:58.161349Z
false
coinbase/coinbase-exchange-ruby
https://github.com/coinbase/coinbase-exchange-ruby/blob/3e01d2ea5ade324bec82233ca29304c80b1058d2/lib/coinbase/exchange/adapters/em_http.rb
lib/coinbase/exchange/adapters/em_http.rb
module Coinbase module Exchange # EM-Http Adapter class EMHTTPClient < APIClient def initialize(api_key = '', api_secret = '', api_pass = '', options = {}) super(api_key, api_secret, api_pass, options) end private def http_verb(method, path, body = nil) if !EventMachine.reactor_running? EM.run do # FIXME: This doesn't work with paginated endpoints http_verb(method, path, body) do |resp| yield(resp) EM.stop end end else req_ts = Time.now.utc.to_i.to_s signature = Base64.encode64( OpenSSL::HMAC.digest('sha256', Base64.decode64(@api_secret).strip, "#{req_ts}#{method}#{path}#{body}")).strip headers = {} headers['Content-Type'] = 'application/json' headers['CB-ACCESS-TIMESTAMP'] = req_ts headers['CB-ACCESS-PASSPHRASE'] = @api_pass headers['CB-ACCESS-KEY'] = @api_key headers['CB-ACCESS-SIGN'] = signature # NOTE: This is documented but not implemented in em-http-request # https://github.com/igrigorik/em-http-request/issues/182 # https://github.com/igrigorik/em-http-request/pull/179 ssl_opts = { cert_chain_file: File.expand_path(File.join(File.dirname(__FILE__), 'ca-coinbase.crt')), verify_peer: true } case method when 'GET' req = EM::HttpRequest.new(@api_uri).get(path: path, head: headers, body: body, ssl: ssl_opts) when 'POST' req = EM::HttpRequest.new(@api_uri).post(path: path, head: headers, body: body, ssl: ssl_opts) when 'DELETE' req = EM::HttpRequest.new(@api_uri).delete(path: path, head: headers, ssl: ssl_opts) else fail end req.callback do |resp| case resp.response_header.status when 200 then yield(EMHTTPResponse.new(resp)) when 400 then fail BadRequestError, resp.response when 401 then fail NotAuthorizedError, resp.response when 403 then fail ForbiddenError, resp.response when 404 then fail NotFoundError, resp.response when 429 then fail RateLimitError, resp.response when 500 then fail InternalServerError, resp.response end end req.errback do |resp| fail APIError, "#{method} #{@api_uri}#{path}: #{resp.error}" end end end end # EM-Http response object class EMHTTPResponse < APIResponse def body @response.response end def headers out = @response.response_header.map do |key, val| [ key.upcase.gsub('_', '-'), val ] end out.to_h end def status @response.response_header.status end end end end
ruby
Apache-2.0
3e01d2ea5ade324bec82233ca29304c80b1058d2
2026-01-04T17:55:58.161349Z
false
coinbase/coinbase-exchange-ruby
https://github.com/coinbase/coinbase-exchange-ruby/blob/3e01d2ea5ade324bec82233ca29304c80b1058d2/lib/coinbase/exchange/adapters/net_http.rb
lib/coinbase/exchange/adapters/net_http.rb
module Coinbase module Exchange # Net-HTTP adapter class NetHTTPClient < APIClient def initialize(api_key = '', api_secret = '', api_pass = '', options = {}) super(api_key, api_secret, api_pass, options) @conn = Net::HTTP.new(@api_uri.host, @api_uri.port) @conn.use_ssl = true if @api_uri.scheme == 'https' @conn.cert_store = self.class.whitelisted_certificates @conn.ssl_version = :TLSv1 end private def http_verb(method, path, body = nil) case method when 'GET' then req = Net::HTTP::Get.new(path) when 'POST' then req = Net::HTTP::Post.new(path) when 'DELETE' then req = Net::HTTP::Delete.new(path) else fail end req.body = body req_ts = Time.now.utc.to_i.to_s signature = Base64.encode64( OpenSSL::HMAC.digest('sha256', Base64.decode64(@api_secret).strip, "#{req_ts}#{method}#{path}#{body}")).strip req['Content-Type'] = 'application/json' req['CB-ACCESS-TIMESTAMP'] = req_ts req['CB-ACCESS-PASSPHRASE'] = @api_pass req['CB-ACCESS-KEY'] = @api_key req['CB-ACCESS-SIGN'] = signature resp = @conn.request(req) case resp.code when "200" then yield(NetHTTPResponse.new(resp)) when "400" then fail BadRequestError, resp.body when "401" then fail NotAuthorizedError, resp.body when "403" then fail ForbiddenError, resp.body when "404" then fail NotFoundError, resp.body when "429" then fail RateLimitError, resp.body when "500" then fail InternalServerError, resp.body end resp.body end end # Net-Http response object class NetHTTPResponse < APIResponse def body @response.body end def headers out = @response.to_hash.map do |key, val| [ key.upcase.gsub('_', '-'), val.count == 1 ? val.first : val ] end out.to_h end def status @response.code.to_i end end end end
ruby
Apache-2.0
3e01d2ea5ade324bec82233ca29304c80b1058d2
2026-01-04T17:55:58.161349Z
false
mydrive/capistrano-deploytags
https://github.com/mydrive/capistrano-deploytags/blob/6ef8f3ec466a1374cd0257de7d66e8063938d0e2/spec/capistrano_deploy_tags_spec.rb
spec/capistrano_deploy_tags_spec.rb
require 'rspec' describe 'Capistrano::Deploytags' do pending "capistrano-spec doesn't support Capistrano 3" end
ruby
BSD-2-Clause
6ef8f3ec466a1374cd0257de7d66e8063938d0e2
2026-01-04T17:55:58.084597Z
false
mydrive/capistrano-deploytags
https://github.com/mydrive/capistrano-deploytags/blob/6ef8f3ec466a1374cd0257de7d66e8063938d0e2/lib/capistrano-deploytags.rb
lib/capistrano-deploytags.rb
ruby
BSD-2-Clause
6ef8f3ec466a1374cd0257de7d66e8063938d0e2
2026-01-04T17:55:58.084597Z
false
mydrive/capistrano-deploytags
https://github.com/mydrive/capistrano-deploytags/blob/6ef8f3ec466a1374cd0257de7d66e8063938d0e2/lib/capistrano/deploytags.rb
lib/capistrano/deploytags.rb
# Ensure deploy tasks are loaded before we run require 'capistrano/deploy' # Load extra tasks into the deploy namespace load File.expand_path("../tasks/deploytags.rake", __FILE__) module CapistranoDeploytags class Helper def self.git_tag_for(stage) "#{stage}-#{formatted_time}" end def self.formatted_time now = if fetch(:deploytag_utc, true) Time.now.utc else Time.now end now.strftime(fetch(:deploytag_time_format, "%Y.%m.%d-%H%M%S-#{now.zone.downcase}")) end def self.commit_message(current_sha, stage) if fetch(:deploytag_commit_message, false) fetch(:deploytag_commit_message) else tag_user = (ENV['USER'] || ENV['USERNAME'] || 'deployer').strip "#{tag_user} deployed #{current_sha} to #{stage}" end end end end
ruby
BSD-2-Clause
6ef8f3ec466a1374cd0257de7d66e8063938d0e2
2026-01-04T17:55:58.084597Z
false
benbalter/jekyll-include-cache
https://github.com/benbalter/jekyll-include-cache/blob/e5613acbf297bc8f8bbac19959b3544ce3485f61/spec/jekyll-include-tag_spec.rb
spec/jekyll-include-tag_spec.rb
# frozen_string_literal: true RSpec.describe JekyllIncludeCache do subject { described_class.cache } context "with an empty cache" do it "initializess the cache" do expect(described_class.cache).to respond_to(:[]) expect(described_class.cache).to respond_to(:[]=) end end context "with something cached" do before { subject["foo"] = "bar" } it "caches" do expect(subject.key?("foo")).to be_truthy end it "returns the cache" do expect(subject["foo"]).to eql("bar") end end context "clearing the cache on render" do let(:site) { fixture_site("site") } before do subject["foo"] = "bar" Jekyll::Hooks.trigger :site, :pre_render, site, site.site_payload end it "clears the cache" do expect(subject.key?("foo")).not_to be_truthy end end end
ruby
MIT
e5613acbf297bc8f8bbac19959b3544ce3485f61
2026-01-04T17:56:02.584063Z
false
benbalter/jekyll-include-cache
https://github.com/benbalter/jekyll-include-cache/blob/e5613acbf297bc8f8bbac19959b3544ce3485f61/spec/spec_helper.rb
spec/spec_helper.rb
# frozen_string_literal: true require "jekyll-include-cache" RSpec.configure do |config| config.expect_with :rspec do |expectations| expectations.include_chain_clauses_in_custom_matcher_descriptions = true end config.mock_with :rspec do |mocks| mocks.verify_partial_doubles = true end config.filter_run_when_matching :focus config.example_status_persistence_file_path = "spec/examples.txt" config.disable_monkey_patching! config.default_formatter = "doc" if config.files_to_run.one? config.order = :random Kernel.srand config.seed end Jekyll.logger.adjust_verbosity(:quiet => true) Jekyll::Cache.cache_dir = File.expand_path("../tmp", __dir__) if defined? Jekyll::Cache def fixture_path(fixture) File.expand_path "./fixtures/#{fixture}", File.dirname(__FILE__) end def fixture_site(fixture, override = {}) default_config = { "source" => fixture_path(fixture) } config = Jekyll::Utils.deep_merge_hashes(default_config, override) config = Jekyll.configuration(config) Jekyll::Site.new(config) end
ruby
MIT
e5613acbf297bc8f8bbac19959b3544ce3485f61
2026-01-04T17:56:02.584063Z
false
benbalter/jekyll-include-cache
https://github.com/benbalter/jekyll-include-cache/blob/e5613acbf297bc8f8bbac19959b3544ce3485f61/spec/jekyll-include-tag/tag_spec.rb
spec/jekyll-include-tag/tag_spec.rb
# frozen_string_literal: true RSpec.describe JekyllIncludeCache::Tag do subject { described_class.send(:new, tag_name, markup, parse_context) } let(:tag_name) { "include_cached" } let(:cache) { JekyllIncludeCache.cache } let(:path) { subject.send(:path, context) } let(:parsed_params) { subject.parse_params(context) } let(:cache_key) { subject.send(:key, path, parsed_params) } let(:file_path) { "foo.html" } let(:params) { "foo=bar foo2=bar2" } let(:markup) { "#{file_path} #{params}" } let(:overrides) { {} } let(:site) { fixture_site("site", overrides) } let(:environments) { {} } let(:outer_scope) { {} } let(:registers) { { :site => site } } let(:context) { Liquid::Context.new(environments, outer_scope, registers) } let(:parse_context) { Liquid::ParseContext.new } it "determines the path" do expected = File.expand_path "../fixtures/site/_includes/foo.html", __dir__ expect(path).to eql(expected) end context "building the key" do it "builds the key" do key = subject.send(:key, "foo.html", "foo" => "bar", "foo2" => "bar2") params = { "foo" => "bar", "foo2" => "bar2" } expect(key).to eql( subject.send(:digest, "foo.html".hash, subject.send(:quick_hash, params)) ) end it "builds the key based on the path" do key = subject.send(:key, "foo2.html", "foo" => "bar", "foo2" => "bar2") params = { "foo" => "bar", "foo2" => "bar2" } expect(key).to eql( subject.send(:digest, "foo2.html".hash, subject.send(:quick_hash, params)) ) end it "builds the key based on the params" do key = subject.send(:key, "foo2.html", "foo" => "bar") params = { "foo" => "bar" } expect(key).to eql(subject.send(:digest, "foo2.html".hash, subject.send(:quick_hash, params))) end end context "rendering" do before { subject.render(context) } let(:rendered) { subject.render(context) } it "renders" do expect(rendered).to eql("Some content\n") end it "caches the include" do expect(cache.key?(cache_key)).to be_truthy expect(cache[cache_key]).to eql("Some content\n") end context "with the cache stubbed" do before { allow(subject).to receive(:key).and_return(cache_key) } before { cache[cache_key] = "Some other content\n" } let(:cache_key) { "asdf" } it "returns the cached value" do expect(rendered).to eql("Some other content\n") end end end context "with an invalid include" do let(:file_path) { "foo2.html" } it "raises an error" do expect { subject.render(context) }.to raise_error(IOError) end end end
ruby
MIT
e5613acbf297bc8f8bbac19959b3544ce3485f61
2026-01-04T17:56:02.584063Z
false
benbalter/jekyll-include-cache
https://github.com/benbalter/jekyll-include-cache/blob/e5613acbf297bc8f8bbac19959b3544ce3485f61/spec/jekyll-include-tag/cache_spec.rb
spec/jekyll-include-tag/cache_spec.rb
# frozen_string_literal: true RSpec.describe JekyllIncludeCache::Cache do before { subject["foo"] = "bar" } it "sets" do subject["foo2"] = "bar2" cache = subject.instance_variable_get("@cache") expect(cache["foo2"]).to eql("bar2") end it "gets" do expect(subject["foo"]).to eql("bar") end it "raises when a key doesn't exist" do expect { subject["doesnt_exist"] }.to raise_error(RuntimeError) end it "knows if a key exists" do expect(subject.key?("foo")).to be_truthy expect(subject.key?("bar")).to be_falsy end it "deletes" do subject["foo2"] = "bar2" expect(subject.key?("foo2")).to be_truthy subject.delete("foo2") expect(subject.key?("foo2")).to be_falsy end it "clears" do expect(subject.key?("foo")).to be_truthy subject.clear cache = subject.instance_variable_get("@cache") expect(cache).to eql({}) end context "getset" do it "returns an existing value" do value = subject.getset "foo" do "bar2" end expect(value).to eql("bar") end it "sets a new value" do value = subject.getset "foo3" do "bar3" end expect(value).to eql("bar3") expect(subject["foo3"]).to eql("bar3") end end end
ruby
MIT
e5613acbf297bc8f8bbac19959b3544ce3485f61
2026-01-04T17:56:02.584063Z
false
benbalter/jekyll-include-cache
https://github.com/benbalter/jekyll-include-cache/blob/e5613acbf297bc8f8bbac19959b3544ce3485f61/lib/jekyll-include-cache.rb
lib/jekyll-include-cache.rb
# frozen_string_literal: true require "jekyll" module JekyllIncludeCache autoload :Tag, "jekyll-include-cache/tag" autoload :Cache, "jekyll-include-cache/cache" class << self def cache @cache ||= if defined? Jekyll::Cache Jekyll::Cache.new(self.class.name) else JekyllIncludeCache::Cache.new end end def reset JekyllIncludeCache.cache.clear end end end Liquid::Template.register_tag("include_cached", JekyllIncludeCache::Tag) Jekyll::Hooks.register :site, :pre_render do |_site| JekyllIncludeCache.reset end
ruby
MIT
e5613acbf297bc8f8bbac19959b3544ce3485f61
2026-01-04T17:56:02.584063Z
false
benbalter/jekyll-include-cache
https://github.com/benbalter/jekyll-include-cache/blob/e5613acbf297bc8f8bbac19959b3544ce3485f61/lib/jekyll-include-cache/tag.rb
lib/jekyll-include-cache/tag.rb
# frozen_string_literal: true require "digest/md5" module JekyllIncludeCache class Tag < Jekyll::Tags::IncludeTag def self.digest_cache @digest_cache ||= {} end def render(context) path = path(context) params = parse_params(context) if @params key = key(path, params) return unless path if JekyllIncludeCache.cache.key?(key) Jekyll.logger.debug "Include cache hit:", path JekyllIncludeCache.cache[key] else Jekyll.logger.debug "Include cache miss:", path JekyllIncludeCache.cache[key] = super end end private def path(context) site = context.registers[:site] file = render_variable(context) || @file locate_include_file(context, file, site.safe) end def key(path, params) path_hash = path.hash params_hash = quick_hash(params) self.class.digest_cache[path_hash] ||= {} self.class.digest_cache[path_hash][params_hash] ||= digest(path_hash, params_hash) end def quick_hash(params) return params.hash unless params md5 = Digest::MD5.new params.sort.each do |_, value| # Using the fact that Jekyll documents don't change during a build. # Instead of calculating the hash of an entire document (expensive!) # we just use its object id. if value.is_a? Jekyll::Drops::Drop md5.update value.object_id.to_s else md5.update value.hash.to_s end end md5.hexdigest end def digest(path_hash, params_hash) md5 = Digest::MD5.new md5.update path_hash.to_s md5.update params_hash.to_s md5.hexdigest end end end
ruby
MIT
e5613acbf297bc8f8bbac19959b3544ce3485f61
2026-01-04T17:56:02.584063Z
false
benbalter/jekyll-include-cache
https://github.com/benbalter/jekyll-include-cache/blob/e5613acbf297bc8f8bbac19959b3544ce3485f61/lib/jekyll-include-cache/version.rb
lib/jekyll-include-cache/version.rb
# frozen_string_literal: true module JekyllIncludeCache VERSION = "0.2.1" end
ruby
MIT
e5613acbf297bc8f8bbac19959b3544ce3485f61
2026-01-04T17:56:02.584063Z
false
benbalter/jekyll-include-cache
https://github.com/benbalter/jekyll-include-cache/blob/e5613acbf297bc8f8bbac19959b3544ce3485f61/lib/jekyll-include-cache/cache.rb
lib/jekyll-include-cache/cache.rb
# frozen_string_literal: true # Jekyll 4.x comptable caching class for pre-4.x compatibility module JekyllIncludeCache class Cache extend Forwardable def_delegators :@cache, :[]=, :key?, :delete, :clear def initialize(_name = nil) @cache = {} end def getset(key) if key?(key) @cache[key] else value = yield @cache[key] = value value end end def [](key) if key?(key) @cache[key] else raise end end end end
ruby
MIT
e5613acbf297bc8f8bbac19959b3544ce3485f61
2026-01-04T17:56:02.584063Z
false
dao42/browser_warrior
https://github.com/dao42/browser_warrior/blob/38aad349679c38a38b3adfa9a125aac47393ba92/test/test_helper.rb
test/test_helper.rb
# Configure Rails Environment ENV["RAILS_ENV"] = "test" require File.expand_path("../../test/dummy/config/environment.rb", __FILE__) #ActiveRecord::Migrator.migrations_paths = [File.expand_path("../../test/dummy/db/migrate", __FILE__)] #ActiveRecord::Migrator.migrations_paths << File.expand_path('../../db/migrate', __FILE__) require "rails/test_help" # Filter out Minitest backtrace while allowing backtrace from other libraries # to be shown. Minitest.backtrace_filter = Minitest::BacktraceFilter.new # Load fixtures from the engine if ActiveSupport::TestCase.respond_to?(:fixture_path=) ActiveSupport::TestCase.fixture_path = File.expand_path("../fixtures", __FILE__) ActionDispatch::IntegrationTest.fixture_path = ActiveSupport::TestCase.fixture_path ActiveSupport::TestCase.file_fixture_path = ActiveSupport::TestCase.fixture_path + "/files" ActiveSupport::TestCase.fixtures :all end
ruby
MIT
38aad349679c38a38b3adfa9a125aac47393ba92
2026-01-04T17:55:59.897926Z
false
dao42/browser_warrior
https://github.com/dao42/browser_warrior/blob/38aad349679c38a38b3adfa9a125aac47393ba92/test/dummy/app/jobs/application_job.rb
test/dummy/app/jobs/application_job.rb
class ApplicationJob < ActiveJob::Base end
ruby
MIT
38aad349679c38a38b3adfa9a125aac47393ba92
2026-01-04T17:55:59.897926Z
false
dao42/browser_warrior
https://github.com/dao42/browser_warrior/blob/38aad349679c38a38b3adfa9a125aac47393ba92/test/dummy/app/helpers/application_helper.rb
test/dummy/app/helpers/application_helper.rb
module ApplicationHelper end
ruby
MIT
38aad349679c38a38b3adfa9a125aac47393ba92
2026-01-04T17:55:59.897926Z
false
dao42/browser_warrior
https://github.com/dao42/browser_warrior/blob/38aad349679c38a38b3adfa9a125aac47393ba92/test/dummy/app/controllers/visitors_controller.rb
test/dummy/app/controllers/visitors_controller.rb
class VisitorsController < ApplicationController def index if params[:zh].present? I18n.locale = 'zh-CN' end end end
ruby
MIT
38aad349679c38a38b3adfa9a125aac47393ba92
2026-01-04T17:55:59.897926Z
false
dao42/browser_warrior
https://github.com/dao42/browser_warrior/blob/38aad349679c38a38b3adfa9a125aac47393ba92/test/dummy/app/controllers/application_controller.rb
test/dummy/app/controllers/application_controller.rb
class ApplicationController < ActionController::Base protect_from_forgery with: :exception prepend_before_action :set_locale def set_locale if params[:zh].present? I18n.locale = :'zh-CN' else I18n.locale = :'en' end end end
ruby
MIT
38aad349679c38a38b3adfa9a125aac47393ba92
2026-01-04T17:55:59.897926Z
false
dao42/browser_warrior
https://github.com/dao42/browser_warrior/blob/38aad349679c38a38b3adfa9a125aac47393ba92/test/dummy/app/models/application_record.rb
test/dummy/app/models/application_record.rb
class ApplicationRecord < ActiveRecord::Base self.abstract_class = true end
ruby
MIT
38aad349679c38a38b3adfa9a125aac47393ba92
2026-01-04T17:55:59.897926Z
false
dao42/browser_warrior
https://github.com/dao42/browser_warrior/blob/38aad349679c38a38b3adfa9a125aac47393ba92/test/dummy/app/mailers/application_mailer.rb
test/dummy/app/mailers/application_mailer.rb
class ApplicationMailer < ActionMailer::Base default from: 'from@example.com' layout 'mailer' end
ruby
MIT
38aad349679c38a38b3adfa9a125aac47393ba92
2026-01-04T17:55:59.897926Z
false
dao42/browser_warrior
https://github.com/dao42/browser_warrior/blob/38aad349679c38a38b3adfa9a125aac47393ba92/test/dummy/app/channels/application_cable/channel.rb
test/dummy/app/channels/application_cable/channel.rb
module ApplicationCable class Channel < ActionCable::Channel::Base end end
ruby
MIT
38aad349679c38a38b3adfa9a125aac47393ba92
2026-01-04T17:55:59.897926Z
false
dao42/browser_warrior
https://github.com/dao42/browser_warrior/blob/38aad349679c38a38b3adfa9a125aac47393ba92/test/dummy/app/channels/application_cable/connection.rb
test/dummy/app/channels/application_cable/connection.rb
module ApplicationCable class Connection < ActionCable::Connection::Base end end
ruby
MIT
38aad349679c38a38b3adfa9a125aac47393ba92
2026-01-04T17:55:59.897926Z
false
dao42/browser_warrior
https://github.com/dao42/browser_warrior/blob/38aad349679c38a38b3adfa9a125aac47393ba92/test/dummy/test/controllers/visitors_controller_test.rb
test/dummy/test/controllers/visitors_controller_test.rb
require 'test_helper' class VisitorsControllerTest < ActionDispatch::IntegrationTest test "should get index" do get root_url assert_response :success end end
ruby
MIT
38aad349679c38a38b3adfa9a125aac47393ba92
2026-01-04T17:55:59.897926Z
false
dao42/browser_warrior
https://github.com/dao42/browser_warrior/blob/38aad349679c38a38b3adfa9a125aac47393ba92/test/dummy/config/application.rb
test/dummy/config/application.rb
require_relative 'boot' require "action_controller/railtie" require "action_mailer/railtie" require "sprockets/railtie" require "rails/test_unit/railtie" require 'action_cable/engine' Bundler.require(*Rails.groups) require "browser_warrior" module Dummy class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. config.i18n.available_locales = ['zh-CN', 'en'] config.i18n.default_locale = 'zh-CN' end end
ruby
MIT
38aad349679c38a38b3adfa9a125aac47393ba92
2026-01-04T17:55:59.897926Z
false
dao42/browser_warrior
https://github.com/dao42/browser_warrior/blob/38aad349679c38a38b3adfa9a125aac47393ba92/test/dummy/config/environment.rb
test/dummy/config/environment.rb
# Load the Rails application. require_relative 'application' # Initialize the Rails application. Rails.application.initialize!
ruby
MIT
38aad349679c38a38b3adfa9a125aac47393ba92
2026-01-04T17:55:59.897926Z
false
dao42/browser_warrior
https://github.com/dao42/browser_warrior/blob/38aad349679c38a38b3adfa9a125aac47393ba92/test/dummy/config/puma.rb
test/dummy/config/puma.rb
# Puma can serve each request in a thread from an internal thread pool. # The `threads` method setting takes two numbers a minimum and maximum. # Any libraries that use thread pools should be configured to match # the maximum value specified for Puma. Default is set to 5 threads for minimum # and maximum, this matches the default thread size of Active Record. # threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 }.to_i threads threads_count, threads_count # Specifies the `port` that Puma will listen on to receive requests, default is 3000. # port ENV.fetch("PORT") { 3000 } # Specifies the `environment` that Puma will run in. # environment ENV.fetch("RAILS_ENV") { "development" } # Specifies the number of `workers` to boot in clustered mode. # Workers are forked webserver processes. If using threads and workers together # the concurrency of the application would be max `threads` * `workers`. # Workers do not work on JRuby or Windows (both of which do not support # processes). # # workers ENV.fetch("WEB_CONCURRENCY") { 2 } # Use the `preload_app!` method when specifying a `workers` number. # This directive tells Puma to first boot the application and load code # before forking the application. This takes advantage of Copy On Write # process behavior so workers use less memory. If you use this option # you need to make sure to reconnect any threads in the `on_worker_boot` # block. # # preload_app! # The code in the `on_worker_boot` will be called if you are using # clustered mode by specifying a number of `workers`. After each worker # process is booted this block will be run, if you are using `preload_app!` # option you will want to use this block to reconnect to any threads # or connections that may have been created at application boot, Ruby # cannot share connections between processes. # # on_worker_boot do # ActiveRecord::Base.establish_connection if defined?(ActiveRecord) # end # Allow puma to be restarted by `rails restart` command. plugin :tmp_restart
ruby
MIT
38aad349679c38a38b3adfa9a125aac47393ba92
2026-01-04T17:55:59.897926Z
false
dao42/browser_warrior
https://github.com/dao42/browser_warrior/blob/38aad349679c38a38b3adfa9a125aac47393ba92/test/dummy/config/routes.rb
test/dummy/config/routes.rb
Rails.application.routes.draw do root 'visitors#index' end
ruby
MIT
38aad349679c38a38b3adfa9a125aac47393ba92
2026-01-04T17:55:59.897926Z
false
dao42/browser_warrior
https://github.com/dao42/browser_warrior/blob/38aad349679c38a38b3adfa9a125aac47393ba92/test/dummy/config/spring.rb
test/dummy/config/spring.rb
%w( .ruby-version .rbenv-vars tmp/restart.txt tmp/caching-dev.txt ).each { |path| Spring.watch(path) }
ruby
MIT
38aad349679c38a38b3adfa9a125aac47393ba92
2026-01-04T17:55:59.897926Z
false
dao42/browser_warrior
https://github.com/dao42/browser_warrior/blob/38aad349679c38a38b3adfa9a125aac47393ba92/test/dummy/config/boot.rb
test/dummy/config/boot.rb
# Set up gems listed in the Gemfile. ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../Gemfile', __dir__) require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE']) $LOAD_PATH.unshift File.expand_path('../../../lib', __dir__)
ruby
MIT
38aad349679c38a38b3adfa9a125aac47393ba92
2026-01-04T17:55:59.897926Z
false
dao42/browser_warrior
https://github.com/dao42/browser_warrior/blob/38aad349679c38a38b3adfa9a125aac47393ba92/test/dummy/config/initializers/filter_parameter_logging.rb
test/dummy/config/initializers/filter_parameter_logging.rb
# Be sure to restart your server when you modify this file. # Configure sensitive parameters which will be filtered from the log file. Rails.application.config.filter_parameters += [:password]
ruby
MIT
38aad349679c38a38b3adfa9a125aac47393ba92
2026-01-04T17:55:59.897926Z
false
dao42/browser_warrior
https://github.com/dao42/browser_warrior/blob/38aad349679c38a38b3adfa9a125aac47393ba92/test/dummy/config/initializers/application_controller_renderer.rb
test/dummy/config/initializers/application_controller_renderer.rb
# Be sure to restart your server when you modify this file. # ApplicationController.renderer.defaults.merge!( # http_host: 'example.org', # https: false # )
ruby
MIT
38aad349679c38a38b3adfa9a125aac47393ba92
2026-01-04T17:55:59.897926Z
false
dao42/browser_warrior
https://github.com/dao42/browser_warrior/blob/38aad349679c38a38b3adfa9a125aac47393ba92/test/dummy/config/initializers/session_store.rb
test/dummy/config/initializers/session_store.rb
# Be sure to restart your server when you modify this file. Rails.application.config.session_store :cookie_store, key: '_dummy_session'
ruby
MIT
38aad349679c38a38b3adfa9a125aac47393ba92
2026-01-04T17:55:59.897926Z
false
dao42/browser_warrior
https://github.com/dao42/browser_warrior/blob/38aad349679c38a38b3adfa9a125aac47393ba92/test/dummy/config/initializers/wrap_parameters.rb
test/dummy/config/initializers/wrap_parameters.rb
# Be sure to restart your server when you modify this file. # This file contains settings for ActionController::ParamsWrapper which # is enabled by default. # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. ActiveSupport.on_load(:action_controller) do wrap_parameters format: [:json] end # To enable root element in JSON for ActiveRecord objects. # ActiveSupport.on_load(:active_record) do # self.include_root_in_json = true # end
ruby
MIT
38aad349679c38a38b3adfa9a125aac47393ba92
2026-01-04T17:55:59.897926Z
false
dao42/browser_warrior
https://github.com/dao42/browser_warrior/blob/38aad349679c38a38b3adfa9a125aac47393ba92/test/dummy/config/initializers/inflections.rb
test/dummy/config/initializers/inflections.rb
# Be sure to restart your server when you modify this file. # Add new inflection rules using the following format. Inflections # are locale specific, and you may define rules for as many different # locales as you wish. All of these examples are active by default: # ActiveSupport::Inflector.inflections(:en) do |inflect| # inflect.plural /^(ox)$/i, '\1en' # inflect.singular /^(ox)en/i, '\1' # inflect.irregular 'person', 'people' # inflect.uncountable %w( fish sheep ) # end # These inflection rules are supported but not enabled by default: # ActiveSupport::Inflector.inflections(:en) do |inflect| # inflect.acronym 'RESTful' # end
ruby
MIT
38aad349679c38a38b3adfa9a125aac47393ba92
2026-01-04T17:55:59.897926Z
false
dao42/browser_warrior
https://github.com/dao42/browser_warrior/blob/38aad349679c38a38b3adfa9a125aac47393ba92/test/dummy/config/initializers/cookies_serializer.rb
test/dummy/config/initializers/cookies_serializer.rb
# Be sure to restart your server when you modify this file. # Specify a serializer for the signed and encrypted cookie jars. # Valid options are :json, :marshal, and :hybrid. Rails.application.config.action_dispatch.cookies_serializer = :json
ruby
MIT
38aad349679c38a38b3adfa9a125aac47393ba92
2026-01-04T17:55:59.897926Z
false
dao42/browser_warrior
https://github.com/dao42/browser_warrior/blob/38aad349679c38a38b3adfa9a125aac47393ba92/test/dummy/config/initializers/assets.rb
test/dummy/config/initializers/assets.rb
# Be sure to restart your server when you modify this file. # Version of your assets, change this if you want to expire all your assets. Rails.application.config.assets.version = '1.0' # Add additional assets to the asset load path # Rails.application.config.assets.paths << Emoji.images_path # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in app/assets folder are already added. # Rails.application.config.assets.precompile += %w( search.js )
ruby
MIT
38aad349679c38a38b3adfa9a125aac47393ba92
2026-01-04T17:55:59.897926Z
false
dao42/browser_warrior
https://github.com/dao42/browser_warrior/blob/38aad349679c38a38b3adfa9a125aac47393ba92/test/dummy/config/initializers/backtrace_silencers.rb
test/dummy/config/initializers/backtrace_silencers.rb
# Be sure to restart your server when you modify this file. # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. # Rails.backtrace_cleaner.remove_silencers!
ruby
MIT
38aad349679c38a38b3adfa9a125aac47393ba92
2026-01-04T17:55:59.897926Z
false
dao42/browser_warrior
https://github.com/dao42/browser_warrior/blob/38aad349679c38a38b3adfa9a125aac47393ba92/test/dummy/config/initializers/mime_types.rb
test/dummy/config/initializers/mime_types.rb
# Be sure to restart your server when you modify this file. # Add new mime types for use in respond_to blocks: # Mime::Type.register "text/richtext", :rtf
ruby
MIT
38aad349679c38a38b3adfa9a125aac47393ba92
2026-01-04T17:55:59.897926Z
false
dao42/browser_warrior
https://github.com/dao42/browser_warrior/blob/38aad349679c38a38b3adfa9a125aac47393ba92/test/dummy/config/environments/test.rb
test/dummy/config/environments/test.rb
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! config.cache_classes = true # Do not eager load code on boot. This avoids loading your whole application # just for the purpose of running a single test. If you are using a tool that # preloads Rails for running tests, you may have to set it to true. config.eager_load = false # Configure public file server for tests with Cache-Control for performance. config.public_file_server.enabled = true config.public_file_server.headers = { 'Cache-Control' => 'public, max-age=3600' } # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Raise exceptions instead of rendering exception templates. config.action_dispatch.show_exceptions = false # Disable request forgery protection in test environment. config.action_controller.allow_forgery_protection = false config.action_mailer.perform_caching = false # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the # ActionMailer::Base.deliveries array. config.action_mailer.delivery_method = :test # Print deprecation notices to the stderr. config.active_support.deprecation = :stderr # Raises error for missing translations # config.action_view.raise_on_missing_translations = true end
ruby
MIT
38aad349679c38a38b3adfa9a125aac47393ba92
2026-01-04T17:55:59.897926Z
false
dao42/browser_warrior
https://github.com/dao42/browser_warrior/blob/38aad349679c38a38b3adfa9a125aac47393ba92/test/dummy/config/environments/development.rb
test/dummy/config/environments/development.rb
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports. config.consider_all_requests_local = true # Enable/disable caching. By default caching is disabled. if Rails.root.join('tmp/caching-dev.txt').exist? config.action_controller.perform_caching = true config.cache_store = :memory_store config.public_file_server.headers = { 'Cache-Control' => 'public, max-age=172800' } else config.action_controller.perform_caching = false config.cache_store = :null_store end # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false config.action_mailer.perform_caching = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = false # Suppress logger output for asset requests. config.assets.quiet = true # Raises error for missing translations # config.action_view.raise_on_missing_translations = true # Use an evented file watcher to asynchronously detect changes in source code, # routes, locales, etc. This feature depends on the listen gem. # config.file_watcher = ActiveSupport::EventedFileUpdateChecker end
ruby
MIT
38aad349679c38a38b3adfa9a125aac47393ba92
2026-01-04T17:55:59.897926Z
false
dao42/browser_warrior
https://github.com/dao42/browser_warrior/blob/38aad349679c38a38b3adfa9a125aac47393ba92/test/dummy/config/environments/production.rb
test/dummy/config/environments/production.rb
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? # Compress JavaScripts and CSS. config.assets.js_compressor = :uglifier # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = false # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = 'http://assets.example.com' # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX # Mount Action Cable outside main process or domain # config.action_cable.mount_path = nil # config.action_cable.url = 'wss://example.com/cable' # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Use the lowest log level to ensure availability of diagnostic information # when problems arise. config.log_level = :debug # Prepend all log lines with the following tags. config.log_tags = [ :request_id ] # Use a different cache store in production. # config.cache_store = :mem_cache_store # Use a real queuing backend for Active Job (and separate queues per environment) # config.active_job.queue_adapter = :resque # config.active_job.queue_name_prefix = "dummy_#{Rails.env}" config.action_mailer.perform_caching = false # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Use a different logger for distributed setups. # require 'syslog/logger' # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') if ENV["RAILS_LOG_TO_STDOUT"].present? logger = ActiveSupport::Logger.new(STDOUT) logger.formatter = config.log_formatter config.logger = ActiveSupport::TaggedLogging.new(logger) end # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false end
ruby
MIT
38aad349679c38a38b3adfa9a125aac47393ba92
2026-01-04T17:55:59.897926Z
false
dao42/browser_warrior
https://github.com/dao42/browser_warrior/blob/38aad349679c38a38b3adfa9a125aac47393ba92/lib/browser_warrior.rb
lib/browser_warrior.rb
require "browser_warrior/engine" require 'browser/version' require 'browser' module BrowserWarrior ROOT = File.expand_path(File.join( File.dirname(__FILE__), '..')) module Controllers module Helpers extend ActiveSupport::Concern included do before_action :check_browser_warrior! if BrowserWarrior.autoenable end def check_browser_warrior! # ignore rails inline controller if params[:controller] == 'rails/welcome' return end # ignore no html controller if params[:format].present? && params[:format] != :html return end # ignore non-get request if ! request.get? return end browser = ::Browser.new(request.user_agent) if ! BrowserWarrior.do_detect(browser) render 'browser_warrior/index', layout: false end end end end @detect_block = lambda do |browser| next true if Rails.env.test? next true if browser.bot? next true unless browser.known? # Allow weixin callback next true if browser.platform.other? # See https://github.com/fnando/browser#usage for more usage next true if browser.wechat? next true if browser.weibo? next true if browser.facebook? # Block known non-modern browser next false if browser.chrome?("<= 65") next false if browser.safari?("< 10") next false if browser.firefox?("< 52") next false if browser.ie?("< 11") next false if browser.edge?("< 15") next false if browser.opera?("< 50") # Allow by default next true end @@autoenable = true mattr_accessor :autoenable def self.detect(&block) @detect_block = block end def self.do_detect(browser) @detect_block.call(browser) end end
ruby
MIT
38aad349679c38a38b3adfa9a125aac47393ba92
2026-01-04T17:55:59.897926Z
false
dao42/browser_warrior
https://github.com/dao42/browser_warrior/blob/38aad349679c38a38b3adfa9a125aac47393ba92/lib/browser_warrior/version.rb
lib/browser_warrior/version.rb
module BrowserWarrior VERSION = '0.14.0' end
ruby
MIT
38aad349679c38a38b3adfa9a125aac47393ba92
2026-01-04T17:55:59.897926Z
false
dao42/browser_warrior
https://github.com/dao42/browser_warrior/blob/38aad349679c38a38b3adfa9a125aac47393ba92/lib/browser_warrior/engine.rb
lib/browser_warrior/engine.rb
module BrowserWarrior class Engine < ::Rails::Engine initializer "browser_warrior.helprs" do ActiveSupport.on_load(:action_controller) do include BrowserWarrior::Controllers::Helpers end end end end
ruby
MIT
38aad349679c38a38b3adfa9a125aac47393ba92
2026-01-04T17:55:59.897926Z
false
dao42/browser_warrior
https://github.com/dao42/browser_warrior/blob/38aad349679c38a38b3adfa9a125aac47393ba92/lib/generators/browser_warrior/views/views_generator.rb
lib/generators/browser_warrior/views/views_generator.rb
module BrowserWarrior module Generators class ViewsGenerator < Rails::Generators::Base source_root ::BrowserWarrior::ROOT desc "Copy views & css files into main app" def copy_views copy_file "app/views/browser_warrior/index.html.erb", "app/views/browser_warrior/index.html.erb" copy_file "app/views/browser_warrior/index.en.html.erb", "app/views/browser_warrior/index.en.html.erb" end def copy_css_image copy_file "app/assets/stylesheets/browser_warrior/application.scss", "app/assets/stylesheets/browser_warrior/application.scss" copy_file "app/assets/images/browser_warrior/chrome.png", "app/assets/images/browser_warrior/chrome.png" copy_file "app/assets/images/browser_warrior/firefox.png", "app/assets/images/browser_warrior/firefox.png" copy_file "app/assets/images/browser_warrior/ie.png", "app/assets/images/browser_warrior/ie.png" copy_file "app/assets/images/browser_warrior/opera.png", "app/assets/images/browser_warrior/opera.png" end end end end
ruby
MIT
38aad349679c38a38b3adfa9a125aac47393ba92
2026-01-04T17:55:59.897926Z
false
dao42/browser_warrior
https://github.com/dao42/browser_warrior/blob/38aad349679c38a38b3adfa9a125aac47393ba92/lib/generators/browser_warrior/install/install_generator.rb
lib/generators/browser_warrior/install/install_generator.rb
module BrowserWarrior module Generators class InstallGenerator < Rails::Generators::Base source_root File.expand_path('../templates', __FILE__) desc "Create a browser_warrior initializer" def copy_initializer template "browser_warrior.rb", "config/initializers/browser_warrior.rb" end end end end
ruby
MIT
38aad349679c38a38b3adfa9a125aac47393ba92
2026-01-04T17:55:59.897926Z
false
dao42/browser_warrior
https://github.com/dao42/browser_warrior/blob/38aad349679c38a38b3adfa9a125aac47393ba92/lib/generators/browser_warrior/install/templates/browser_warrior.rb
lib/generators/browser_warrior/install/templates/browser_warrior.rb
BrowserWarrior.detect do |browser| next true if Rails.env.test? next true if browser.bot? next true unless browser.known? # Allow weixin callback next true if browser.platform.other? # See https://github.com/fnando/browser#usage for more usage next true if browser.wechat? next true if browser.weibo? next true if browser.facebook? # Block known non-modern browser next false if browser.chrome?("<= 65") next false if browser.safari?("< 10") next false if browser.firefox?("< 52") next false if browser.ie?("< 11") next false if browser.edge?("< 15") next false if browser.opera?("< 50") # Allow by default next true end
ruby
MIT
38aad349679c38a38b3adfa9a125aac47393ba92
2026-01-04T17:55:59.897926Z
false
FTBpro/count-von-count
https://github.com/FTBpro/count-von-count/blob/5585796fddbe713434f8865bc85d190fd427e300/spec/script_loader.rb
spec/script_loader.rb
require 'yaml' require 'json' require 'ruby-debug' class ScriptLoader class << self attr_accessor :log_player_reads_hash end def self.load set_config load_scripts_to_log_player_test_db if self.spec_config["log_player_integration"] File.open("/usr/local/openresty/nginx/conf/vars.conf", 'w') { |f| f.write(<<-VARS set $redis_counter_hash #{von_count_script_hash}; VARS ) } restart_nginx end def self.von_count_script_hash @von_count_script_hash ||= `redis-cli SCRIPT LOAD "$(cat "lib/redis/voncount.lua")"`.strip end def self.load_scripts_to_log_player_test_db @log_player_reads_hash ||= `redis-cli -n #{self.spec_config["log_player_redis_db"]} SCRIPT LOAD "$(cat "lib/redis/voncount.lua")"`.strip end def self.set_config redis = Redis.new(host: HOST, port: "6379") config = `cat spec/config/voncount.config | tr -d '\n' | tr -d ' '` redis.set("von_count_config_live", config) end def self.restart_nginx `echo "#{personal_settings['sudo_password']}" | sudo -S nginx -s reload` sleep 1 end def self.clean_access_log `rm -f /usr/local/openresty/nginx/logs/access.log` end def self.personal_settings @@settings ||= YAML.load_file("config/personal.yml") rescue {} end def self.spec_config @@spec_config ||= YAML.load_file('spec/config/spec_config.yml') rescue {} end end
ruby
MIT
5585796fddbe713434f8865bc85d190fd427e300
2026-01-04T17:56:02.028410Z
false
FTBpro/count-von-count
https://github.com/FTBpro/count-von-count/blob/5585796fddbe713434f8865bc85d190fd427e300/spec/spec_helper.rb
spec/spec_helper.rb
require 'open-uri' require 'script_loader' require 'rubygems' require 'spork' require 'redis' require 'json' require 'support/redis_object_factory' require "integration/log_player_integrator" #uncomment the following line to use spork with the debugger #require 'spork/ext/ruby-debug' HOST = "127.0.0.1" Spork.prefork do # Loading more in this block will cause your tests to run faster. However, # if you change any configuration or code from libraries loaded here, you'll # need to restart spork for it take effect. end Spork.each_run do # This code will be run each time you run your specs. end # --- Instructions --- # Sort the contents of this file into a Spork.prefork and a Spork.each_run # block. # # The Spork.prefork block is run only once when the spork server is started. # You typically want to place most of your (slow) initializer code in here, in # particular, require'ing any 3rd-party gems that you don't normally modify # during development. # # The Spork.each_run block is run each time you run your specs. In case you # need to load files that tend to change during development, require them here. # With Rails, your application modules are loaded automatically, so sometimes # this block can remain empty. # # Note: You can modify files loaded *from* the Spork.each_run block without # restarting the spork server. However, this file itself will not be reloaded, # so if you change any of the code inside the each_run block, you still need to # restart the server. In general, if you have non-trivial code in this file, # it's advisable to move it into a separate file so you can easily edit it # without restarting spork. (For example, with RSpec, you could move # non-trivial code into a file spec/support/my_helper.rb, making sure that the # spec/support/* files are require'd from inside the each_run block.) # # Any code that is left outside the two blocks will be run during preforking # *and* during each_run -- that's probably not what you want. # # These instructions should self-destruct in 10 seconds. If they don't, feel # free to delete them. def spec_config @spec_config ||= YAML.load_file('spec/config/spec_config.yml') rescue {} end spec_config["redis_port"] lib = File.expand_path('../../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) $redis = Redis.new(host: spec_config["redis_host"], port: spec_config["redis_port"], db: spec_config["redis_db"]) $log_player_redis = Redis.new(host: HOST, port: spec_config["redis_port"] , db: spec_config["log_player_redis_db"]) ScriptLoader.load RedisObjectFactory.redis = $redis def create(type, ids = nil) ids ||= { id: rand(1000000) } RedisObjectFactory.new(type, ids) end
ruby
MIT
5585796fddbe713434f8865bc85d190fd427e300
2026-01-04T17:56:02.028410Z
false
FTBpro/count-von-count
https://github.com/FTBpro/count-von-count/blob/5585796fddbe713434f8865bc85d190fd427e300/spec/support/redis_object_factory.rb
spec/support/redis_object_factory.rb
class RedisObjectFactory attr_reader :type, :key, :ids, :id class << self attr_accessor :redis end def initialize(type_, ids_) @type = type_ @ids = ids_ @id = @ids.values.join("_") @key = "#{@type}_#{@id}" key_type = self.class.redis.type(@key) initial_data if key_type == "hash" || key_type == "none" initial_set if key_type == "zset" || key_type == "none" end def data data = Hash.new(0) data.merge(self.class.redis.hgetall @key) end def initial_data @initial_data ||= data end def initial_set @initial_set ||= set end def set set = Hash.new(0) set.merge(Hash[*$redis.zrange(key, 0, -1, withscores: true).flatten]) end def should_plus_1(key) data[key].to_i.should == initial_data[key].to_i + 1 end def should_minus_1(key) data[key].to_i.should == initial_data[key].to_i - 1 end end
ruby
MIT
5585796fddbe713434f8865bc85d190fd427e300
2026-01-04T17:56:02.028410Z
false
FTBpro/count-von-count
https://github.com/FTBpro/count-von-count/blob/5585796fddbe713434f8865bc85d190fd427e300/spec/integration/log_player_integrator.rb
spec/integration/log_player_integrator.rb
require 'ruby-debug' require 'spec_helper' def self.spec_config @@spec_config ||= YAML.load_file('spec/config/spec_config.yml') rescue {} end Spec::Runner.configure do |config| if self.spec_config["log_player_integration"] config.before(:all) do flush_keys ScriptLoader.clean_access_log ScriptLoader.restart_nginx end config.after(:all) do compare_log_player_values_to_real_time_values end end def compare_log_player_values_to_real_time_values run_log_player $redis.keys.each do |key| if !unrelevant_keys.include?(key) if !compare_value(key) raise RSpec::Expectations::ExpectationNotMetError, "Log Player Intregration: difference in #{key}" end end end end def flush_keys cache_keys = $redis.keys "*" cache_keys = cache_keys.reject { |key| key.match(/^von_count_config/)} $redis.del(cache_keys) if cache_keys.any? cache_keys = $log_player_redis.keys "*" cache_keys = cache_keys.reject { |key| key.match(/^von_count_config/)} $log_player_redis.del(cache_keys.reject { |key| key.match(/^von_count_config/)}) if cache_keys.any? end def unrelevant_keys ["von_count_config_live"] end def compare_value(key) if $redis.type(key) == "hash" return $redis.hgetall(key) == $log_player_redis.hgetall(key) elsif $redis.type(key) == "zset" return $redis.zrevrange(key, 0, -1, withscores:true) == $log_player_redis.zrevrange(key, 0, -1, withscores:true) elsif $redis.type(key) == "string" return $redis.get(key) == $log_player_redis.get(key) end false end def run_log_player `lua \ /usr/local/openresty/nginx/count-von-count/lib/log_player.lua \ /usr/local/openresty/nginx/logs/access.log \ #{spec_config["redis_host"]} \ #{spec_config["redis_port"]} \ #{spec_config["log_player_redis_db"]} \ ` end end
ruby
MIT
5585796fddbe713434f8865bc85d190fd427e300
2026-01-04T17:56:02.028410Z
false
FTBpro/count-von-count
https://github.com/FTBpro/count-von-count/blob/5585796fddbe713434f8865bc85d190fd427e300/spec/lib/utils_spec.rb
spec/lib/utils_spec.rb
require "spec_helper" describe "Utils" do describe "Android bad Query String with amp;" do before :each do @user = create :User @author = create :User open("http://#{HOST}/reads?user=#{@user.id}&amp;author=#{@author.id}") end context "it should replace &amp; with &" do it "should have a correct redis key for user" do $redis.keys("*").include?(@user.key).should be_true end it "should have a correct redis key for other user" do $redis.keys("*").include?(@author.key).should be_true end end end end
ruby
MIT
5585796fddbe713434f8865bc85d190fd427e300
2026-01-04T17:56:02.028410Z
false
FTBpro/count-von-count
https://github.com/FTBpro/count-von-count/blob/5585796fddbe713434f8865bc85d190fd427e300/spec/lib/counting_spec.rb
spec/lib/counting_spec.rb
require 'spec_helper' require 'ruby-debug' describe "Counting" do before :each do @user = create :User, id: 10 @author = create :User, id: 30 @post = create :Post, id: 100 end describe "reads action" do describe "User Hash" do before do open("http://#{HOST}/reads?post=#{@post.id}&user=#{@user.id}&author=#{@author.id}") end it "should increase the reads of the user by one" do @user.should_plus_1("reads") end describe "Author" do it "should increase the post's author num of time he's been read" do @author.should_plus_1("reads_got") end end end describe "Post Hash" do before do open("http://#{HOST}/reads?post=#{@post.id}") end it "should increase the post reads counter" do @post.should_plus_1("reads") end end describe "UserDaily Hash" do before do @user_daily = create :UserDaily, { user: @user.id, day: Time.now.strftime("%d"), month: Time.now.strftime("%m"), year: Time.now.strftime("%Y") } open("http://#{HOST}/reads?user=#{@user.id}") end it "should increase the daily reads of the user by one" do @user_daily.should_plus_1("reads") end it "should set a TTL for the objects" do $redis.ttl(@user_daily.key).should > 0 end end # describe "AuthorWeeklyDemographics Hash" do # before do # @author_weekly_demographics = create :UserWeeklyDemographics, {user: @author.id, week: Time.now.strftime("%W"), year: Time.now.strftime("%Y")} # open("http://#{HOST}/reads?author=#{@author.id}") # end # it "should increase reads counter" do # @author_weekly_demographics.should_plus_1("--") # end # end end describe "comments action" do before :each do open("http://#{HOST}/comments?user=#{@user.id}&author=#{@author.id}") end describe "User Hash" do it "should increase the user's num of comments by 1" do @user.should_plus_1("comments") end describe "Author" do it "should increase the post's author num of comments he got" do @author.should_plus_1("comments_got") end end end describe "Post Hash" do before :each do open("http://#{HOST}/comments?post=#{@post.id}") end it "should increase the post's num of comments" do @post.should_plus_1("comments") end end end describe "post_create action" do # before do # open("http://#{HOST}/post_create?user=#{@user.id}") # end # it "should increase the user's num of posts created by 1" do # @user.should_plus_1("post_create") # end # describe "TeamCounters" do # #TODO: Add spec # end # describe "TeamWriters" do # #TODO: Add spec # end end describe "post_remove action" do before do open("http://#{HOST}/post_remove?user=#{@user.id}") end it "should decrease the user's number of post_create" do @user.should_minus_1("post_create") end end end
ruby
MIT
5585796fddbe713434f8865bc85d190fd427e300
2026-01-04T17:56:02.028410Z
false
FTBpro/count-von-count
https://github.com/FTBpro/count-von-count/blob/5585796fddbe713434f8865bc85d190fd427e300/spec/lib/get_spec.rb
spec/lib/get_spec.rb
require 'spec_helper' describe "Get" do before do @user = create :User @author= create :User open("http://#{HOST}/reads?user=#{@user.id}&author=#{@author.id}") end def get(query_string) JSON.parse(open("http://#{HOST}/get?#{query_string}").read.gsub("\n", "") ) end describe "Header" do it "should have a 'Access-Control-Allow-Origin *' in the response header" do response = open("http://#{HOST}/get?key=User_#{@user.id}") response.meta.keys.should include "access-control-allow-origin" response.meta["access-control-allow-origin"].should == "*" end end describe "Hash key" do describe "single key" do it "should return a json with all the attributes of the key when attr params are not defined" do hash = get("key=User_#{@user.id}") hash.keys.sort.should match_array(["reads"]) end it "should return a json containing only the values defined by the attr array parameter in the query string" do hash = get("key=User_#{@user.id}&attr[]=reads&attr[]=logins") hash.keys.sort.should match_array(["logins", "reads"]) end context "when attribute doesnt exist" do it "should return nil" do hash = get("key=User_#{@user.id}&attr[]=reads&attr[]=logins") hash["reads"].to_i.should eq 1 hash.keys.should match_array(["logins", "reads"]) hash["logins"].should eq nil end end context "when only attribute defined" do it "should return only the value of the desired attribute" do rslt = open("http://#{HOST}/get?key=User_#{@user.id}&attr=reads").read.gsub("\n", "") rslt.should == "1" end end context "as array" do it "should return a json with a single key equal to the requested key and its value as hash" do hash = get("key[]=User_#{@user.id}") hash.keys.should match_array([@user.key]) hash[@user.key].keys.should match_array(["reads"]) end end end end describe "multiple keys" do describe "without attributes" do it "should return a json with the given keys as keys and for each key a hash with all of its attributes " do hash = get("key[]=#{@user.key}&key[]=#{@author.key}") hash.keys.should match_array([@user.key, @author.key]) hash[@user.key].keys.should match_array(["reads"]) hash[@author.key].keys.should match_array(["reads_got"]) end end describe "with attributes" do it "should return a json with the given keys as keys and for each key a hash with all the given attributes" do hash = get("key[]=#{@user.key}&key[]=#{@author.key}&attr[]=reads&attr[]=logins") hash.keys.should match_array([@user.key, @author.key]) hash[@user.key].keys.should match_array(["logins", "reads"]) hash[@author.key].keys.should match_array(["logins", "reads"]) end context "multiple attributes" do before do open("http://#{HOST}/reads?user=#{@author.id}") end it "should return a json with the given keys as keys and for each key a value for the given attribute (single attribute)" do hash = get("key[]=#{@user.key}&key[]=#{@author.key}&attr=reads") hash.keys.should match_array([@user.key, @author.key]) hash[@user.key].should eq "1" hash[@author.key].should eq "1" end end it "should return a json with the given keys as keys and for each key a hash with the given attribute (single attribute as array)" do hash = get("key[]=#{@user.key}&key[]=#{@author.key}&attr[]=reads") hash.keys.should match_array([@user.key, @author.key]) hash[@user.key].keys.should match_array(["reads"]) hash[@author.key].keys.should match_array(["reads"]) end end end end
ruby
MIT
5585796fddbe713434f8865bc85d190fd427e300
2026-01-04T17:56:02.028410Z
false
FTBpro/count-von-count
https://github.com/FTBpro/count-von-count/blob/5585796fddbe713434f8865bc85d190fd427e300/config/deploy.rb
config/deploy.rb
# ------------------------------------------- # Git and deploytment details # ------------------------------------------- set :application, "count-von-count" set :repository, "git://github.com/FTBpro/count-von-count.git" set :scm, :git set :deploy_to, '/home/deploy/count-von-count' set :user, "deploy" set :use_sudo, false set :nginx_dir, "/usr/local/openresty/nginx" set :branch, fetch(:branch, "master") set :env, fetch(:env, "production") env_servers = { production: "***.***.***.***", qa: "***.***.***.***" } server env_servers[env.to_sym], :app, :web, :db after 'deploy:setup', 'nginx:folder_permissions', 'symlink:app', 'symlink:conf', 'redis:start', 'nginx:start' before 'deploy:restart', 'deploy:load_redis_lua' namespace :symlink do desc "Symlink nginx to application folder" task :app do run "sudo ln -sf #{deploy_to}/current/ #{nginx_dir}/count-von-count" end desc "Symlink to voncount.nginx.conf" task :conf do run "sudo mkdir -p #{nginx_dir}/conf/include" run "sudo ln -sf #{deploy_to}/current/config/voncount.nginx.conf #{nginx_dir}/conf/include/voncount.conf" end end namespace :nginx do task :start do run "sudo nginx" end task :stop do run "sudo nginx -s stop" end desc "Reload nginx with current configuration" task :reload do run "sudo nginx -s reload" end task :folder_permissions do run "sudo chown -R #{user}:#{user} #{nginx_dir}" end end namespace :redis do task :start, roles: :db do run "sudo service redis-server start" end task :stop, roles: :db do run "sudo service redis-server start" end task :restart, roles: :db do run "sudo service redis-server restart" end end def system_config @system_config ||= YAML.load_file('config/system.config') rescue {} end namespace :deploy do desc "Load the lua script to redis and saving the SHA in a file for nginx to use" task :load_redis_lua do run "sudo rm -f #{nginx_dir}/conf/include/vars.conf" run "sudo echo 'set \$redis_counter_hash '$(redis-cli -h #{system_config["redis_host"]} -p #{system_config["redis_port"]} SCRIPT LOAD \"$(cat '#{deploy_to}/current/lib/redis/voncount.lua')\")';' > #{nginx_dir}/conf/vars.conf" run "sudo echo 'set \$redis_mobile_hash '$(redis-cli SCRIPT LOAD \"$(cat '#{deploy_to}/current/lib/redis/mobile.lua')\")';' >> #{nginx_dir}/conf/vars.conf" run "sudo redis-cli set von_count_config_live \"$(cat '#{deploy_to}/current/config/voncount.config' | tr -d '\n' | tr -d ' ')\"" end task :restart do nginx.reload end end
ruby
MIT
5585796fddbe713434f8865bc85d190fd427e300
2026-01-04T17:56:02.028410Z
false
sparklemotion/http-cookie
https://github.com/sparklemotion/http-cookie/blob/e5b73f3b0a3331a6591a928c1ad49dbe3aed4065/test/test_http_cookie.rb
test/test_http_cookie.rb
# -*- coding: utf-8 -*- # frozen_string_literal: false require File.expand_path('helper', File.dirname(__FILE__)) require 'psych' if !defined?(YAML) && RUBY_VERSION == "1.9.2" require 'yaml' class TestHTTPCookie < Test::Unit::TestCase def setup httpdate = 'Sun, 27-Sep-2037 00:00:00 GMT' @cookie_params = { 'expires' => 'expires=%s' % httpdate, 'path' => 'path=/', 'domain' => 'domain=.rubyforge.org', 'httponly' => 'HttpOnly', } @expires = Time.parse(httpdate) end def test_parse_dates url = URI.parse('http://localhost/') yesterday = Time.now - 86400 dates = [ "14 Apr 89 03:20:12", "14 Apr 89 03:20 GMT", "Fri, 17 Mar 89 4:01:33", "Fri, 17 Mar 89 4:01 GMT", "Mon Jan 16 16:12 PDT 1989", #"Mon Jan 16 16:12 +0130 1989", "6 May 1992 16:41-JST (Wednesday)", #"22-AUG-1993 10:59:12.82", "22-AUG-1993 10:59pm", "22-AUG-1993 12:59am", "22-AUG-1993 12:59 PM", #"Friday, August 04, 1995 3:54 PM", #"06/21/95 04:24:34 PM", #"20/06/95 21:07", #"95-06-08 19:32:48 EDT", ] dates.each do |date| cookie = "PREF=1; expires=#{date}" assert_equal 1, HTTP::Cookie.parse(cookie, url) { |c| assert c.expires, "Tried parsing: #{date}" assert_send [c.expires, :<, yesterday] }.size end [ ["PREF=1; expires=Wed, 01 Jan 100 12:34:56 GMT", nil], ["PREF=1; expires=Sat, 01 Jan 1600 12:34:56 GMT", nil], ["PREF=1; expires=Tue, 01 Jan 69 12:34:56 GMT", 2069], ["PREF=1; expires=Thu, 01 Jan 70 12:34:56 GMT", 1970], ["PREF=1; expires=Wed, 01 Jan 20 12:34:56 GMT", 2020], ["PREF=1; expires=Sat, 01 Jan 2020 12:34:60 GMT", nil], ["PREF=1; expires=Sat, 01 Jan 2020 12:60:56 GMT", nil], ["PREF=1; expires=Sat, 01 Jan 2020 24:00:00 GMT", nil], ["PREF=1; expires=Sat, 32 Jan 2020 12:34:56 GMT", nil], ].each { |set_cookie, year| cookie, = HTTP::Cookie.parse(set_cookie, url) if year assert_equal year, cookie.expires.year, "#{set_cookie}: expires in #{year}" else assert_equal nil, cookie.expires, "#{set_cookie}: invalid expiry date" end } end def test_parse_empty cookie_str = 'a=b; ; c=d' uri = URI.parse 'http://example' assert_equal 1, HTTP::Cookie.parse(cookie_str, uri) { |cookie| assert_equal 'a', cookie.name assert_equal 'b', cookie.value }.size end def test_parse_no_space cookie_str = "foo=bar;Expires=Sun, 06 Nov 2011 00:28:06 GMT;Path=/" uri = URI.parse 'http://example' assert_equal 1, HTTP::Cookie.parse(cookie_str, uri) { |cookie| assert_equal 'foo', cookie.name assert_equal 'bar', cookie.value assert_equal '/', cookie.path assert_equal Time.at(1320539286), cookie.expires }.size end def test_parse_too_long_cookie uri = URI.parse 'http://example' cookie_str = "foo=#{'Cookie' * 680}; path=/ab/" assert_equal(HTTP::Cookie::MAX_LENGTH - 1, cookie_str.bytesize) assert_equal 1, HTTP::Cookie.parse(cookie_str, uri).size assert_equal 1, HTTP::Cookie.parse(cookie_str.sub(';', 'x;'), uri).size assert_equal 0, HTTP::Cookie.parse(cookie_str.sub(';', 'xx;'), uri).size end def test_parse_quoted cookie_str = "quoted=\"value\"; Expires=Sun, 06 Nov 2011 00:11:18 GMT; Path=/; comment=\"comment is \\\"comment\\\"\"" uri = URI.parse 'http://example' assert_equal 1, HTTP::Cookie.parse(cookie_str, uri) { |cookie| assert_equal 'quoted', cookie.name assert_equal 'value', cookie.value }.size end def test_parse_no_nothing cookie = '; "", ;' url = URI.parse('http://www.example.com/') assert_equal 0, HTTP::Cookie.parse(cookie, url).size end def test_parse_no_name cookie = '=no-name; path=/' url = URI.parse('http://www.example.com/') assert_equal 0, HTTP::Cookie.parse(cookie, url).size end def test_parse_bad_name cookie = "a\001b=c" url = URI.parse('http://www.example.com/') assert_nothing_raised { assert_equal 0, HTTP::Cookie.parse(cookie, url).size } end def test_parse_bad_value cookie = "a=b\001c" url = URI.parse('http://www.example.com/') assert_nothing_raised { assert_equal 0, HTTP::Cookie.parse(cookie, url).size } end def test_parse_weird_cookie cookie = 'n/a, ASPSESSIONIDCSRRQDQR=FBLDGHPBNDJCPCGNCPAENELB; path=/' url = URI.parse('http://www.searchinnovation.com/') assert_equal 1, HTTP::Cookie.parse(cookie, url) { |c| assert_equal('ASPSESSIONIDCSRRQDQR', c.name) assert_equal('FBLDGHPBNDJCPCGNCPAENELB', c.value) }.size end def test_double_semicolon double_semi = 'WSIDC=WEST;; domain=.williams-sonoma.com; path=/' url = URI.parse('http://williams-sonoma.com/') assert_equal 1, HTTP::Cookie.parse(double_semi, url) { |cookie| assert_equal('WSIDC', cookie.name) assert_equal('WEST', cookie.value) }.size end def test_parse_bad_version bad_cookie = 'PRETANET=TGIAqbFXtt; Name=/PRETANET; Path=/; Version=1.2; Content-type=text/html; Domain=192.168.6.196; expires=Friday, 13-November-2026 23:01:46 GMT;' url = URI.parse('http://192.168.6.196/') # The version attribute is obsolete and simply ignored cookies = HTTP::Cookie.parse(bad_cookie, url) assert_equal 1, cookies.size end def test_parse_bad_max_age bad_cookie = 'PRETANET=TGIAqbFXtt; Name=/PRETANET; Path=/; Max-Age=forever; Content-type=text/html; Domain=192.168.6.196; expires=Friday, 13-November-2026 23:01:46 GMT;' url = URI.parse('http://192.168.6.196/') # A bad max-age is simply ignored cookies = HTTP::Cookie.parse(bad_cookie, url) assert_equal 1, cookies.size assert_equal nil, cookies.first.max_age end def test_parse_date_fail url = URI.parse('http://localhost/') dates = [ "20/06/95 21:07", ] dates.each { |date| cookie = "PREF=1; expires=#{date}" assert_equal 1, HTTP::Cookie.parse(cookie, url) { |c| assert_equal(true, c.expires.nil?) }.size } end def test_parse_domain_dot url = URI.parse('http://host.example.com/') cookie_str = 'a=b; domain=.example.com' cookie = HTTP::Cookie.parse(cookie_str, url).first assert_equal 'example.com', cookie.domain assert cookie.for_domain? assert_equal '.example.com', cookie.dot_domain end def test_parse_domain_no_dot url = URI.parse('http://host.example.com/') cookie_str = 'a=b; domain=example.com' cookie = HTTP::Cookie.parse(cookie_str, url).first assert_equal 'example.com', cookie.domain assert cookie.for_domain? assert_equal '.example.com', cookie.dot_domain end def test_parse_public_suffix cookie = HTTP::Cookie.new('a', 'b', :domain => 'com') assert_equal('com', cookie.domain) assert_equal(false, cookie.for_domain?) cookie.origin = 'http://com/' assert_equal('com', cookie.domain) assert_equal(false, cookie.for_domain?) assert_raises(ArgumentError) { cookie.origin = 'http://example.com/' } end def test_parse_domain_none url = URI.parse('http://example.com/') cookie_str = 'a=b;' cookie = HTTP::Cookie.parse(cookie_str, url).first assert_equal 'example.com', cookie.domain assert !cookie.for_domain? assert_equal 'example.com', cookie.dot_domain end def test_parse_max_age url = URI.parse('http://localhost/') epoch, date = 4485353164, 'Fri, 19 Feb 2112 19:26:04 GMT' base = Time.at(1363014000) cookie = HTTP::Cookie.parse("name=Akinori; expires=#{date}", url).first assert_equal Time.at(epoch), cookie.expires cookie = HTTP::Cookie.parse('name=Akinori; max-age=3600', url).first assert_in_delta Time.now + 3600, cookie.expires, 1 cookie = HTTP::Cookie.parse('name=Akinori; max-age=3600', url, :created_at => base).first assert_equal base + 3600, cookie.expires # Max-Age has precedence over Expires cookie = HTTP::Cookie.parse("name=Akinori; max-age=3600; expires=#{date}", url).first assert_in_delta Time.now + 3600, cookie.expires, 1 cookie = HTTP::Cookie.parse("name=Akinori; max-age=3600; expires=#{date}", url, :created_at => base).first assert_equal base + 3600, cookie.expires cookie = HTTP::Cookie.parse("name=Akinori; expires=#{date}; max-age=3600", url).first assert_in_delta Time.now + 3600, cookie.expires, 1 cookie = HTTP::Cookie.parse("name=Akinori; expires=#{date}; max-age=3600", url, :created_at => base).first assert_equal base + 3600, cookie.expires end def test_parse_expires_session url = URI.parse('http://localhost/') [ 'name=Akinori', 'name=Akinori; expires', 'name=Akinori; max-age', 'name=Akinori; expires=', 'name=Akinori; max-age=', ].each { |str| cookie = HTTP::Cookie.parse(str, url).first assert cookie.session?, str } [ 'name=Akinori; expires=Mon, 19 Feb 2012 19:26:04 GMT', 'name=Akinori; max-age=3600', ].each { |str| cookie = HTTP::Cookie.parse(str, url).first assert !cookie.session?, str } end def test_parse_many url = URI 'http://localhost/' cookie_str = "abc, " \ "name=Aaron; Domain=localhost; Expires=Sun, 06 Nov 2011 00:29:51 GMT; Path=/, " \ "name=Aaron; Domain=localhost; Expires=Sun, 06 Nov 2011 00:29:51 GMT; Path=/, " \ "name=Aaron; Domain=localhost; Expires=Sun, 06 Nov 2011 00:29:51 GMT; Path=/, " \ "name=Aaron; Domain=localhost; Expires=Sun, 06 Nov 2011 00:29:51 GMT; Path=/; HttpOnly, " \ "expired=doh; Expires=Fri, 04 Nov 2011 00:29:51 GMT; Path=/, " \ "a_path1=some_path; Expires=Sun, 06 Nov 2011 00:29:51 GMT; Path=/some_path, " \ "a_path2=some_path; Expires=Sun, 06 Nov 2011 00:29:51 GMT; Path=/some_path[], " \ "no_path1=no_path; Expires=Sun, 06 Nov 2011 00:29:52 GMT, no_expires=nope; Path=/, " \ "no_path2=no_path; Expires=Sun, 06 Nov 2011 00:29:52 GMT; no_expires=nope; Path, " \ "no_path3=no_path; Expires=Sun, 06 Nov 2011 00:29:52 GMT; no_expires=nope; Path=, " \ "rel_path1=rel_path; Expires=Sun, 06 Nov 2011 00:29:52 GMT; no_expires=nope; Path=foo/bar, " \ "rel_path1=rel_path; Expires=Sun, 06 Nov 2011 00:29:52 GMT; no_expires=nope; Path=foo, " \ "no_domain1=no_domain; Expires=Sun, 06 Nov 2011 00:29:53 GMT; no_expires=nope, " \ "no_domain2=no_domain; Expires=Sun, 06 Nov 2011 00:29:53 GMT; no_expires=nope; Domain, " \ "no_domain3=no_domain; Expires=Sun, 06 Nov 2011 00:29:53 GMT; no_expires=nope; Domain=" cookies = HTTP::Cookie.parse cookie_str, url assert_equal 16, cookies.length name = cookies.find { |c| c.name == 'name' } assert_equal "Aaron", name.value assert_equal "/", name.path assert_equal Time.at(1320539391), name.expires a_path1 = cookies.find { |c| c.name == 'a_path1' } assert_equal "some_path", a_path1.value assert_equal "/some_path", a_path1.path assert_equal Time.at(1320539391), a_path1.expires a_path2 = cookies.find { |c| c.name == 'a_path2' } assert_equal "some_path", a_path2.value assert_equal "/some_path[]", a_path2.path assert_equal Time.at(1320539391), a_path2.expires no_expires = cookies.find { |c| c.name == 'no_expires' } assert_equal "nope", no_expires.value assert_equal "/", no_expires.path assert_nil no_expires.expires no_path_cookies = cookies.select { |c| c.value == 'no_path' } assert_equal 3, no_path_cookies.size no_path_cookies.each { |c| assert_equal "/", c.path, c.name assert_equal Time.at(1320539392), c.expires, c.name } rel_path_cookies = cookies.select { |c| c.value == 'rel_path' } assert_equal 2, rel_path_cookies.size rel_path_cookies.each { |c| assert_equal "/", c.path, c.name assert_equal Time.at(1320539392), c.expires, c.name } no_domain_cookies = cookies.select { |c| c.value == 'no_domain' } assert_equal 3, no_domain_cookies.size no_domain_cookies.each { |c| assert !c.for_domain?, c.name assert_equal c.domain, url.host, c.name assert_equal Time.at(1320539393), c.expires, c.name } assert cookies.find { |c| c.name == 'expired' } end def test_parse_valid_cookie url = URI.parse('http://rubyforge.org/') cookie_params = @cookie_params cookie_value = '12345%7D=ASDFWEE345%3DASda' cookie_params.keys.combine.each do |keys| cookie_text = [cookie_value, *keys.map { |key| cookie_params[key] }].join('; ') cookie, = HTTP::Cookie.parse(cookie_text, url) assert_equal('12345%7D=ASDFWEE345%3DASda', cookie.to_s) assert_equal('/', cookie.path) assert_equal(keys.include?('expires') ? @expires : nil, cookie.expires) assert_equal(keys.include?('httponly'), cookie.httponly?) end end def test_parse_valid_cookie_empty_value url = URI.parse('http://rubyforge.org/') cookie_params = @cookie_params cookie_value = '12345%7D=' cookie_params.keys.combine.each do |keys| cookie_text = [cookie_value, *keys.map { |key| cookie_params[key] }].join('; ') cookie, = HTTP::Cookie.parse(cookie_text, url) assert_equal('12345%7D=', cookie.to_s) assert_equal('', cookie.value) assert_equal('/', cookie.path) assert_equal(keys.include?('expires') ? @expires : nil, cookie.expires) assert_equal(keys.include?('httponly'), cookie.httponly?) end end # If no path was given, use the one from the URL def test_cookie_using_url_path url = URI.parse('http://rubyforge.org/login.php') cookie_params = @cookie_params cookie_value = '12345%7D=ASDFWEE345%3DASda' cookie_params.keys.combine.each do |keys| next if keys.include?('path') cookie_text = [cookie_value, *keys.map { |key| cookie_params[key] }].join('; ') cookie, = HTTP::Cookie.parse(cookie_text, url) assert_equal('12345%7D=ASDFWEE345%3DASda', cookie.to_s) assert_equal('/', cookie.path) assert_equal(keys.include?('expires') ? @expires : nil, cookie.expires) assert_equal(keys.include?('httponly'), cookie.httponly?) end end # Test using secure cookies def test_cookie_with_secure url = URI.parse('http://rubyforge.org/') cookie_params = @cookie_params.merge('secure' => 'secure') cookie_value = '12345%7D=ASDFWEE345%3DASda' cookie_params.keys.combine.each do |keys| next unless keys.include?('secure') cookie_text = [cookie_value, *keys.map { |key| cookie_params[key] }].join('; ') cookie, = HTTP::Cookie.parse(cookie_text, url) assert_equal('12345%7D=ASDFWEE345%3DASda', cookie.to_s) assert_equal('/', cookie.path) assert_equal(true, cookie.secure) assert_equal(keys.include?('expires') ? @expires : nil, cookie.expires) assert_equal(keys.include?('httponly'), cookie.httponly?) end end def test_cookie_value [ ['foo="bar baz"', 'bar baz'], ['foo="bar\"; \"baz"', 'bar"; "baz'], ].each { |cookie_value, value| cookie = HTTP::Cookie.new('foo', value) assert_equal(cookie_value, cookie.cookie_value) } pairs = [ ['Foo', 'value1'], ['Bar', 'value 2'], ['Baz', 'value3'], ['Bar', 'value"4'], ['Quux', 'x, value=5'], ] cookie_value = HTTP::Cookie.cookie_value(pairs.map { |name, value| HTTP::Cookie.new(:name => name, :value => value) }) assert_equal 'Foo=value1; Bar="value 2"; Baz=value3; Bar="value\\"4"; Quux="x, value=5"', cookie_value hash = HTTP::Cookie.cookie_value_to_hash(cookie_value) assert_equal pairs.map(&:first).uniq.size, hash.size hash.each_pair { |name, value| _, pvalue = pairs.assoc(name) assert_equal pvalue, value } # Do not treat comma in a Cookie header value as separator; see CVE-2016-7401 hash = HTTP::Cookie.cookie_value_to_hash('Quux=x, value=5; Foo=value1; Bar="value 2"; Baz=value3; Bar="value\\"4"') assert_equal pairs.map(&:first).uniq.size, hash.size hash.each_pair { |name, value| _, pvalue = pairs.assoc(name) assert_equal pvalue, value } end def test_set_cookie_value url = URI.parse('http://rubyforge.org/path/') [ HTTP::Cookie.new('a', 'b', :domain => 'rubyforge.org', :path => '/path/'), HTTP::Cookie.new('a', 'b', :origin => url), ].each { |cookie| cookie.set_cookie_value } [ HTTP::Cookie.new('a', 'b', :domain => 'rubyforge.org'), HTTP::Cookie.new('a', 'b', :for_domain => true, :path => '/path/'), ].each { |cookie| assert_raises(RuntimeError) { cookie.set_cookie_value } } ['foo=bar', 'foo="bar"', 'foo="ba\"r baz"'].each { |cookie_value| cookie_params = @cookie_params.merge('path' => '/path/', 'secure' => 'secure', 'max-age' => 'Max-Age=1000') date = Time.at(Time.now.to_i) cookie_params.keys.combine.each do |keys| cookie_text = [cookie_value, *keys.map { |key| cookie_params[key] }].join('; ') cookie, = HTTP::Cookie.parse(cookie_text, url, :created_at => date) cookie2, = HTTP::Cookie.parse(cookie.set_cookie_value, url, :created_at => date) assert_equal(cookie.name, cookie2.name) assert_equal(cookie.value, cookie2.value) assert_equal(cookie.domain, cookie2.domain) assert_equal(cookie.for_domain?, cookie2.for_domain?) assert_equal(cookie.path, cookie2.path) assert_equal(cookie.expires, cookie2.expires) if keys.include?('max-age') assert_equal(date + 1000, cookie2.expires) elsif keys.include?('expires') assert_equal(@expires, cookie2.expires) else assert_equal(nil, cookie2.expires) end assert_equal(cookie.secure?, cookie2.secure?) assert_equal(cookie.httponly?, cookie2.httponly?) end } end def test_parse_cookie_no_spaces url = URI.parse('http://rubyforge.org/') cookie_params = @cookie_params cookie_value = '12345%7D=ASDFWEE345%3DASda' cookie_params.keys.combine.each do |keys| cookie_text = [cookie_value, *keys.map { |key| cookie_params[key] }].join(';') cookie, = HTTP::Cookie.parse(cookie_text, url) assert_equal('12345%7D=ASDFWEE345%3DASda', cookie.to_s) assert_equal('/', cookie.path) assert_equal(keys.include?('expires') ? @expires : nil, cookie.expires) assert_equal(keys.include?('httponly'), cookie.httponly?) end end def test_new cookie = HTTP::Cookie.new('key', 'value') assert_equal 'key', cookie.name assert_equal 'value', cookie.value assert_equal nil, cookie.expires assert_raises(RuntimeError) { cookie.acceptable? } # Minimum unit for the expires attribute is second expires = Time.at((Time.now + 3600).to_i) cookie = HTTP::Cookie.new('key', 'value', :expires => expires.dup) assert_equal 'key', cookie.name assert_equal 'value', cookie.value assert_equal expires, cookie.expires assert_raises(RuntimeError) { cookie.acceptable? } # various keywords [ ["Expires", /use downcased symbol/], ].each { |key, pattern| assert_warning(pattern, "warn of key: #{key.inspect}") { cookie = HTTP::Cookie.new(:value => 'value', :name => 'key', key => expires.dup) assert_equal 'key', cookie.name assert_equal 'value', cookie.value assert_equal expires, cookie.expires, "key: #{key.inspect}" } } [ [:Expires, /unknown attribute name/], [:expires?, /unknown attribute name/], [[:expires], /invalid keyword/], ].each { |key, pattern| assert_warning(pattern, "warn of key: #{key.inspect}") { cookie = HTTP::Cookie.new(:value => 'value', :name => 'key', key => expires.dup) assert_equal 'key', cookie.name assert_equal 'value', cookie.value assert_equal nil, cookie.expires, "key: #{key.inspect}" } } cookie = HTTP::Cookie.new(:value => 'value', :name => 'key', :expires => expires.dup) assert_equal 'key', cookie.name assert_equal 'value', cookie.value assert_equal expires, cookie.expires assert_equal false, cookie.for_domain? assert_raises(RuntimeError) { # domain and path are missing cookie.acceptable? } cookie = HTTP::Cookie.new(:value => 'value', :name => 'key', :expires => expires.dup, :domain => '.example.com') assert_equal 'key', cookie.name assert_equal 'value', cookie.value assert_equal expires, cookie.expires assert_equal true, cookie.for_domain? assert_raises(RuntimeError) { # path is missing cookie.acceptable? } cookie = HTTP::Cookie.new(:value => 'value', :name => 'key', :expires => expires.dup, :domain => 'example.com', :for_domain => false) assert_equal 'key', cookie.name assert_equal 'value', cookie.value assert_equal expires, cookie.expires assert_equal false, cookie.for_domain? assert_raises(RuntimeError) { # path is missing cookie.acceptable? } cookie = HTTP::Cookie.new(:value => 'value', :name => 'key', :expires => expires.dup, :domain => 'example.org', :for_domain? => true) assert_equal 'key', cookie.name assert_equal 'value', cookie.value assert_equal expires, cookie.expires assert_equal 'example.org', cookie.domain assert_equal true, cookie.for_domain? assert_raises(RuntimeError) { # path is missing cookie.acceptable? } assert_raises(ArgumentError) { HTTP::Cookie.new() } assert_raises(ArgumentError) { HTTP::Cookie.new(:value => 'value') } assert_raises(ArgumentError) { HTTP::Cookie.new('', 'value') } assert_raises(ArgumentError) { HTTP::Cookie.new('key=key', 'value') } assert_raises(ArgumentError) { HTTP::Cookie.new("key\tkey", 'value') } assert_raises(ArgumentError) { HTTP::Cookie.new('key', 'value', 'something') } assert_raises(ArgumentError) { HTTP::Cookie.new('key', 'value', {}, 'something') } [ HTTP::Cookie.new(:name => 'name'), HTTP::Cookie.new("key", nil, :for_domain => true), HTTP::Cookie.new("key", nil), HTTP::Cookie.new("key", :secure => true), HTTP::Cookie.new("key"), ].each { |cookie| assert_equal '', cookie.value assert_equal true, cookie.expired? } [ HTTP::Cookie.new(:name => 'name', :max_age => 3600), HTTP::Cookie.new("key", nil, :expires => Time.now + 3600), HTTP::Cookie.new("key", :expires => Time.now + 3600), HTTP::Cookie.new("key", :expires => Time.now + 3600, :value => nil), ].each { |cookie| assert_equal '', cookie.value assert_equal false, cookie.expired? } end def cookie_values(options = {}) { :name => 'Foo', :value => 'Bar', :path => '/', :expires => Time.now + (10 * 86400), :for_domain => true, :domain => 'rubyforge.org', :origin => 'http://rubyforge.org/' }.merge(options) end def test_bad_name [ "a\tb", "a\vb", "a\rb", "a\nb", 'a b', "a\\b", 'a"b', # 'a:b', 'a/b', 'a[b]', 'a=b', 'a,b', 'a;b', ].each { |name| assert_raises(ArgumentError) { HTTP::Cookie.new(cookie_values(:name => name)) } cookie = HTTP::Cookie.new(cookie_values) assert_raises(ArgumentError) { cookie.name = name } } end def test_bad_value [ "a\tb", "a\vb", "a\rb", "a\nb", "a\\b", 'a"b', # 'a:b', 'a/b', 'a[b]', ].each { |name| assert_raises(ArgumentError) { HTTP::Cookie.new(cookie_values(:name => name)) } cookie = HTTP::Cookie.new(cookie_values) assert_raises(ArgumentError) { cookie.name = name } } end def test_compare time = Time.now cookies = [ { :created_at => time + 1 }, { :created_at => time - 1 }, { :created_at => time }, { :created_at => time, :path => '/foo/bar/' }, { :created_at => time, :path => '/foo/' }, { :created_at => time, :path => '/foo' }, ].map { |attrs| HTTP::Cookie.new(cookie_values(attrs)) } assert_equal([3, 4, 5, 1, 2, 0], cookies.sort.map { |i| cookies.find_index { |j| j.equal?(i) } }) end def test_expiration expires = Time.now + 86400 cookie = HTTP::Cookie.new(cookie_values(expires: expires)) assert_equal(expires, cookie.expires) assert_equal false, cookie.expired? assert_equal true, cookie.expired?(cookie.expires + 1) assert_equal false, cookie.expired?(cookie.expires - 1) cookie.expire! assert_equal true, cookie.expired? end def test_expiration_using_datetime expires = DateTime.now + 1 cookie = HTTP::Cookie.new(cookie_values(expires: expires)) assert_equal(expires.to_time, cookie.expires) assert_equal false, cookie.expired? assert_equal true, cookie.expired?(cookie.expires + 1) assert_equal false, cookie.expired?(cookie.expires - 1) cookie.expire! assert_equal true, cookie.expired? end def test_max_age= cookie = HTTP::Cookie.new(cookie_values) expires = cookie.expires assert_raises(ArgumentError) { cookie.max_age = "+1" } # make sure #expires is not destroyed assert_equal expires, cookie.expires assert_raises(ArgumentError) { cookie.max_age = "1.5" } # make sure #expires is not destroyed assert_equal expires, cookie.expires assert_raises(ArgumentError) { cookie.max_age = "1 day" } # make sure #expires is not destroyed assert_equal expires, cookie.expires assert_raises(TypeError) { cookie.max_age = [1] } # make sure #expires is not destroyed assert_equal expires, cookie.expires cookie.max_age = "12" assert_equal 12, cookie.max_age cookie.max_age = -3 assert_equal(-3, cookie.max_age) end def test_session cookie = HTTP::Cookie.new(cookie_values) assert_equal false, cookie.session? assert_equal nil, cookie.max_age cookie.expires = nil assert_equal true, cookie.session? assert_equal nil, cookie.max_age cookie.expires = Time.now + 3600 assert_equal false, cookie.session? assert_equal nil, cookie.max_age cookie.max_age = 3600 assert_equal false, cookie.session? assert_equal cookie.created_at + 3600, cookie.expires cookie.max_age = nil assert_equal true, cookie.session? assert_equal nil, cookie.expires end def test_equal assert_not_equal(HTTP::Cookie.new(cookie_values), HTTP::Cookie.new(cookie_values(:value => 'bar'))) end def test_new_tld_domain url = URI 'http://rubyforge.org/' tld_cookie1 = HTTP::Cookie.new(cookie_values(:domain => 'org', :origin => url)) assert_equal false, tld_cookie1.for_domain? assert_equal 'org', tld_cookie1.domain assert_equal false, tld_cookie1.acceptable? tld_cookie2 = HTTP::Cookie.new(cookie_values(:domain => '.org', :origin => url)) assert_equal false, tld_cookie1.for_domain? assert_equal 'org', tld_cookie2.domain assert_equal false, tld_cookie2.acceptable? end def test_new_tld_domain_from_tld url = URI 'http://org/' tld_cookie1 = HTTP::Cookie.new(cookie_values(:domain => 'org', :origin => url)) assert_equal false, tld_cookie1.for_domain? assert_equal 'org', tld_cookie1.domain assert_equal true, tld_cookie1.acceptable? tld_cookie2 = HTTP::Cookie.new(cookie_values(:domain => '.org', :origin => url)) assert_equal false, tld_cookie1.for_domain? assert_equal 'org', tld_cookie2.domain assert_equal true, tld_cookie2.acceptable? end def test_fall_back_rules_for_local_domains url = URI 'http://www.example.local' tld_cookie = HTTP::Cookie.new(cookie_values(:domain => '.local', :origin => url)) assert_equal false, tld_cookie.acceptable? sld_cookie = HTTP::Cookie.new(cookie_values(:domain => '.example.local', :origin => url)) assert_equal true, sld_cookie.acceptable? end def test_new_rejects_cookies_with_ipv4_address_subdomain url = URI 'http://192.168.0.1/' cookie = HTTP::Cookie.new(cookie_values(:domain => '.0.1', :origin => url)) assert_equal false, cookie.acceptable? end def test_value cookie = HTTP::Cookie.new('name', 'value') assert_equal 'value', cookie.value cookie.value = 'new value' assert_equal 'new value', cookie.value assert_raises(ArgumentError) { cookie.value = "a\tb" } assert_raises(ArgumentError) { cookie.value = "a\nb" } assert_equal false, cookie.expired? cookie.value = nil assert_equal '', cookie.value assert_equal true, cookie.expired? end def test_path uri = URI.parse('http://example.com/foo/bar') assert_equal '/foo/bar', uri.path cookie_str = 'a=b' cookie = HTTP::Cookie.parse(cookie_str, uri).first assert '/foo/', cookie.path cookie_str = 'a=b; path=/foo' cookie = HTTP::Cookie.parse(cookie_str, uri).first assert '/foo', cookie.path uri = URI.parse('http://example.com') assert_equal '', uri.path cookie_str = 'a=b' cookie = HTTP::Cookie.parse(cookie_str, uri).first assert '/', cookie.path cookie_str = 'a=b; path=/foo' cookie = HTTP::Cookie.parse(cookie_str, uri).first assert '/foo', cookie.path end def test_domain_nil cookie = HTTP::Cookie.new('a', 'b') assert_raises(RuntimeError) { cookie.valid_for_uri?('http://example.com/') } end def test_domain= url = URI.parse('http://host.dom.example.com:8080/') cookie_str = 'a=b; domain=Example.Com' cookie = HTTP::Cookie.parse(cookie_str, url).first assert 'example.com', cookie.domain cookie.domain = DomainName(url.host) assert 'host.dom.example.com', cookie.domain cookie.domain = 'Dom.example.com' assert 'dom.example.com', cookie.domain cookie.domain = Object.new.tap { |o| def o.to_str 'Example.com' end } assert 'example.com', cookie.domain url = URI 'http://rubyforge.org/' [nil, '', '.'].each { |d| cookie = HTTP::Cookie.new('Foo', 'Bar', :path => '/') cookie.domain = d assert_equal nil, cookie.domain, "domain=#{d.inspect}" assert_equal nil, cookie.domain_name, "domain=#{d.inspect}" assert_raises(RuntimeError) { cookie.acceptable? } cookie = HTTP::Cookie.new('Foo', 'Bar', :path => '/') cookie.origin = url cookie.domain = d assert_equal url.host, cookie.domain, "domain=#{d.inspect}" assert_equal true, cookie.acceptable?, "domain=#{d.inspect}" } end def test_origin= url = URI.parse('http://example.com/path/') cookie = HTTP::Cookie.new('a', 'b') assert_raises(ArgumentError) { cookie.origin = 123 } cookie.origin = url assert_equal '/path/', cookie.path assert_equal 'example.com', cookie.domain assert_equal false, cookie.for_domain assert_raises(ArgumentError) { # cannot change the origin once set cookie.origin = URI.parse('http://www.example.com/') } cookie = HTTP::Cookie.new('a', 'b', :domain => '.example.com', :path => '/') cookie.origin = url assert_equal '/', cookie.path assert_equal 'example.com', cookie.domain assert_equal true, cookie.for_domain assert_raises(ArgumentError) { # cannot change the origin once set cookie.origin = URI.parse('http://www.example.com/') } cookie = HTTP::Cookie.new('a', 'b') cookie.origin = HTTP::Cookie::URIParser.parse('http://example.com/path[]/') assert_equal '/path[]/', cookie.path cookie = HTTP::Cookie.new('a', 'b', :domain => '.example.com') cookie.origin = URI.parse('http://example.org/') assert_equal false, cookie.acceptable? cookie = HTTP::Cookie.new('a', 'b', :domain => '.example.com') cookie.origin = 'file:///tmp/test.html' assert_equal nil, cookie.path cookie = HTTP::Cookie.new('a', 'b', :domain => '.example.com', :path => '/') cookie.origin = 'file:///tmp/test.html' assert_equal false, cookie.acceptable? end def test_acceptable_from_uri? cookie = HTTP::Cookie.new(cookie_values( :domain => 'uk', :for_domain => true, :origin => nil)) assert_equal false, cookie.for_domain? assert_equal true, cookie.acceptable_from_uri?('http://uk/')
ruby
MIT
e5b73f3b0a3331a6591a928c1ad49dbe3aed4065
2026-01-04T17:56:01.207236Z
true
sparklemotion/http-cookie
https://github.com/sparklemotion/http-cookie/blob/e5b73f3b0a3331a6591a928c1ad49dbe3aed4065/test/simplecov_start.rb
test/simplecov_start.rb
require 'simplecov' SimpleCov.start
ruby
MIT
e5b73f3b0a3331a6591a928c1ad49dbe3aed4065
2026-01-04T17:56:01.207236Z
false
sparklemotion/http-cookie
https://github.com/sparklemotion/http-cookie/blob/e5b73f3b0a3331a6591a928c1ad49dbe3aed4065/test/test_http_cookie_jar.rb
test/test_http_cookie_jar.rb
# frozen_string_literal: false require File.expand_path('helper', File.dirname(__FILE__)) require 'tmpdir' module TestHTTPCookieJar class TestAutoloading < Test::Unit::TestCase def test_nonexistent_store assert_raises(NameError) { HTTP::CookieJar::NonexistentStore } end def test_nonexistent_store_in_config expected = /cookie store unavailable: :nonexistent, error: (cannot load|no such file to load) .*nonexistent_store/ assert_raise_with_message(ArgumentError, expected) { HTTP::CookieJar.new(store: :nonexistent) } end def test_erroneous_store Dir.mktmpdir { |dir| Dir.mkdir(File.join(dir, 'http')) Dir.mkdir(File.join(dir, 'http', 'cookie_jar')) rb = File.join(dir, 'http', 'cookie_jar', 'erroneous_store.rb') File.open(rb, 'w').close $LOAD_PATH.unshift(dir) assert_raises(NameError) { HTTP::CookieJar::ErroneousStore } assert($LOADED_FEATURES.any? { |file| FileTest.identical?(file, rb) }) } end def test_nonexistent_saver assert_raises(NameError) { HTTP::CookieJar::NonexistentSaver } end def test_erroneous_saver Dir.mktmpdir { |dir| Dir.mkdir(File.join(dir, 'http')) Dir.mkdir(File.join(dir, 'http', 'cookie_jar')) rb = File.join(dir, 'http', 'cookie_jar', 'erroneous_saver.rb') File.open(rb, 'w').close $LOAD_PATH.unshift(dir) assert_raises(NameError) { HTTP::CookieJar::ErroneousSaver } assert($LOADED_FEATURES.any? { |file| FileTest.identical?(file, rb) }) } end end module CommonTests def setup(options = nil, options2 = nil) default_options = { :store => :hash, :gc_threshold => 1500, # increased by 10 for shorter test time } new_options = default_options.merge(options || {}) new_options2 = new_options.merge(options2 || {}) @store_type = new_options[:store] @gc_threshold = new_options[:gc_threshold] @jar = HTTP::CookieJar.new(new_options) @jar2 = HTTP::CookieJar.new(new_options2) end #def hash_store? # @store_type == :hash #end def mozilla_store? @store_type == :mozilla end def cookie_values(options = {}) { :name => 'Foo', :value => 'Bar', :path => '/', :expires => Time.at(Time.now.to_i + 10 * 86400), # to_i is important here :for_domain => true, :domain => 'rubyforge.org', :origin => 'http://rubyforge.org/' }.merge(options) end def test_empty? assert_equal true, @jar.empty? cookie = HTTP::Cookie.new(cookie_values) @jar.add(cookie) assert_equal false, @jar.empty? assert_equal false, @jar.empty?('http://rubyforge.org/') assert_equal true, @jar.empty?('http://example.local/') end def test_two_cookies_same_domain_and_name_different_paths url = URI 'http://rubyforge.org/' cookie = HTTP::Cookie.new(cookie_values) @jar.add(cookie) @jar.add(HTTP::Cookie.new(cookie_values(:path => '/onetwo'))) assert_equal(1, @jar.cookies(url).length) assert_equal 2, @jar.cookies(URI('http://rubyforge.org/onetwo')).length end def test_domain_case url = URI 'http://rubyforge.org/' # Add one cookie with an expiration date in the future cookie = HTTP::Cookie.new(cookie_values) @jar.add(cookie) assert_equal(1, @jar.cookies(url).length) @jar.add(HTTP::Cookie.new(cookie_values(:domain => 'RuByForge.Org', :name => 'aaron'))) assert_equal(2, @jar.cookies(url).length) url2 = URI 'http://RuByFoRgE.oRg/' assert_equal(2, @jar.cookies(url2).length) end def test_host_only url = URI.parse('http://rubyforge.org/') @jar.add(HTTP::Cookie.new( cookie_values(:domain => 'rubyforge.org', :for_domain => false))) assert_equal(1, @jar.cookies(url).length) assert_equal(1, @jar.cookies(URI('http://RubyForge.org/')).length) assert_equal(1, @jar.cookies(URI('https://RubyForge.org/')).length) assert_equal(0, @jar.cookies(URI('http://www.rubyforge.org/')).length) end def test_host_only_with_unqualified_hostname @jar.add(HTTP::Cookie.new(cookie_values( :origin => 'http://localhost/', :domain => 'localhost', :for_domain => false))) assert_equal(1, @jar.cookies(URI('http://localhost/')).length) assert_equal(1, @jar.cookies(URI('http://Localhost/')).length) assert_equal(1, @jar.cookies(URI('https://Localhost/')).length) end def test_empty_value url = URI 'http://rubyforge.org/' values = cookie_values(:value => "") # Add one cookie with an expiration date in the future cookie = HTTP::Cookie.new(values) @jar.add(cookie) assert_equal(1, @jar.cookies(url).length) @jar.add HTTP::Cookie.new(values.merge(:domain => 'RuByForge.Org', :name => 'aaron')) assert_equal(2, @jar.cookies(url).length) url2 = URI 'http://RuByFoRgE.oRg/' assert_equal(2, @jar.cookies(url2).length) end def test_add_future_cookies url = URI 'http://rubyforge.org/' # Add one cookie with an expiration date in the future cookie = HTTP::Cookie.new(cookie_values) @jar.add(cookie) assert_equal(1, @jar.cookies(url).length) # Add the same cookie, and we should still only have one @jar.add(HTTP::Cookie.new(cookie_values)) assert_equal(1, @jar.cookies(url).length) # Make sure we can get the cookie from different paths assert_equal(1, @jar.cookies(URI('http://rubyforge.org/login')).length) # Make sure we can't get the cookie from different domains assert_equal(0, @jar.cookies(URI('http://google.com/')).length) end def test_add_multiple_cookies url = URI 'http://rubyforge.org/' # Add one cookie with an expiration date in the future cookie = HTTP::Cookie.new(cookie_values) @jar.add(cookie) assert_equal(1, @jar.cookies(url).length) # Add the same cookie, and we should still only have one @jar.add(HTTP::Cookie.new(cookie_values(:name => 'Baz'))) assert_equal(2, @jar.cookies(url).length) # Make sure we can get the cookie from different paths assert_equal(2, @jar.cookies(URI('http://rubyforge.org/login')).length) # Make sure we can't get the cookie from different domains assert_equal(0, @jar.cookies(URI('http://google.com/')).length) end def test_add_multiple_cookies_with_the_same_name now = Time.now cookies = [ { :value => 'a', :path => '/', }, { :value => 'b', :path => '/abc/def/', :created_at => now - 1 }, { :value => 'c', :path => '/abc/def/', :domain => 'www.rubyforge.org', :origin => 'http://www.rubyforge.org/abc/def/', :created_at => now }, { :value => 'd', :path => '/abc/' }, ].map { |attrs| HTTP::Cookie.new(cookie_values(attrs)) } url = URI 'http://www.rubyforge.org/abc/def/ghi' cookies.permutation(cookies.size) { |shuffled| @jar.clear shuffled.each { |cookie| @jar.add(cookie) } assert_equal %w[b c d a], @jar.cookies(url).map { |cookie| cookie.value } } end def test_fall_back_rules_for_local_domains url = URI 'http://www.example.local' sld_cookie = HTTP::Cookie.new(cookie_values(:domain => '.example.local', :origin => url)) @jar.add(sld_cookie) assert_equal(1, @jar.cookies(url).length) end def test_add_makes_exception_for_localhost url = URI 'http://localhost' tld_cookie = HTTP::Cookie.new(cookie_values(:domain => 'localhost', :origin => url)) @jar.add(tld_cookie) assert_equal(1, @jar.cookies(url).length) end def test_add_cookie_for_the_parent_domain url = URI 'http://x.foo.com' cookie = HTTP::Cookie.new(cookie_values(:domain => '.foo.com', :origin => url)) @jar.add(cookie) assert_equal(1, @jar.cookies(url).length) end def test_add_rejects_cookies_with_unknown_domain_or_path cookie = HTTP::Cookie.new(cookie_values.reject { |k,v| [:origin, :domain].include?(k) }) assert_raises(ArgumentError) { @jar.add(cookie) } cookie = HTTP::Cookie.new(cookie_values.reject { |k,v| [:origin, :path].include?(k) }) assert_raises(ArgumentError) { @jar.add(cookie) } end def test_add_does_not_reject_cookies_from_a_nested_subdomain url = URI 'http://y.x.foo.com' cookie = HTTP::Cookie.new(cookie_values(:domain => '.foo.com', :origin => url)) @jar.add(cookie) assert_equal(1, @jar.cookies(url).length) end def test_cookie_without_leading_dot_does_not_cause_substring_match url = URI 'http://arubyforge.org/' cookie = HTTP::Cookie.new(cookie_values(:domain => 'rubyforge.org')) @jar.add(cookie) assert_equal(0, @jar.cookies(url).length) end def test_cookie_without_leading_dot_matches_subdomains url = URI 'http://admin.rubyforge.org/' cookie = HTTP::Cookie.new(cookie_values(:domain => 'rubyforge.org', :origin => url)) @jar.add(cookie) assert_equal(1, @jar.cookies(url).length) end def test_cookies_with_leading_dot_match_subdomains url = URI 'http://admin.rubyforge.org/' @jar.add(HTTP::Cookie.new(cookie_values(:domain => '.rubyforge.org', :origin => url))) assert_equal(1, @jar.cookies(url).length) end def test_cookies_with_leading_dot_match_parent_domains url = URI 'http://rubyforge.org/' @jar.add(HTTP::Cookie.new(cookie_values(:domain => '.rubyforge.org', :origin => url))) assert_equal(1, @jar.cookies(url).length) end def test_cookies_with_leading_dot_match_parent_domains_exactly url = URI 'http://arubyforge.org/' @jar.add(HTTP::Cookie.new(cookie_values(:domain => '.rubyforge.org'))) assert_equal(0, @jar.cookies(url).length) end def test_cookie_for_ipv4_address_matches_the_exact_ipaddress url = URI 'http://192.168.0.1/' cookie = HTTP::Cookie.new(cookie_values(:domain => '192.168.0.1', :origin => url)) @jar.add(cookie) assert_equal(1, @jar.cookies(url).length) end def test_cookie_for_ipv6_address_matches_the_exact_ipaddress url = URI 'http://[fe80::0123:4567:89ab:cdef]/' cookie = HTTP::Cookie.new(cookie_values(:domain => '[fe80::0123:4567:89ab:cdef]', :origin => url)) @jar.add(cookie) assert_equal(1, @jar.cookies(url).length) end def test_cookies_dot url = URI 'http://www.host.example/' @jar.add(HTTP::Cookie.new(cookie_values(:domain => 'www.host.example', :origin => url))) url = URI 'http://wwwxhost.example/' assert_equal(0, @jar.cookies(url).length) end def test_cookies_no_host url = URI 'file:///path/' @jar.add(HTTP::Cookie.new(cookie_values(:origin => url))) assert_equal(0, @jar.cookies(url).length) end def test_clear url = URI 'http://rubyforge.org/' # Add one cookie with an expiration date in the future cookie = HTTP::Cookie.new(cookie_values(:origin => url)) @jar.add(cookie) @jar.add(HTTP::Cookie.new(cookie_values(:name => 'Baz', :origin => url))) assert_equal(2, @jar.cookies(url).length) @jar.clear assert_equal(0, @jar.cookies(url).length) end def test_save_cookies_yaml url = URI 'http://rubyforge.org/' # Add one cookie with an expiration date in the future cookie = HTTP::Cookie.new(cookie_values(:origin => url)) s_cookie = HTTP::Cookie.new(cookie_values(:name => 'Bar', :expires => nil, :origin => url)) @jar.add(cookie) @jar.add(s_cookie) @jar.add(HTTP::Cookie.new(cookie_values(:name => 'Baz', :for_domain => false, :origin => url))) assert_equal(3, @jar.cookies(url).length) Dir.mktmpdir do |dir| value = @jar.save(File.join(dir, "cookies.yml")) assert_same @jar, value @jar2.load(File.join(dir, "cookies.yml")) cookies = @jar2.cookies(url).sort_by { |cookie| cookie.name } assert_equal(2, cookies.length) assert_equal('Baz', cookies[0].name) assert_equal(false, cookies[0].for_domain) assert_equal('Foo', cookies[1].name) assert_equal(true, cookies[1].for_domain) end assert_equal(3, @jar.cookies(url).length) end def test_save_load_signature Dir.mktmpdir { |dir| filename = File.join(dir, "cookies.yml") @jar.save(filename, :format => :cookiestxt, :session => true) @jar.save(filename, :format => :cookiestxt, :session => true) @jar.save(filename, :format => :cookiestxt) @jar.save(filename, :cookiestxt, :session => true) @jar.save(filename, :cookiestxt) @jar.save(filename, HTTP::CookieJar::CookiestxtSaver) @jar.save(filename, HTTP::CookieJar::CookiestxtSaver.new) @jar.save(filename, :session => true) @jar.save(filename) assert_raises(ArgumentError) { @jar.save() } assert_raises(ArgumentError) { @jar.save(filename, :nonexistent) } assert_raises(TypeError) { @jar.save(filename, { :format => :cookiestxt }, { :session => true }) } assert_raises(ArgumentError) { @jar.save(filename, :cookiestxt, { :session => true }, { :format => :cookiestxt }) } @jar.load(filename, :format => :cookiestxt, :linefeed => "\n") @jar.load(filename, :format => :cookiestxt, :linefeed => "\n") @jar.load(filename, :format => :cookiestxt) @jar.load(filename, HTTP::CookieJar::CookiestxtSaver) @jar.load(filename, HTTP::CookieJar::CookiestxtSaver.new) @jar.load(filename, :cookiestxt, :linefeed => "\n") @jar.load(filename, :cookiestxt) @jar.load(filename, :linefeed => "\n") @jar.load(filename) assert_raises(ArgumentError) { @jar.load() } assert_raises(ArgumentError) { @jar.load(filename, :nonexistent) } assert_raises(TypeError) { @jar.load(filename, { :format => :cookiestxt }, { :linefeed => "\n" }) } assert_raises(ArgumentError) { @jar.load(filename, :cookiestxt, { :linefeed => "\n" }, { :format => :cookiestxt }) } } end def test_save_session_cookies_yaml url = URI 'http://rubyforge.org/' # Add one cookie with an expiration date in the future cookie = HTTP::Cookie.new(cookie_values) s_cookie = HTTP::Cookie.new(cookie_values(:name => 'Bar', :expires => nil)) @jar.add(cookie) @jar.add(s_cookie) @jar.add(HTTP::Cookie.new(cookie_values(:name => 'Baz'))) assert_equal(3, @jar.cookies(url).length) Dir.mktmpdir do |dir| @jar.save(File.join(dir, "cookies.yml"), :format => :yaml, :session => true) @jar2.load(File.join(dir, "cookies.yml")) assert_equal(3, @jar2.cookies(url).length) end assert_equal(3, @jar.cookies(url).length) end def test_save_and_read_cookiestxt url = HTTP::Cookie::URIParser.parse('https://rubyforge.org/foo[]/') # Add one cookie with an expiration date in the future cookie = HTTP::Cookie.new(cookie_values) expires = cookie.expires s_cookie = HTTP::Cookie.new(cookie_values(:name => 'Bar', :expires => nil)) cookie2 = HTTP::Cookie.new(cookie_values(:name => 'Baz', :value => 'Foo#Baz', :path => '/foo[]/', :for_domain => false)) h_cookie = HTTP::Cookie.new(cookie_values(:name => 'Quux', :value => 'Foo#Quux', :httponly => true)) ma_cookie = HTTP::Cookie.new(cookie_values(:name => 'Maxage', :value => 'Foo#Maxage', :max_age => 15000)) @jar.add(cookie) @jar.add(s_cookie) @jar.add(cookie2) @jar.add(h_cookie) @jar.add(ma_cookie) assert_equal(5, @jar.cookies(url).length) Dir.mktmpdir do |dir| filename = File.join(dir, "cookies.txt") @jar.save(filename, :cookiestxt) content = File.read(filename) filename2 = File.join(dir, "cookies2.txt") open(filename2, 'w') { |w| w.puts '# HTTP Cookie File' @jar.save(w, :cookiestxt, :header => nil) } assert_equal content, File.read(filename2) assert_match(/^\.rubyforge\.org\t.*\tFoo\t/, content) assert_match(/^rubyforge\.org\t.*\tBaz\t/, content) assert_match(/^#HttpOnly_\.rubyforge\.org\t/, content) @jar2.load(filename, :cookiestxt) # HACK test the format cookies = @jar2.cookies(url) assert_equal(4, cookies.length) cookies.each { |cookie| case cookie.name when 'Foo' assert_equal 'Bar', cookie.value assert_equal expires, cookie.expires assert_equal 'rubyforge.org', cookie.domain assert_equal true, cookie.for_domain assert_equal '/', cookie.path assert_equal false, cookie.httponly? when 'Baz' assert_equal 'Foo#Baz', cookie.value assert_equal 'rubyforge.org', cookie.domain assert_equal false, cookie.for_domain assert_equal '/foo[]/', cookie.path assert_equal false, cookie.httponly? when 'Quux' assert_equal 'Foo#Quux', cookie.value assert_equal expires, cookie.expires assert_equal 'rubyforge.org', cookie.domain assert_equal true, cookie.for_domain assert_equal '/', cookie.path assert_equal true, cookie.httponly? when 'Maxage' assert_equal 'Foo#Maxage', cookie.value assert_equal nil, cookie.max_age assert_in_delta ma_cookie.expires, cookie.expires, 1 else raise end } end assert_equal(5, @jar.cookies(url).length) end def test_load_yaml_mechanize @jar.load(test_file('mechanize.yml'), :yaml) assert_equal 4, @jar.to_a.size com_nid, com_pref = @jar.cookies('http://www.google.com/') assert_equal 'NID', com_nid.name assert_equal 'Sun, 23 Sep 2063 08:20:15 GMT', com_nid.expires.httpdate assert_equal 'google.com', com_nid.domain_name.hostname assert_equal 'PREF', com_pref.name assert_equal 'Tue, 24 Mar 2065 08:20:15 GMT', com_pref.expires.httpdate assert_equal 'google.com', com_pref.domain_name.hostname cojp_nid, cojp_pref = @jar.cookies('http://www.google.co.jp/') assert_equal 'NID', cojp_nid.name assert_equal 'Sun, 23 Sep 2063 08:20:16 GMT', cojp_nid.expires.httpdate assert_equal 'google.co.jp', cojp_nid.domain_name.hostname assert_equal 'PREF', cojp_pref.name assert_equal 'Tue, 24 Mar 2065 08:20:16 GMT', cojp_pref.expires.httpdate assert_equal 'google.co.jp', cojp_pref.domain_name.hostname end def test_expire_cookies url = URI 'http://rubyforge.org/' # Add one cookie with an expiration date in the future cookie = HTTP::Cookie.new(cookie_values) @jar.add(cookie) assert_equal(1, @jar.cookies(url).length) # Add a second cookie @jar.add(HTTP::Cookie.new(cookie_values(:name => 'Baz'))) assert_equal(2, @jar.cookies(url).length) # Make sure we can get the cookie from different paths assert_equal(2, @jar.cookies(URI('http://rubyforge.org/login')).length) # Expire the first cookie @jar.add(HTTP::Cookie.new(cookie_values(:expires => Time.now - (10 * 86400)))) assert_equal(1, @jar.cookies(url).length) # Expire the second cookie @jar.add(HTTP::Cookie.new(cookie_values( :name => 'Baz', :expires => Time.now - (10 * 86400)))) assert_equal(0, @jar.cookies(url).length) end def test_session_cookies values = cookie_values(:expires => nil) url = URI 'http://rubyforge.org/' # Add one cookie with an expiration date in the future cookie = HTTP::Cookie.new(values) @jar.add(cookie) assert_equal(1, @jar.cookies(url).length) # Add a second cookie @jar.add(HTTP::Cookie.new(values.merge(:name => 'Baz'))) assert_equal(2, @jar.cookies(url).length) # Make sure we can get the cookie from different paths assert_equal(2, @jar.cookies(URI('http://rubyforge.org/login')).length) # Expire the first cookie @jar.add(HTTP::Cookie.new(values.merge(:expires => Time.now - (10 * 86400)))) assert_equal(1, @jar.cookies(url).length) # Expire the second cookie @jar.add(HTTP::Cookie.new(values.merge(:name => 'Baz', :expires => Time.now - (10 * 86400)))) assert_equal(0, @jar.cookies(url).length) # When given a URI with a blank path, CookieJar#cookies should return # cookies with the path '/': url = URI 'http://rubyforge.org' assert_equal '', url.path assert_equal(0, @jar.cookies(url).length) # Now add a cookie with the path set to '/': @jar.add(HTTP::Cookie.new(values.merge(:name => 'has_root_path', :path => '/'))) assert_equal(1, @jar.cookies(url).length) end def test_paths url = URI 'http://rubyforge.org/login' values = cookie_values(:path => "/login", :expires => nil, :origin => url) # Add one cookie with an expiration date in the future cookie = HTTP::Cookie.new(values) @jar.add(cookie) assert_equal(1, @jar.cookies(url).length) # Add a second cookie @jar.add(HTTP::Cookie.new(values.merge( :name => 'Baz' ))) assert_equal(2, @jar.cookies(url).length) # Make sure we don't get the cookie in a different path assert_equal(0, @jar.cookies(URI('http://rubyforge.org/hello')).length) assert_equal(0, @jar.cookies(URI('http://rubyforge.org/')).length) # Expire the first cookie @jar.add(HTTP::Cookie.new(values.merge( :expires => Time.now - (10 * 86400)))) assert_equal(1, @jar.cookies(url).length) # Expire the second cookie @jar.add(HTTP::Cookie.new(values.merge( :name => 'Baz', :expires => Time.now - (10 * 86400)))) assert_equal(0, @jar.cookies(url).length) end def test_non_rfc3986_compliant_paths url = HTTP::Cookie::URIParser.parse('http://RubyForge.org/login[]') values = cookie_values(:path => "/login[]", :expires => nil, :origin => url) # Add one cookie with an expiration date in the future cookie = HTTP::Cookie.new(values) @jar.add(cookie) assert_equal(1, @jar.cookies(url).length) # Add a second cookie @jar.add(HTTP::Cookie.new(values.merge( :name => 'Baz' ))) assert_equal(2, @jar.cookies(url).length) # Make sure we don't get the cookie in a different path assert_equal(0, @jar.cookies(HTTP::Cookie::URIParser.parse('http://RubyForge.org/hello[]')).length) assert_equal(0, @jar.cookies(HTTP::Cookie::URIParser.parse('http://RubyForge.org/')).length) # Expire the first cookie @jar.add(HTTP::Cookie.new(values.merge( :expires => Time.now - (10 * 86400)))) assert_equal(1, @jar.cookies(url).length) # Expire the second cookie @jar.add(HTTP::Cookie.new(values.merge( :name => 'Baz', :expires => Time.now - (10 * 86400)))) assert_equal(0, @jar.cookies(url).length) end def test_ssl_cookies # thanks to michal "ocher" ochman for reporting the bug responsible for this test. values = cookie_values(:expires => nil) values_ssl = values.merge(:name => 'Baz', :domain => "#{values[:domain]}:443") url = URI 'https://rubyforge.org/login' cookie = HTTP::Cookie.new(values) @jar.add(cookie) assert_equal(1, @jar.cookies(url).length, "did not handle SSL cookie") cookie = HTTP::Cookie.new(values_ssl) @jar.add(cookie) assert_equal(2, @jar.cookies(url).length, "did not handle SSL cookie with :443") end def test_secure_cookie nurl = URI 'http://rubyforge.org/login' surl = URI 'https://rubyforge.org/login' nncookie = HTTP::Cookie.new(cookie_values(:name => 'Foo1', :origin => nurl)) sncookie = HTTP::Cookie.new(cookie_values(:name => 'Foo1', :origin => surl)) nscookie = HTTP::Cookie.new(cookie_values(:name => 'Foo2', :secure => true, :origin => nurl)) sscookie = HTTP::Cookie.new(cookie_values(:name => 'Foo2', :secure => true, :origin => surl)) @jar.add(nncookie) @jar.add(sncookie) @jar.add(nscookie) @jar.add(sscookie) assert_equal('Foo1', @jar.cookies(nurl).map { |c| c.name }.sort.join(' ') ) assert_equal('Foo1 Foo2', @jar.cookies(surl).map { |c| c.name }.sort.join(' ') ) end def test_delete cookie1 = HTTP::Cookie.new(cookie_values) cookie2 = HTTP::Cookie.new(:name => 'Foo', :value => '', :domain => 'rubyforge.org', :for_domain => false, :path => '/') cookie3 = HTTP::Cookie.new(:name => 'Foo', :value => '', :domain => 'rubyforge.org', :for_domain => true, :path => '/') @jar.add(cookie1) @jar.delete(cookie2) if mozilla_store? assert_equal(1, @jar.to_a.length) @jar.delete(cookie3) end assert_equal(0, @jar.to_a.length) end def test_accessed_at orig = HTTP::Cookie.new(cookie_values(:expires => nil)) @jar.add(orig) time = orig.accessed_at assert_in_delta 1.0, time, Time.now, "accessed_at is initialized to the current time" cookie, = @jar.to_a assert_equal time, cookie.accessed_at, "accessed_at is not updated by each()" cookie, = @jar.cookies("http://rubyforge.org/") assert_send [cookie.accessed_at, :>, time], "accessed_at is not updated by each(url)" end def test_max_cookies slimit = HTTP::Cookie::MAX_COOKIES_TOTAL + @gc_threshold limit_per_domain = HTTP::Cookie::MAX_COOKIES_PER_DOMAIN uri = URI('http://www.example.org/') date = Time.at(Time.now.to_i + 86400) (1..(limit_per_domain + 1)).each { |i| @jar << HTTP::Cookie.new(cookie_values( :name => 'Foo%d' % i, :value => 'Bar%d' % i, :domain => uri.host, :for_domain => true, :path => '/dir%d/' % (i / 2), :origin => uri )).tap { |cookie| cookie.created_at = i == 42 ? date - i : date } } assert_equal limit_per_domain + 1, @jar.to_a.size @jar.cleanup count = @jar.to_a.size assert_equal limit_per_domain, count assert_equal [*1..(limit_per_domain + 1)] - [42], @jar.map { |cookie| cookie.name[/(\d+)$/].to_i }.sort hlimit = HTTP::Cookie::MAX_COOKIES_TOTAL n = hlimit / limit_per_domain * 2 (1..n).each { |i| (1..(limit_per_domain + 1)).each { |j| uri = URI('http://www%d.example.jp/' % i) @jar << HTTP::Cookie.new(cookie_values( :name => 'Baz%d' % j, :value => 'www%d.example.jp' % j, :domain => uri.host, :for_domain => true, :path => '/dir%d/' % (i / 2), :origin => uri )).tap { |cookie| cookie.created_at = i == j ? date - i : date } count += 1 } } assert_send [count, :>, slimit] assert_send [@jar.to_a.size, :<=, slimit] @jar.cleanup assert_equal hlimit, @jar.to_a.size assert_equal false, @jar.any? { |cookie| cookie.domain == cookie.value } end def test_parse set_cookie = [ "name=Akinori; Domain=rubyforge.org; Expires=Sun, 08 Aug 2076 19:00:00 GMT; Path=/", "country=Japan; Domain=rubyforge.org; Expires=Sun, 08 Aug 2076 19:00:00 GMT; Path=/", "city=Tokyo; Domain=rubyforge.org; Expires=Sun, 08 Aug 2076 19:00:00 GMT; Path=/", ].join(', ') cookies = @jar.parse(set_cookie, 'http://rubyforge.org/') assert_equal %w[Akinori Japan Tokyo], cookies.map { |c| c.value } assert_equal %w[Tokyo Japan Akinori], @jar.to_a.sort_by { |c| c.name }.map { |c| c.value } end def test_parse_with_block set_cookie = [ "name=Akinori; Domain=rubyforge.org; Expires=Sun, 08 Aug 2076 19:00:00 GMT; Path=/", "country=Japan; Domain=rubyforge.org; Expires=Sun, 08 Aug 2076 19:00:00 GMT; Path=/", "city=Tokyo; Domain=rubyforge.org; Expires=Sun, 08 Aug 2076 19:00:00 GMT; Path=/", ].join(', ') cookies = @jar.parse(set_cookie, 'http://rubyforge.org/') { |c| c.name != 'city' } assert_equal %w[Akinori Japan], cookies.map { |c| c.value } assert_equal %w[Japan Akinori], @jar.to_a.sort_by { |c| c.name }.map { |c| c.value } end def test_expire_by_each_and_cleanup uri = URI('http://www.example.org/') ts = Time.now.to_f if ts % 1 > 0.5 sleep 0.5 ts += 0.5 end expires = Time.at(ts.floor) time = expires if mozilla_store? # MozillaStore only has the time precision of seconds. time = expires expires -= 1 end 0.upto(2) { |i| c = HTTP::Cookie.new('Foo%d' % (3 - i), 'Bar', :expires => expires + i, :origin => uri) @jar << c @jar2 << c } assert_equal %w[Foo1 Foo2], @jar.cookies.map(&:name) assert_equal %w[Foo1 Foo2], @jar2.cookies(uri).map(&:name) sleep_until time + 1 assert_equal %w[Foo1], @jar.cookies.map(&:name) assert_equal %w[Foo1], @jar2.cookies(uri).map(&:name) sleep_until time + 2 @jar.cleanup @jar2.cleanup assert_send [@jar, :empty?] assert_send [@jar2, :empty?] end end class WithHashStore < Test::Unit::TestCase include CommonTests def test_new jar = HTTP::CookieJar.new(:store => :hash) assert_instance_of HTTP::CookieJar::HashStore, jar.store assert_raises(ArgumentError) { jar = HTTP::CookieJar.new(:store => :nonexistent) } jar = HTTP::CookieJar.new(:store => HTTP::CookieJar::HashStore.new) assert_instance_of HTTP::CookieJar::HashStore, jar.store jar = HTTP::CookieJar.new(:store => HTTP::CookieJar::HashStore) end def test_clone jar = @jar.clone assert_not_send [ @jar.store, :equal?, jar.store ] assert_not_send [ @jar.store.instance_variable_get(:@jar), :equal?, jar.store.instance_variable_get(:@jar) ] assert_equal @jar.cookies, jar.cookies end end class WithMozillaStore < Test::Unit::TestCase include CommonTests def setup super( { :store => :mozilla, :filename => ":memory:" }, { :store => :mozilla, :filename => ":memory:" }) end def add_and_delete(jar) jar.parse("name=Akinori; Domain=rubyforge.org; Expires=Sun, 08 Aug 2076 19:00:00 GMT; Path=/", 'http://rubyforge.org/') jar.parse("country=Japan; Domain=rubyforge.org; Expires=Sun, 08 Aug 2076 19:00:00 GMT; Path=/", 'http://rubyforge.org/') jar.delete(HTTP::Cookie.new("name", :domain => 'rubyforge.org')) end def test_clone assert_raises(TypeError) { @jar.clone } end def test_close add_and_delete(@jar) assert_not_send [@jar.store, :closed?] @jar.store.close assert_send [@jar.store, :closed?] @jar.store.close # should do nothing assert_send [@jar.store, :closed?] end def test_finalizer db = nil loop { jar = HTTP::CookieJar.new(:store => :mozilla, :filename => ':memory:') add_and_delete(jar) db = jar.store.instance_variable_get(:@db) class << db alias close_orig close def close STDERR.print "[finalizer is called]" STDERR.flush close_orig end end break } end def test_upgrade_mozillastore Dir.mktmpdir { |dir| filename = File.join(dir, 'cookies.sqlite') sqlite = SQLite3::Database.new(filename) sqlite.execute(<<-'SQL') CREATE TABLE moz_cookies ( id INTEGER PRIMARY KEY, name TEXT,
ruby
MIT
e5b73f3b0a3331a6591a928c1ad49dbe3aed4065
2026-01-04T17:56:01.207236Z
true
sparklemotion/http-cookie
https://github.com/sparklemotion/http-cookie/blob/e5b73f3b0a3331a6591a928c1ad49dbe3aed4065/test/helper.rb
test/helper.rb
require 'rubygems' require 'test-unit' require 'uri' require 'http/cookie' module Test module Unit module Assertions def assert_warn(pattern, message = nil, &block) class << (output = +"") alias write << end stderr, $stderr = $stderr, output yield assert_match(pattern, output, message) ensure $stderr = stderr end def assert_warning(pattern, message = nil, &block) verbose, $VERBOSE = $VERBOSE, true assert_warn(pattern, message, &block) ensure $VERBOSE = verbose end end end end module Enumerable def combine masks = inject([[], 1]){|(ar, m), e| [ar << m, m << 1 ] }[0] all = masks.inject(0){ |al, m| al|m } result = [] for i in 1..all do tmp = [] each_with_index do |e, idx| tmp << e unless (masks[idx] & i) == 0 end result << tmp end result end end def test_file(filename) File.expand_path(filename, File.dirname(__FILE__)) end def sleep_until(time) if (s = time - Time.now) > 0 sleep s + 0.01 end end
ruby
MIT
e5b73f3b0a3331a6591a928c1ad49dbe3aed4065
2026-01-04T17:56:01.207236Z
false
sparklemotion/http-cookie
https://github.com/sparklemotion/http-cookie/blob/e5b73f3b0a3331a6591a928c1ad49dbe3aed4065/lib/http-cookie.rb
lib/http-cookie.rb
require 'http/cookie'
ruby
MIT
e5b73f3b0a3331a6591a928c1ad49dbe3aed4065
2026-01-04T17:56:01.207236Z
false
sparklemotion/http-cookie
https://github.com/sparklemotion/http-cookie/blob/e5b73f3b0a3331a6591a928c1ad49dbe3aed4065/lib/http/cookie_jar.rb
lib/http/cookie_jar.rb
# :markup: markdown require 'http/cookie' ## # This class is used to manage the Cookies that have been returned from # any particular website. class HTTP::CookieJar class << self def const_missing(name) case name.to_s when /\A([A-Za-z]+)Store\z/ file = 'http/cookie_jar/%s_store' % $1.downcase when /\A([A-Za-z]+)Saver\z/ file = 'http/cookie_jar/%s_saver' % $1.downcase end begin require file rescue LoadError raise NameError, 'can\'t resolve constant %s; failed to load %s' % [name, file] end if const_defined?(name) const_get(name) else raise NameError, 'can\'t resolve constant %s after loading %s' % [name, file] end end end attr_reader :store def get_impl(base, value, *args) case value when base value when Symbol begin base.implementation(value).new(*args) rescue IndexError => e raise ArgumentError, e.message end when Class if base >= value value.new(*args) else raise TypeError, 'not a subclass of %s: %s' % [base, value] end else raise TypeError, 'invalid object: %s' % value.inspect end end private :get_impl # Generates a new cookie jar. # # Available option keywords are as below: # # :store # : The store class that backs this jar. (default: `:hash`) # A symbol addressing a store class, a store class, or an instance # of a store class is accepted. Symbols are mapped to store # classes, like `:hash` to HTTP::CookieJar::HashStore and `:mozilla` # to HTTP::CookieJar::MozillaStore. # # Any options given are passed through to the initializer of the # specified store class. For example, the `:mozilla` # (HTTP::CookieJar::MozillaStore) store class requires a `:filename` # option. See individual store classes for details. def initialize(options = nil) opthash = { :store => :hash, } opthash.update(options) if options @store = get_impl(AbstractStore, opthash[:store], opthash) end # The copy constructor. Not all backend store classes support cloning. def initialize_copy(other) @store = other.instance_eval { @store.dup } end # Adds a cookie to the jar if it is acceptable, and returns self in # any case. A given cookie must have domain and path attributes # set, or ArgumentError is raised. # # Whether a cookie with the `for_domain` flag on overwrites another # with the flag off or vice versa depends on the store used. See # individual store classes for that matter. # # ### Compatibility Note for Mechanize::Cookie users # # In HTTP::Cookie, each cookie object can store its origin URI # (cf. #origin). While the origin URI of a cookie can be set # manually by #origin=, one is typically given in its generation. # To be more specific, HTTP::Cookie.new takes an `:origin` option # and HTTP::Cookie.parse takes one via the second argument. # # # Mechanize::Cookie # jar.add(origin, cookie) # jar.add!(cookie) # no acceptance check is performed # # # HTTP::Cookie # jar.origin = origin # jar.add(cookie) # acceptance check is performed def add(cookie) @store.add(cookie) if begin cookie.acceptable? rescue RuntimeError => e raise ArgumentError, e.message end self end alias << add # Deletes a cookie that has the same name, domain and path as a # given cookie from the jar and returns self. # # How the `for_domain` flag value affects the set of deleted cookies # depends on the store used. See individual store classes for that # matter. def delete(cookie) @store.delete(cookie) self end # Gets an array of cookies sorted by the path and creation time. If # `url` is given, only ones that should be sent to the URL/URI are # selected, with the access time of each of them updated. def cookies(url = nil) each(url).sort end # Tests if the jar is empty. If `url` is given, tests if there is # no cookie for the URL. def empty?(url = nil) if url each(url) { return false } return true else @store.empty? end end # Iterates over all cookies that are not expired in no particular # order. # # An optional argument `uri` specifies a URI/URL indicating the # destination of the cookies being selected. Every cookie yielded # should be good to send to the given URI, # i.e. cookie.valid_for_uri?(uri) evaluates to true. # # If (and only if) the `uri` option is given, last access time of # each cookie is updated to the current time. def each(uri = nil, &block) # :yield: cookie block_given? or return enum_for(__method__, uri) if uri uri = HTTP::Cookie::URIParser.parse(uri) return self unless URI::HTTP === uri && uri.host end @store.each(uri, &block) self end include Enumerable # Parses a Set-Cookie field value `set_cookie` assuming that it is # sent from a source URL/URI `origin`, and adds the cookies parsed # as valid and considered acceptable to the jar. Returns an array # of cookies that have been added. # # If a block is given, it is called for each cookie and the cookie # is added only if the block returns a true value. # # `jar.parse(set_cookie, origin)` is a shorthand for this: # # HTTP::Cookie.parse(set_cookie, origin) { |cookie| # jar.add(cookie) # } # # See HTTP::Cookie.parse for available options. def parse(set_cookie, origin, options = nil) # :yield: cookie if block_given? HTTP::Cookie.parse(set_cookie, origin, options).tap { |cookies| cookies.select! { |cookie| yield(cookie) && add(cookie) } } else HTTP::Cookie.parse(set_cookie, origin, options) { |cookie| add(cookie) } end end # call-seq: # jar.save(filename_or_io, **options) # jar.save(filename_or_io, format = :yaml, **options) # # Saves the cookie jar into a file or an IO in the format specified # and returns self. If a given object responds to #write it is # taken as an IO, or taken as a filename otherwise. # # Available option keywords are below: # # * `:format` # # Specifies the format for saving. A saver class, a symbol # addressing a saver class, or a pre-generated instance of a # saver class is accepted. # # <dl class="rdoc-list note-list"> # <dt>:yaml</dt> # <dd>YAML structure (default)</dd> # <dt>:cookiestxt</dt> # <dd>Mozilla's cookies.txt format</dd> # </dl> # # * `:session` # # <dl class="rdoc-list note-list"> # <dt>true</dt> # <dd>Save session cookies as well.</dd> # <dt>false</dt> # <dd>Do not save session cookies. (default)</dd> # </dl> # # All options given are passed through to the underlying cookie # saver module's constructor. def save(writable, *options) opthash = { :format => :yaml, :session => false, } case options.size when 0 when 1 case options = options.first when Symbol opthash[:format] = options else if hash = Hash.try_convert(options) opthash.update(hash) end end when 2 opthash[:format], options = options if hash = Hash.try_convert(options) opthash.update(hash) end else raise ArgumentError, 'wrong number of arguments (%d for 1-3)' % (1 + options.size) end saver = get_impl(AbstractSaver, opthash[:format], opthash) if writable.respond_to?(:write) saver.save(writable, self) else File.open(writable, 'w') { |io| saver.save(io, self) } end self end # call-seq: # jar.load(filename_or_io, **options) # jar.load(filename_or_io, format = :yaml, **options) # # Loads cookies recorded in a file or an IO in the format specified # into the jar and returns self. If a given object responds to # \#read it is taken as an IO, or taken as a filename otherwise. # # Available option keywords are below: # # * `:format` # # Specifies the format for loading. A saver class, a symbol # addressing a saver class, or a pre-generated instance of a # saver class is accepted. # # <dl class="rdoc-list note-list"> # <dt>:yaml</dt> # <dd>YAML structure (default)</dd> # <dt>:cookiestxt</dt> # <dd>Mozilla's cookies.txt format</dd> # </dl> # # All options given are passed through to the underlying cookie # saver module's constructor. def load(readable, *options) opthash = { :format => :yaml, :session => false, } case options.size when 0 when 1 case options = options.first when Symbol opthash[:format] = options else if hash = Hash.try_convert(options) opthash.update(hash) end end when 2 opthash[:format], options = options if hash = Hash.try_convert(options) opthash.update(hash) end else raise ArgumentError, 'wrong number of arguments (%d for 1-3)' % (1 + options.size) end saver = get_impl(AbstractSaver, opthash[:format], opthash) if readable.respond_to?(:write) saver.load(readable, self) else File.open(readable, 'r') { |io| saver.load(io, self) } end self end # Clears the cookie jar and returns self. def clear @store.clear self end # Removes expired cookies and returns self. If `session` is true, # all session cookies are removed as well. def cleanup(session = false) @store.cleanup session self end end
ruby
MIT
e5b73f3b0a3331a6591a928c1ad49dbe3aed4065
2026-01-04T17:56:01.207236Z
false
sparklemotion/http-cookie
https://github.com/sparklemotion/http-cookie/blob/e5b73f3b0a3331a6591a928c1ad49dbe3aed4065/lib/http/cookie.rb
lib/http/cookie.rb
# :markup: markdown # frozen_string_literal: true require 'http/cookie/version' require 'http/cookie/uri_parser' require 'time' require 'uri' require 'domain_name' require 'http/cookie/ruby_compat' require 'cgi' module HTTP autoload :CookieJar, 'http/cookie_jar' end # This class is used to represent an HTTP Cookie. class HTTP::Cookie # Maximum number of bytes per cookie (RFC 6265 6.1 requires 4096 at # least) MAX_LENGTH = 4096 # Maximum number of cookies per domain (RFC 6265 6.1 requires 50 at # least) MAX_COOKIES_PER_DOMAIN = 50 # Maximum number of cookies total (RFC 6265 6.1 requires 3000 at # least) MAX_COOKIES_TOTAL = 3000 # :stopdoc: UNIX_EPOCH = Time.at(0) PERSISTENT_PROPERTIES = %w[ name value domain for_domain path secure httponly expires max_age created_at accessed_at ] # :startdoc: # The cookie name. It may not be nil or empty. # # Assign a string containing any of the following characters will # raise ArgumentError: control characters (`\x00-\x1F` and `\x7F`), # space and separators `,;\"=`. # # Note that RFC 6265 4.1.1 lists more characters disallowed for use # in a cookie name, which are these: `<>@:/[]?{}`. Using these # characters will reduce interoperability. # # :attr_accessor: name # The cookie value. # # Assign a string containing a control character (`\x00-\x1F` and # `\x7F`) will raise ArgumentError. # # Assigning nil sets the value to an empty string and the expiration # date to the Unix epoch. This is a handy way to make a cookie for # expiration. # # Note that RFC 6265 4.1.1 lists more characters disallowed for use # in a cookie value, which are these: ` ",;\`. Using these # characters will reduce interoperability. # # :attr_accessor: value # The cookie domain. # # Setting a domain with a leading dot implies that the #for_domain # flag should be turned on. The setter accepts a DomainName object # as well as a string-like. # # :attr_accessor: domain # The path attribute value. # # The setter treats an empty path ("") as the root path ("/"). # # :attr_accessor: path # The origin of the cookie. # # Setting this will initialize the #domain and #path attribute # values if unknown yet. If the cookie already has a domain value # set, it is checked against the origin URL to see if the origin is # allowed to issue a cookie of the domain, and ArgumentError is # raised if the check fails. # # :attr_accessor: origin # The Expires attribute value as a Time object. # # The setter method accepts a Time / DateTime object, a string representation # of date/time that Time.parse can understand, or `nil`. # # Setting this value resets #max_age to nil. When #max_age is # non-nil, #expires returns `created_at + max_age`. # # :attr_accessor: expires # The Max-Age attribute value as an integer, the number of seconds # before expiration. # # The setter method accepts an integer, or a string-like that # represents an integer which will be stringified and then # integerized using #to_i. # # This value is reset to nil when #expires= is called. # # :attr_accessor: max_age # :call-seq: # new(name, value = nil) # new(name, value = nil, **attr_hash) # new(**attr_hash) # # Creates a cookie object. For each key of `attr_hash`, the setter # is called if defined and any error (typically ArgumentError or # TypeError) that is raised will be passed through. Each key can be # either a downcased symbol or a string that may be mixed case. # Support for the latter may, however, be obsoleted in future when # Ruby 2.0's keyword syntax is adopted. # # If `value` is omitted or it is nil, an expiration cookie is # created unless `max_age` or `expires` (`expires_at`) is given. # # e.g. # # new("uid", "a12345") # new("uid", "a12345", :domain => 'example.org', # :for_domain => true, :expired => Time.now + 7*86400) # new("name" => "uid", "value" => "a12345", "Domain" => 'www.example.org') # def initialize(*args) @name = @origin = @domain = @path = @expires = @max_age = nil @for_domain = @secure = @httponly = false @session = true @created_at = @accessed_at = Time.now case argc = args.size when 1 if attr_hash = Hash.try_convert(args.last) args.pop else self.name, self.value = args # value is set to nil return end when 2..3 if attr_hash = Hash.try_convert(args.last) args.pop self.name, value = args else argc == 2 or raise ArgumentError, "wrong number of arguments (#{argc} for 1-3)" self.name, self.value = args return end else raise ArgumentError, "wrong number of arguments (#{argc} for 1-3)" end for_domain = false domain = max_age = origin = nil attr_hash.each_pair { |okey, val| case key ||= okey when :name self.name = val when :value value = val when :domain domain = val when :path self.path = val when :origin origin = val when :for_domain, :for_domain? for_domain = val when :max_age # Let max_age take precedence over expires max_age = val when :expires, :expires_at self.expires = val unless max_age when :httponly, :httponly? @httponly = val when :secure, :secure? @secure = val when Symbol setter = :"#{key}=" if respond_to?(setter) __send__(setter, val) else warn "unknown attribute name: #{okey.inspect}" if $VERBOSE next end when String warn "use downcased symbol for keyword: #{okey.inspect}" if $VERBOSE key = key.downcase.to_sym redo else warn "invalid keyword ignored: #{okey.inspect}" if $VERBOSE next end } if @name.nil? raise ArgumentError, "name must be specified" end @for_domain = for_domain self.domain = domain if domain self.origin = origin if origin self.max_age = max_age if max_age self.value = value.nil? && (@expires || @max_age) ? '' : value end autoload :Scanner, 'http/cookie/scanner' class << self # Tests if +target_path+ is under +base_path+ as described in RFC # 6265 5.1.4. +base_path+ must be an absolute path. # +target_path+ may be empty, in which case it is treated as the # root path. # # e.g. # # path_match?('/admin/', '/admin/index') == true # path_match?('/admin/', '/Admin/index') == false # path_match?('/admin/', '/admin/') == true # path_match?('/admin/', '/admin') == false # # path_match?('/admin', '/admin') == true # path_match?('/admin', '/Admin') == false # path_match?('/admin', '/admins') == false # path_match?('/admin', '/admin/') == true # path_match?('/admin', '/admin/index') == true def path_match?(base_path, target_path) base_path.start_with?('/') or return false # RFC 6265 5.1.4 bsize = base_path.size tsize = target_path.size return bsize == 1 if tsize == 0 # treat empty target_path as "/" return false unless target_path.start_with?(base_path) return true if bsize == tsize || base_path.end_with?('/') target_path[bsize] == ?/ end # Parses a Set-Cookie header value `set_cookie` assuming that it # is sent from a source URI/URL `origin`, and returns an array of # Cookie objects. Parts (separated by commas) that are malformed # or considered unacceptable are silently ignored. # # If a block is given, each cookie object is passed to the block. # # Available option keywords are below: # # :created_at # : The creation time of the cookies parsed. # # :logger # : Logger object useful for debugging # # ### Compatibility Note for Mechanize::Cookie users # # * Order of parameters changed in HTTP::Cookie.parse: # # Mechanize::Cookie.parse(uri, set_cookie[, log]) # # HTTP::Cookie.parse(set_cookie, uri[, :logger => # log]) # # * HTTP::Cookie.parse does not accept nil for `set_cookie`. # # * HTTP::Cookie.parse does not yield nil nor include nil in an # returned array. It simply ignores unparsable parts. # # * HTTP::Cookie.parse is made to follow RFC 6265 to the extent # not terribly breaking interoperability with broken # implementations. In particular, it is capable of parsing # cookie definitions containing double-quotes just as naturally # expected. def parse(set_cookie, origin, options = nil, &block) if options logger = options[:logger] created_at = options[:created_at] end origin = HTTP::Cookie::URIParser.parse(origin) [].tap { |cookies| Scanner.new(set_cookie, logger).scan_set_cookie { |name, value, attrs| break if name.nil? || name.empty? begin cookie = new(name, value) rescue => e logger.warn("Invalid name or value: #{e}") if logger next end cookie.created_at = created_at if created_at attrs.each { |aname, avalue| begin case aname when 'domain' cookie.for_domain = true # The following may negate @for_domain if the value is # an eTLD or IP address, hence this order. cookie.domain = avalue when 'path' cookie.path = avalue when 'expires' # RFC 6265 4.1.2.2 # The Max-Age attribute has precedence over the Expires # attribute. cookie.expires = avalue unless cookie.max_age when 'max-age' cookie.max_age = avalue when 'secure' cookie.secure = avalue when 'httponly' cookie.httponly = avalue end rescue => e logger.warn("Couldn't parse #{aname} '#{avalue}': #{e}") if logger end } cookie.origin = origin cookie.acceptable? or next yield cookie if block_given? cookies << cookie } } end # Takes an array of cookies and returns a string for use in the # Cookie header, like "name1=value2; name2=value2". def cookie_value(cookies) cookies.join('; ') end # Parses a Cookie header value into a hash of name-value string # pairs. The first appearance takes precedence if multiple pairs # with the same name occur. def cookie_value_to_hash(cookie_value) {}.tap { |hash| Scanner.new(cookie_value).scan_cookie { |name, value| hash[name] ||= value } } end end attr_reader :name # See #name. def name= name name = (String.try_convert(name) or raise TypeError, "#{name.class} is not a String") if name.empty? raise ArgumentError, "cookie name cannot be empty" elsif name.match(/[\x00-\x20\x7F,;\\"=]/) raise ArgumentError, "invalid cookie name" end # RFC 6265 4.1.1 # cookie-name may not match: # /[\x00-\x20\x7F()<>@,;:\\"\/\[\]?={}]/ @name = name end attr_reader :value # See #value. def value= value if value.nil? self.expires = UNIX_EPOCH return @value = '' end value = (String.try_convert(value) or raise TypeError, "#{value.class} is not a String") if value.match(/[\x00-\x1F\x7F]/) raise ArgumentError, "invalid cookie value" end # RFC 6265 4.1.1 # cookie-name may not match: # /[^\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]/ @value = value end attr_reader :domain # See #domain. def domain= domain case domain when nil @for_domain = false if @origin @domain_name = DomainName.new(@origin.host) @domain = @domain_name.hostname else @domain_name = @domain = nil end return nil when DomainName @domain_name = domain else domain = (String.try_convert(domain) or raise TypeError, "#{domain.class} is not a String") if domain.start_with?('.') for_domain = true domain = domain[1..-1] end if domain.empty? return self.domain = nil end # Do we really need to support this? if domain.match(/\A([^:]+):[0-9]+\z/) domain = $1 end @domain_name = DomainName.new(domain) end # RFC 6265 5.3 5. if domain_name.domain.nil? # a public suffix or IP address @for_domain = false else @for_domain = for_domain unless for_domain.nil? end @domain = @domain_name.hostname end # Returns the domain, with a dot prefixed only if the domain flag is # on. def dot_domain @for_domain ? (+'.') << @domain : @domain end # Returns the domain attribute value as a DomainName object. attr_reader :domain_name # The domain flag. (the opposite of host-only-flag) # # If this flag is true, this cookie will be sent to any host in the # \#domain, including the host domain itself. If it is false, this # cookie will be sent only to the host indicated by the #domain. attr_accessor :for_domain alias for_domain? for_domain attr_reader :path # See #path. def path= path path = (String.try_convert(path) or raise TypeError, "#{path.class} is not a String") @path = path.start_with?('/') ? path : '/' end attr_reader :origin # See #origin. def origin= origin return origin if origin == @origin @origin.nil? or raise ArgumentError, "origin cannot be changed once it is set" # Delay setting @origin because #domain= or #path= may fail origin = HTTP::Cookie::URIParser.parse(origin) if URI::HTTP === origin self.domain ||= origin.host self.path ||= (origin + './').path end @origin = origin end # The secure flag. (secure-only-flag) # # A cookie with this flag on should only be sent via a secure # protocol like HTTPS. attr_accessor :secure alias secure? secure # The HttpOnly flag. (http-only-flag) # # A cookie with this flag on should be hidden from a client script. attr_accessor :httponly alias httponly? httponly # The session flag. (the opposite of persistent-flag) # # A cookie with this flag on should be hidden from a client script. attr_reader :session alias session? session def expires @expires or @created_at && @max_age ? @created_at + @max_age : nil end # See #expires. def expires= t case t when nil, Time when DateTime t = t.to_time else t = Time.parse(t) end @max_age = nil @session = t.nil? @expires = t end alias expires_at expires alias expires_at= expires= attr_reader :max_age # See #max_age. def max_age= sec case sec when Integer, nil else str = String.try_convert(sec) or raise TypeError, "#{sec.class} is not an Integer or String" /\A-?\d+\z/.match(str) or raise ArgumentError, "invalid Max-Age: #{sec.inspect}" sec = str.to_i end @expires = nil if @session = sec.nil? @max_age = nil else @max_age = sec end end # Tests if this cookie is expired by now, or by a given time. def expired?(time = Time.now) if expires = self.expires expires <= time else false end end # Expires this cookie by setting the expires attribute value to a # past date. def expire! self.expires = UNIX_EPOCH self end # The time this cookie was created at. This value is used as a base # date for interpreting the Max-Age attribute value. See #expires. attr_accessor :created_at # The time this cookie was last accessed at. attr_accessor :accessed_at # Tests if it is OK to accept this cookie if it is sent from a given # URI/URL, `uri`. def acceptable_from_uri?(uri) uri = HTTP::Cookie::URIParser.parse(uri) return false unless URI::HTTP === uri && uri.host host = DomainName.new(uri.host) # RFC 6265 5.3 case when host.hostname == @domain true when @for_domain # !host-only-flag host.cookie_domain?(@domain_name) else @domain.nil? end end # Tests if it is OK to accept this cookie considering its origin. # If either domain or path is missing, raises ArgumentError. If # origin is missing, returns true. def acceptable? case when @domain.nil? raise "domain is missing" when @path.nil? raise "path is missing" when @origin.nil? true else acceptable_from_uri?(@origin) end end # Tests if it is OK to send this cookie to a given `uri`. A # RuntimeError is raised if the cookie's domain is unknown. def valid_for_uri?(uri) if @domain.nil? raise "cannot tell if this cookie is valid because the domain is unknown" end uri = HTTP::Cookie::URIParser.parse(uri) # RFC 6265 5.4 return false if secure? && !(URI::HTTPS === uri) acceptable_from_uri?(uri) && HTTP::Cookie.path_match?(@path, uri.path) end # Returns a string for use in the Cookie header, i.e. `name=value` # or `name="value"`. def cookie_value +"#{@name}=#{Scanner.quote(@value)}" end alias to_s cookie_value # Returns a string for use in the Set-Cookie header. If necessary # information like a path or domain (when `for_domain` is set) is # missing, RuntimeError is raised. It is always the best to set an # origin before calling this method. def set_cookie_value string = cookie_value if @for_domain if @domain string << "; Domain=#{@domain}" else raise "for_domain is specified but domain is unknown" end end if @path if !@origin || (@origin + './').path != @path string << "; Path=#{@path}" end else raise "path is unknown" end if @max_age string << "; Max-Age=#{@max_age}" elsif @expires string << "; Expires=#{@expires.httpdate}" end if @httponly string << "; HttpOnly" end if @secure string << "; Secure" end string end def inspect '#<%s:' % self.class << PERSISTENT_PROPERTIES.map { |key| '%s=%s' % [key, instance_variable_get(:"@#{key}").inspect] }.join(', ') << ' origin=%s>' % [@origin ? @origin.to_s : 'nil'] end # Compares the cookie with another. When there are many cookies with # the same name for a URL, the value of the smallest must be used. def <=> other # RFC 6265 5.4 # Precedence: 1. longer path 2. older creation (@name <=> other.name).nonzero? || (other.path.length <=> @path.length).nonzero? || (@created_at <=> other.created_at).nonzero? || @value <=> other.value end include Comparable # Hash serialization helper for use back into other libraries (Like Selenium) def to_h PERSISTENT_PROPERTIES.each_with_object({}) { |property, hash| hash[property.to_sym] = instance_variable_get("@#{property}") } end # YAML serialization helper for Syck. def to_yaml_properties PERSISTENT_PROPERTIES.map { |name| "@#{name}" } end # YAML serialization helper for Psych. def encode_with(coder) PERSISTENT_PROPERTIES.each { |key| coder[key.to_s] = instance_variable_get(:"@#{key}") } end # YAML deserialization helper for Syck. def init_with(coder) yaml_initialize(coder.tag, coder.map) end # YAML deserialization helper for Psych. def yaml_initialize(tag, map) expires = nil @origin = nil map.each { |key, value| case key when 'expires' # avoid clobbering max_age expires = value when *PERSISTENT_PROPERTIES __send__(:"#{key}=", value) end } self.expires = expires if self.max_age.nil? end end
ruby
MIT
e5b73f3b0a3331a6591a928c1ad49dbe3aed4065
2026-01-04T17:56:01.207236Z
false
sparklemotion/http-cookie
https://github.com/sparklemotion/http-cookie/blob/e5b73f3b0a3331a6591a928c1ad49dbe3aed4065/lib/http/cookie/version.rb
lib/http/cookie/version.rb
module HTTP class Cookie VERSION = "1.1.0" end end
ruby
MIT
e5b73f3b0a3331a6591a928c1ad49dbe3aed4065
2026-01-04T17:56:01.207236Z
false
sparklemotion/http-cookie
https://github.com/sparklemotion/http-cookie/blob/e5b73f3b0a3331a6591a928c1ad49dbe3aed4065/lib/http/cookie/uri_parser.rb
lib/http/cookie/uri_parser.rb
module HTTP::Cookie::URIParser module_function # Regular Expression taken from RFC 3986 Appendix B URIREGEX = %r{ \A (?: (?<scheme> [^:/?\#]+ ) : )? (?: // (?<authority> [^/?\#]* ) )? (?<path> [^?\#]* ) (?: \? (?<query> [^\#]* ) )? (?: \# (?<fragment> .* ) )? \z }x # Escape RFC 3986 "reserved" characters minus valid characters for path # More specifically, gen-delims minus "/" / "?" / "#" def escape_path(path) path.sub(/\A[^?#]+/) { |p| p.gsub(/[:\[\]@]+/) { |r| CGI.escape(r) } } end # Parse a URI string or object, relaxing the constraints on the path component def parse(uri) URI(uri) rescue URI::InvalidURIError str = String.try_convert(uri) or raise ArgumentError, "bad argument (expected URI object or URI string)" m = URIREGEX.match(str) or raise path = m[:path] str[m.begin(:path)...m.end(:path)] = escape_path(path) uri = URI.parse(str) uri.__send__(:set_path, path) uri end end
ruby
MIT
e5b73f3b0a3331a6591a928c1ad49dbe3aed4065
2026-01-04T17:56:01.207236Z
false
sparklemotion/http-cookie
https://github.com/sparklemotion/http-cookie/blob/e5b73f3b0a3331a6591a928c1ad49dbe3aed4065/lib/http/cookie/ruby_compat.rb
lib/http/cookie/ruby_compat.rb
class Array def select! # :yield: x i = 0 each_with_index { |x, j| yield x or next self[i] = x if i != j i += 1 } return nil if i == size self[i..-1] = [] self end unless method_defined?(:select!) def sort_by!(&block) # :yield: x replace(sort_by(&block)) end unless method_defined?(:sort_by!) end class Hash class << self def try_convert(object) if object.is_a?(Hash) || (object.respond_to?(:to_hash) && (object = object.to_hash).is_a?(Hash)) object else nil end end unless method_defined?(:try_convert) end end class String class << self def try_convert(object) if object.is_a?(String) || (object.respond_to?(:to_str) && (object = object.to_str).is_a?(String)) object else nil end end unless method_defined?(:try_convert) end end # In Ruby < 1.9.3 URI() does not accept a URI object. if RUBY_VERSION < "1.9.3" require 'uri' begin URI(URI('')) rescue def URI(url) # :nodoc: case url when URI url when String URI.parse(url) else raise ArgumentError, 'bad argument (expected URI object or URI string)' end end end end
ruby
MIT
e5b73f3b0a3331a6591a928c1ad49dbe3aed4065
2026-01-04T17:56:01.207236Z
false
sparklemotion/http-cookie
https://github.com/sparklemotion/http-cookie/blob/e5b73f3b0a3331a6591a928c1ad49dbe3aed4065/lib/http/cookie/scanner.rb
lib/http/cookie/scanner.rb
# frozen_string_literal: true require 'http/cookie' require 'strscan' require 'time' class HTTP::Cookie::Scanner < StringScanner # Whitespace. RE_WSP = /[ \t]+/ # A pattern that matches a cookie name or attribute name which may # be empty, capturing trailing whitespace. RE_NAME = /(?!#{RE_WSP})[^,;\\"=]*/ RE_BAD_CHAR = /([\x00-\x20\x7F",;\\])/ # A pattern that matches the comma in a (typically date) value. RE_COOKIE_COMMA = /,(?=#{RE_WSP}?#{RE_NAME}=)/ def initialize(string, logger = nil) @logger = logger super(string) end class << self def quote(s) return s unless s.match(RE_BAD_CHAR) (+'"') << s.gsub(/([\\"])/, "\\\\\\1") << '"' end end def skip_wsp skip(RE_WSP) end def scan_dquoted (+'').tap { |s| case when skip(/"/) break when skip(/\\/) s << getch when scan(/[^"\\]+/) s << matched end until eos? } end def scan_name scan(RE_NAME).tap { |s| s.rstrip! if s } end def scan_value(comma_as_separator = false) (+'').tap { |s| case when scan(/[^,;"]+/) s << matched when skip(/"/) # RFC 6265 2.2 # A cookie-value may be DQUOTE'd. s << scan_dquoted when check(/;/) break when comma_as_separator && check(RE_COOKIE_COMMA) break else s << getch end until eos? s.rstrip! } end def scan_name_value(comma_as_separator = false) name = scan_name if skip(/\=/) value = scan_value(comma_as_separator) else scan_value(comma_as_separator) value = nil end [name, value] end if Time.respond_to?(:strptime) def tuple_to_time(day_of_month, month, year, time) Time.strptime( '%02d %s %04d %02d:%02d:%02d UTC' % [day_of_month, month, year, *time], '%d %b %Y %T %Z' ).tap { |date| date.day == day_of_month or return nil } end else def tuple_to_time(day_of_month, month, year, time) Time.parse( '%02d %s %04d %02d:%02d:%02d UTC' % [day_of_month, month, year, *time] ).tap { |date| date.day == day_of_month or return nil } end end private :tuple_to_time def parse_cookie_date(s) # RFC 6265 5.1.1 time = day_of_month = month = year = nil s.split(/[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]+/).each { |token| case when time.nil? && token.match(/\A(\d{1,2}):(\d{1,2})(?::(\d{1,2}))?(?=\D|\z)/) sec = if $3 $3.to_i else # violation of the RFC @logger.warn("Time lacks the second part: #{token}") if @logger 0 end time = [$1.to_i, $2.to_i, sec] when day_of_month.nil? && token.match(/\A(\d{1,2})(?=\D|\z)/) day_of_month = $1.to_i when month.nil? && token.match(/\A(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i) month = $1.capitalize when year.nil? && token.match(/\A(\d{2,4})(?=\D|\z)/) year = $1.to_i end } if day_of_month.nil? || month.nil? || year.nil? || time.nil? return nil end case day_of_month when 1..31 else return nil end case year when 100..1600 return nil when 70..99 year += 1900 when 0..69 year += 2000 end hh, mm, ss = time if hh > 23 || mm > 59 || ss > 59 return nil end tuple_to_time(day_of_month, month, year, time) end def scan_set_cookie # RFC 6265 4.1.1 & 5.2 until eos? start = pos len = nil skip_wsp name, value = scan_name_value(true) if value.nil? @logger.warn("Cookie definition lacks a name-value pair.") if @logger elsif name.empty? @logger.warn("Cookie definition has an empty name.") if @logger value = nil end attrs = {} case when skip(/,/) # The comma is used as separator for concatenating multiple # values of a header. len = (pos - 1) - start break when skip(/;/) skip_wsp aname, avalue = scan_name_value(true) next if aname.empty? || value.nil? aname.downcase! case aname when 'expires' # RFC 6265 5.2.1 avalue &&= parse_cookie_date(avalue) or next when 'max-age' # RFC 6265 5.2.2 next unless /\A-?\d+\z/.match(avalue) when 'domain' # RFC 6265 5.2.3 # An empty value SHOULD be ignored. next if avalue.nil? || avalue.empty? when 'path' # RFC 6265 5.2.4 # A relative path must be ignored rather than normalizing it # to "/". next unless /\A\//.match(avalue) when 'secure', 'httponly' # RFC 6265 5.2.5, 5.2.6 avalue = true end attrs[aname] = avalue end until eos? len ||= pos - start if len > HTTP::Cookie::MAX_LENGTH @logger.warn("Cookie definition too long: #{name}") if @logger next end yield name, value, attrs if value end end def scan_cookie # RFC 6265 4.1.1 & 5.4 until eos? skip_wsp # Do not treat comma in a Cookie header value as separator; see CVE-2016-7401 name, value = scan_name_value(false) yield name, value if value skip(/;/) end end end
ruby
MIT
e5b73f3b0a3331a6591a928c1ad49dbe3aed4065
2026-01-04T17:56:01.207236Z
false
sparklemotion/http-cookie
https://github.com/sparklemotion/http-cookie/blob/e5b73f3b0a3331a6591a928c1ad49dbe3aed4065/lib/http/cookie_jar/yaml_saver.rb
lib/http/cookie_jar/yaml_saver.rb
# :markup: markdown require 'http/cookie_jar' require 'psych' if !defined?(YAML) && RUBY_VERSION == "1.9.2" require 'yaml' # YAMLSaver saves and loads cookies in the YAML format. It can load a # YAML file saved by Mechanize, but the saving format is not # compatible with older versions of Mechanize (< 2.7). class HTTP::CookieJar::YAMLSaver < HTTP::CookieJar::AbstractSaver # :singleton-method: new # :call-seq: # new(**options) # # There is no option keyword supported at the moment. ## def save(io, jar) YAML.dump(@session ? jar.to_a : jar.reject(&:session?), io) end def load(io, jar) begin data = load_yaml(io) rescue ArgumentError => e case e.message when %r{\Aundefined class/module Mechanize::} # backward compatibility with Mechanize::Cookie begin io.rewind # hopefully yaml = io.read # a gross hack yaml.gsub!(%r{^( [^ ].*:) !ruby/object:Mechanize::Cookie$}, "\\1") data = load_yaml(yaml) rescue Errno::ESPIPE @logger.warn "could not rewind the stream for conversion" if @logger rescue ArgumentError end end end case data when Array data.each { |cookie| jar.add(cookie) } when Hash # backward compatibility with Mechanize::Cookie data.each { |domain, paths| paths.each { |path, names| names.each { |cookie_name, cookie_hash| if cookie_hash.respond_to?(:ivars) # YAML::Object of Syck cookie_hash = cookie_hash.ivars end cookie = HTTP::Cookie.new({}.tap { |hash| cookie_hash.each_pair { |key, value| hash[key.to_sym] = value } }) jar.add(cookie) } } } else @logger.warn "incompatible YAML cookie data discarded" if @logger return end end private def default_options {} end if YAML.name == 'Psych' && Psych::VERSION >= '3.1' def load_yaml(yaml) YAML.safe_load(yaml, :permitted_classes => %w[Time HTTP::Cookie Mechanize::Cookie DomainName], :aliases => true) end else def load_yaml(yaml) YAML.load(yaml) end end end
ruby
MIT
e5b73f3b0a3331a6591a928c1ad49dbe3aed4065
2026-01-04T17:56:01.207236Z
false
sparklemotion/http-cookie
https://github.com/sparklemotion/http-cookie/blob/e5b73f3b0a3331a6591a928c1ad49dbe3aed4065/lib/http/cookie_jar/abstract_store.rb
lib/http/cookie_jar/abstract_store.rb
# :markup: markdown require 'monitor' # An abstract superclass for all store classes. class HTTP::CookieJar::AbstractStore include MonitorMixin class << self @@class_map = {} # Gets an implementation class by the name, optionally trying to # load "http/cookie_jar/*_store" if not found. If loading fails, # IndexError is raised. def implementation(symbol) @@class_map.fetch(symbol) rescue IndexError begin require 'http/cookie_jar/%s_store' % symbol @@class_map.fetch(symbol) rescue LoadError, IndexError => e raise IndexError, 'cookie store unavailable: %s, error: %s' % [symbol.inspect, e.message] end end def inherited(subclass) # :nodoc: @@class_map[class_to_symbol(subclass)] = subclass end def class_to_symbol(klass) # :nodoc: klass.name[/[^:]+?(?=Store$|$)/].downcase.to_sym end end # Defines options and their default values. def default_options # {} end private :default_options # :call-seq: # new(**options) # # Called by the constructor of each subclass using super(). def initialize(options = nil) super() # MonitorMixin options ||= {} @logger = options[:logger] # Initializes each instance variable of the same name as option # keyword. default_options.each_pair { |key, default| instance_variable_set("@#{key}", options.fetch(key, default)) } end # This is an abstract method that each subclass must override. def initialize_copy(other) # self end # Implements HTTP::CookieJar#add(). # # This is an abstract method that each subclass must override. def add(cookie) # self end # Implements HTTP::CookieJar#delete(). # # This is an abstract method that each subclass must override. def delete(cookie) # self end # Iterates over all cookies that are not expired. # # An optional argument +uri+ specifies a URI object indicating the # destination of the cookies being selected. Every cookie yielded # should be good to send to the given URI, # i.e. cookie.valid_for_uri?(uri) evaluates to true. # # If (and only if) the +uri+ option is given, last access time of # each cookie is updated to the current time. # # This is an abstract method that each subclass must override. def each(uri = nil, &block) # :yield: cookie # if uri # ... # else # synchronize { # ... # } # end # self end include Enumerable # Implements HTTP::CookieJar#empty?(). def empty? each { return false } true end # Implements HTTP::CookieJar#clear(). # # This is an abstract method that each subclass must override. def clear # self end # Implements HTTP::CookieJar#cleanup(). # # This is an abstract method that each subclass must override. def cleanup(session = false) # if session # select { |cookie| cookie.session? || cookie.expired? } # else # select(&:expired?) # end.each { |cookie| # delete(cookie) # } # # subclasses can optionally remove over-the-limit cookies. # self end end
ruby
MIT
e5b73f3b0a3331a6591a928c1ad49dbe3aed4065
2026-01-04T17:56:01.207236Z
false
sparklemotion/http-cookie
https://github.com/sparklemotion/http-cookie/blob/e5b73f3b0a3331a6591a928c1ad49dbe3aed4065/lib/http/cookie_jar/hash_store.rb
lib/http/cookie_jar/hash_store.rb
# :markup: markdown require 'http/cookie_jar' class HTTP::CookieJar # A store class that uses a hash-based cookie store. # # In this store, cookies that share the same name, domain and path # will overwrite each other regardless of the `for_domain` flag # value. This store is built after the storage model described in # RFC 6265 5.3 where there is no mention of how the host-only-flag # affects in storing cookies. On the other hand, in MozillaStore # two cookies with the same name, domain and path coexist as long as # they differ in the `for_domain` flag value, which means they need # to be expired individually. class HashStore < AbstractStore def default_options { :gc_threshold => HTTP::Cookie::MAX_COOKIES_TOTAL / 20 } end # :call-seq: # new(**options) # # Generates a hash based cookie store. # # Available option keywords are as below: # # :gc_threshold # : GC threshold; A GC happens when this many times cookies have # been stored (default: `HTTP::Cookie::MAX_COOKIES_TOTAL / 20`) def initialize(options = nil) super @jar = { # hostname => { # path => { # name => cookie, # ... # }, # ... # }, # ... } @gc_index = 0 end # The copy constructor. This store class supports cloning. def initialize_copy(other) @jar = Marshal.load(Marshal.dump(other.instance_variable_get(:@jar))) end def add(cookie) path_cookies = ((@jar[cookie.domain] ||= {})[cookie.path] ||= {}) path_cookies[cookie.name] = cookie cleanup if (@gc_index += 1) >= @gc_threshold self end def delete(cookie) path_cookies = ((@jar[cookie.domain] ||= {})[cookie.path] ||= {}) path_cookies.delete(cookie.name) self end def each(uri = nil) # :yield: cookie now = Time.now if uri tpath = uri.path @jar.each { |domain, paths| paths.each { |path, hash| next unless HTTP::Cookie.path_match?(path, tpath) hash.delete_if { |name, cookie| if cookie.expired?(now) true else if cookie.valid_for_uri?(uri) cookie.accessed_at = now yield cookie end false end } } } else synchronize { @jar.each { |domain, paths| paths.each { |path, hash| hash.delete_if { |name, cookie| if cookie.expired?(now) true else yield cookie false end } } } } end self end def clear @jar.clear self end def cleanup(session = false) now = Time.now all_cookies = [] synchronize { break if @gc_index == 0 @jar.each { |domain, paths| domain_cookies = [] paths.each { |path, hash| hash.delete_if { |name, cookie| if cookie.expired?(now) || (session && cookie.session?) true else domain_cookies << cookie false end } } if (debt = domain_cookies.size - HTTP::Cookie::MAX_COOKIES_PER_DOMAIN) > 0 domain_cookies.sort_by!(&:created_at) domain_cookies.slice!(0, debt).each { |cookie| delete(cookie) } end all_cookies.concat(domain_cookies) } if (debt = all_cookies.size - HTTP::Cookie::MAX_COOKIES_TOTAL) > 0 all_cookies.sort_by!(&:created_at) all_cookies.slice!(0, debt).each { |cookie| delete(cookie) } end @jar.delete_if { |domain, paths| paths.delete_if { |path, hash| hash.empty? } paths.empty? } @gc_index = 0 } self end end end
ruby
MIT
e5b73f3b0a3331a6591a928c1ad49dbe3aed4065
2026-01-04T17:56:01.207236Z
false
sparklemotion/http-cookie
https://github.com/sparklemotion/http-cookie/blob/e5b73f3b0a3331a6591a928c1ad49dbe3aed4065/lib/http/cookie_jar/mozilla_store.rb
lib/http/cookie_jar/mozilla_store.rb
# :markup: markdown require 'http/cookie_jar' require 'sqlite3' class HTTP::CookieJar # A store class that uses Mozilla compatible SQLite3 database as # backing store. # # Session cookies are stored separately on memory and will not be # stored persistently in the SQLite3 database. class MozillaStore < AbstractStore # :stopdoc: SCHEMA_VERSION = 7 def default_options { :gc_threshold => HTTP::Cookie::MAX_COOKIES_TOTAL / 20, :app_id => 0, :in_browser_element => false, } end ALL_COLUMNS = %w[ baseDomain originAttributes name value host path expiry creationTime lastAccessed isSecure isHttpOnly appId inBrowserElement ] SQL = {} Callable = proc { |obj, meth, *args| proc { obj.__send__(meth, *args) } } class Database < SQLite3::Database def initialize(file, options = {}) @stmts = [] options = { :results_as_hash => true, }.update(options) super end def prepare(sql) case st = super when SQLite3::Statement @stmts << st end st end def close return self if closed? @stmts.reject! { |st| st.closed? || st.close } super end end # :startdoc: # :call-seq: # new(**options) # # Generates a Mozilla cookie store. If the file does not exist, # it is created. If it does and its schema is old, it is # automatically upgraded with a new schema keeping the existing # data. # # Available option keywords are as below: # # :filename # : A file name of the SQLite3 database to open. This option is # mandatory. # # :gc_threshold # : GC threshold; A GC happens when this many times cookies have # been stored (default: `HTTP::Cookie::MAX_COOKIES_TOTAL / 20`) # # :app_id # : application ID (default: `0`) to have per application jar. # # :in_browser_element # : a flag to tell if cookies are stored in an in browser # element. (default: `false`) def initialize(options = nil) super @origin_attributes = encode_www_form({}.tap { |params| params['appId'] = @app_id if @app_id.nonzero? params['inBrowserElement'] = 1 if @in_browser_element }) @filename = options[:filename] or raise ArgumentError, ':filename option is missing' @sjar = HTTP::CookieJar::HashStore.new @db = Database.new(@filename) @stmt = Hash.new { |st, key| st[key] = @db.prepare(SQL[key]) } ObjectSpace.define_finalizer(self, Callable[@db, :close]) upgrade_database @gc_index = 0 end # Raises TypeError. Cloning is inhibited in this store class. def initialize_copy(other) raise TypeError, 'can\'t clone %s' % self.class end # The file name of the SQLite3 database given in initialization. attr_reader :filename # Closes the SQLite3 database. After closing, any operation may # raise an error. def close @db.closed? || @db.close self end # Tests if the SQLite3 database is closed. def closed? @db.closed? end # Returns the schema version of the database. def schema_version @schema_version ||= @db.execute("PRAGMA user_version").first["user_version"] rescue SQLite3::SQLException @logger.warn "couldn't get schema version!" if @logger return nil end protected def schema_version= version @db.execute("PRAGMA user_version = %d" % version) @schema_version = version end def create_table_v5 self.schema_version = 5 @db.execute("DROP TABLE IF EXISTS moz_cookies") @db.execute(<<-'SQL') CREATE TABLE moz_cookies ( id INTEGER PRIMARY KEY, baseDomain TEXT, appId INTEGER DEFAULT 0, inBrowserElement INTEGER DEFAULT 0, name TEXT, value TEXT, host TEXT, path TEXT, expiry INTEGER, lastAccessed INTEGER, creationTime INTEGER, isSecure INTEGER, isHttpOnly INTEGER, CONSTRAINT moz_uniqueid UNIQUE (name, host, path, appId, inBrowserElement) ) SQL @db.execute(<<-'SQL') CREATE INDEX moz_basedomain ON moz_cookies (baseDomain, appId, inBrowserElement); SQL end def create_table_v6 self.schema_version = 6 @db.execute("DROP TABLE IF EXISTS moz_cookies") @db.execute(<<-'SQL') CREATE TABLE moz_cookies ( id INTEGER PRIMARY KEY, baseDomain TEXT, originAttributes TEXT NOT NULL DEFAULT '', name TEXT, value TEXT, host TEXT, path TEXT, expiry INTEGER, lastAccessed INTEGER, creationTime INTEGER, isSecure INTEGER, isHttpOnly INTEGER, CONSTRAINT moz_uniqueid UNIQUE (name, host, path, originAttributes) ) SQL @db.execute(<<-'SQL') CREATE INDEX moz_basedomain ON moz_cookies (baseDomain, originAttributes); SQL end def create_table self.schema_version = SCHEMA_VERSION @db.execute("DROP TABLE IF EXISTS moz_cookies") @db.execute(<<-'SQL') CREATE TABLE moz_cookies ( id INTEGER PRIMARY KEY, baseDomain TEXT, originAttributes TEXT NOT NULL DEFAULT '', name TEXT, value TEXT, host TEXT, path TEXT, expiry INTEGER, lastAccessed INTEGER, creationTime INTEGER, isSecure INTEGER, isHttpOnly INTEGER, appId INTEGER DEFAULT 0, inBrowserElement INTEGER DEFAULT 0, CONSTRAINT moz_uniqueid UNIQUE (name, host, path, originAttributes) ) SQL @db.execute(<<-'SQL') CREATE INDEX moz_basedomain ON moz_cookies (baseDomain, originAttributes); SQL end def db_prepare(sql) st = @db.prepare(sql) yield st ensure st.close if st end def upgrade_database loop { case schema_version when nil, 0 self.schema_version = SCHEMA_VERSION break when 1 @db.execute("ALTER TABLE moz_cookies ADD lastAccessed INTEGER") self.schema_version += 1 when 2 @db.execute("ALTER TABLE moz_cookies ADD baseDomain TEXT") db_prepare("UPDATE moz_cookies SET baseDomain = :baseDomain WHERE id = :id") { |st_update| @db.execute("SELECT id, host FROM moz_cookies") { |row| domain_name = DomainName.new(row['host'][/\A\.?(.*)/, 1]) domain = domain_name.domain || domain_name.hostname st_update.execute(:baseDomain => domain, :id => row['id']) } } @db.execute("CREATE INDEX moz_basedomain ON moz_cookies (baseDomain)") self.schema_version += 1 when 3 db_prepare("DELETE FROM moz_cookies WHERE id = :id") { |st_delete| prev_row = nil @db.execute(<<-'SQL') { |row| SELECT id, name, host, path FROM moz_cookies ORDER BY name ASC, host ASC, path ASC, expiry ASC SQL if %w[name host path].all? { |col| prev_row and row[col] == prev_row[col] } st_delete.execute(prev_row['id']) end prev_row = row } } @db.execute("ALTER TABLE moz_cookies ADD creationTime INTEGER") @db.execute("UPDATE moz_cookies SET creationTime = (SELECT id WHERE id = moz_cookies.id)") @db.execute("CREATE UNIQUE INDEX moz_uniqueid ON moz_cookies (name, host, path)") self.schema_version += 1 when 4 @db.execute("ALTER TABLE moz_cookies RENAME TO moz_cookies_old") @db.execute("DROP INDEX moz_basedomain") create_table_v5 @db.execute(<<-'SQL') INSERT INTO moz_cookies (baseDomain, appId, inBrowserElement, name, value, host, path, expiry, lastAccessed, creationTime, isSecure, isHttpOnly) SELECT baseDomain, 0, 0, name, value, host, path, expiry, lastAccessed, creationTime, isSecure, isHttpOnly FROM moz_cookies_old SQL @db.execute("DROP TABLE moz_cookies_old") when 5 @db.execute("ALTER TABLE moz_cookies RENAME TO moz_cookies_old") @db.execute("DROP INDEX moz_basedomain") create_table_v6 @db.create_function('CONVERT_TO_ORIGIN_ATTRIBUTES', 2) { |func, appId, inBrowserElement| params = {} params['appId'] = appId if appId.nonzero? params['inBrowserElement'] = inBrowserElement if inBrowserElement.nonzero? func.result = encode_www_form(params) } @db.execute(<<-'SQL') INSERT INTO moz_cookies (baseDomain, originAttributes, name, value, host, path, expiry, lastAccessed, creationTime, isSecure, isHttpOnly) SELECT baseDomain, CONVERT_TO_ORIGIN_ATTRIBUTES(appId, inBrowserElement), name, value, host, path, expiry, lastAccessed, creationTime, isSecure, isHttpOnly FROM moz_cookies_old SQL @db.execute("DROP TABLE moz_cookies_old") when 6 @db.execute("ALTER TABLE moz_cookies ADD appId INTEGER DEFAULT 0") @db.execute("ALTER TABLE moz_cookies ADD inBrowserElement INTEGER DEFAULT 0") @db.create_function('SET_APP_ID', 1) { |func, originAttributes| func.result = get_query_param(originAttributes, 'appId').to_i # nil.to_i == 0 } @db.create_function('SET_IN_BROWSER', 1) { |func, originAttributes| func.result = get_query_param(originAttributes, 'inBrowserElement').to_i # nil.to_i == 0 } @db.execute(<<-'SQL') UPDATE moz_cookies SET appId = SET_APP_ID(originAttributes), inBrowserElement = SET_IN_BROWSER(originAttributes) SQL @logger.info("Upgraded database to schema version %d" % schema_version) if @logger self.schema_version += 1 else break end } begin @db.execute("SELECT %s from moz_cookies limit 1" % ALL_COLUMNS.join(', ')) rescue SQLite3::SQLException create_table end end SQL[:add] = <<-'SQL' % [ INSERT OR REPLACE INTO moz_cookies (%s) VALUES (%s) SQL ALL_COLUMNS.join(', '), ALL_COLUMNS.map { |col| ":#{col}" }.join(', ') ] def db_add(cookie) @stmt[:add].execute({ :baseDomain => cookie.domain_name.domain || cookie.domain, :originAttributes => @origin_attributes, :name => cookie.name, :value => cookie.value, :host => cookie.dot_domain, :path => cookie.path, :expiry => cookie.expires_at.to_i, :creationTime => serialize_usectime(cookie.created_at), :lastAccessed => serialize_usectime(cookie.accessed_at), :isSecure => cookie.secure? ? 1 : 0, :isHttpOnly => cookie.httponly? ? 1 : 0, :appId => @app_id, :inBrowserElement => @in_browser_element ? 1 : 0, }) cleanup if (@gc_index += 1) >= @gc_threshold self end SQL[:delete] = <<-'SQL' DELETE FROM moz_cookies WHERE appId = :appId AND inBrowserElement = :inBrowserElement AND name = :name AND host = :host AND path = :path SQL def db_delete(cookie) @stmt[:delete].execute({ :appId => @app_id, :inBrowserElement => @in_browser_element ? 1 : 0, :name => cookie.name, :host => cookie.dot_domain, :path => cookie.path, }) self end if RUBY_VERSION >= '1.9' def encode_www_form(enum) URI.encode_www_form(enum) end def get_query_param(str, key) URI.decode_www_form(str).find { |k, v| break v if k == key } end else def encode_www_form(enum) enum.map { |k, v| "#{CGI.escape(k)}=#{CGI.escape(v)}" }.join('&') end def get_query_param(str, key) CGI.parse(str)[key].first end end def serialize_usectime(time) time ? (time.to_f * 1e6).floor : 0 end def deserialize_usectime(value) Time.at(value ? value / 1e6 : 0) end public def add(cookie) if cookie.session? @sjar.add(cookie) db_delete(cookie) else @sjar.delete(cookie) db_add(cookie) end end def delete(cookie) @sjar.delete(cookie) db_delete(cookie) end SQL[:cookies_for_domain] = <<-'SQL' SELECT * FROM moz_cookies WHERE baseDomain = :baseDomain AND appId = :appId AND inBrowserElement = :inBrowserElement AND expiry >= :expiry SQL SQL[:update_lastaccessed] = <<-'SQL' UPDATE moz_cookies SET lastAccessed = :lastAccessed WHERE id = :id SQL SQL[:all_cookies] = <<-'SQL' SELECT * FROM moz_cookies WHERE appId = :appId AND inBrowserElement = :inBrowserElement AND expiry >= :expiry SQL def each(uri = nil, &block) # :yield: cookie now = Time.now if uri thost = DomainName.new(uri.host) @stmt[:cookies_for_domain].execute({ :baseDomain => thost.domain || thost.hostname, :appId => @app_id, :inBrowserElement => @in_browser_element ? 1 : 0, :expiry => now.to_i, }).each { |row| if secure = row['isSecure'] != 0 next unless URI::HTTPS === uri end cookie = HTTP::Cookie.new({}.tap { |attrs| attrs[:name] = row['name'] attrs[:value] = row['value'] attrs[:domain] = row['host'] attrs[:path] = row['path'] attrs[:expires_at] = Time.at(row['expiry']) attrs[:accessed_at] = deserialize_usectime(row['lastAccessed']) attrs[:created_at] = deserialize_usectime(row['creationTime']) attrs[:secure] = secure attrs[:httponly] = row['isHttpOnly'] != 0 }) if cookie.valid_for_uri?(uri) cookie.accessed_at = now @stmt[:update_lastaccessed].execute({ 'lastAccessed' => serialize_usectime(now), 'id' => row['id'], }) yield cookie end } @sjar.each(uri, &block) else @stmt[:all_cookies].execute({ :appId => @app_id, :inBrowserElement => @in_browser_element ? 1 : 0, :expiry => now.to_i, }).each { |row| cookie = HTTP::Cookie.new({}.tap { |attrs| attrs[:name] = row['name'] attrs[:value] = row['value'] attrs[:domain] = row['host'] attrs[:path] = row['path'] attrs[:expires_at] = Time.at(row['expiry']) attrs[:accessed_at] = deserialize_usectime(row['lastAccessed']) attrs[:created_at] = deserialize_usectime(row['creationTime']) attrs[:secure] = row['isSecure'] != 0 attrs[:httponly] = row['isHttpOnly'] != 0 }) yield cookie } @sjar.each(&block) end self end def clear @db.execute("DELETE FROM moz_cookies") @sjar.clear self end SQL[:delete_expired] = <<-'SQL' DELETE FROM moz_cookies WHERE expiry < :expiry SQL SQL[:overusing_domains] = <<-'SQL' SELECT LTRIM(host, '.') domain, COUNT(*) count FROM moz_cookies GROUP BY domain HAVING count > :count SQL SQL[:delete_per_domain_overuse] = <<-'SQL' DELETE FROM moz_cookies WHERE id IN ( SELECT id FROM moz_cookies WHERE LTRIM(host, '.') = :domain ORDER BY creationtime LIMIT :limit) SQL SQL[:delete_total_overuse] = <<-'SQL' DELETE FROM moz_cookies WHERE id IN ( SELECT id FROM moz_cookies ORDER BY creationTime ASC LIMIT :limit ) SQL def cleanup(session = false) synchronize { break if @gc_index == 0 @stmt[:delete_expired].execute({ 'expiry' => Time.now.to_i }) @stmt[:overusing_domains].execute({ 'count' => HTTP::Cookie::MAX_COOKIES_PER_DOMAIN }).each { |row| domain, count = row['domain'], row['count'] @stmt[:delete_per_domain_overuse].execute({ 'domain' => domain, 'limit' => count - HTTP::Cookie::MAX_COOKIES_PER_DOMAIN, }) } overrun = count - HTTP::Cookie::MAX_COOKIES_TOTAL if overrun > 0 @stmt[:delete_total_overuse].execute({ 'limit' => overrun }) end @gc_index = 0 } self end end end
ruby
MIT
e5b73f3b0a3331a6591a928c1ad49dbe3aed4065
2026-01-04T17:56:01.207236Z
false
sparklemotion/http-cookie
https://github.com/sparklemotion/http-cookie/blob/e5b73f3b0a3331a6591a928c1ad49dbe3aed4065/lib/http/cookie_jar/abstract_saver.rb
lib/http/cookie_jar/abstract_saver.rb
# :markup: markdown # An abstract superclass for all saver classes. class HTTP::CookieJar::AbstractSaver class << self @@class_map = {} # Gets an implementation class by the name, optionally trying to # load "http/cookie_jar/*_saver" if not found. If loading fails, # IndexError is raised. def implementation(symbol) @@class_map.fetch(symbol) rescue IndexError begin require 'http/cookie_jar/%s_saver' % symbol @@class_map.fetch(symbol) rescue LoadError, IndexError raise IndexError, 'cookie saver unavailable: %s' % symbol.inspect end end def inherited(subclass) # :nodoc: @@class_map[class_to_symbol(subclass)] = subclass end def class_to_symbol(klass) # :nodoc: klass.name[/[^:]+?(?=Saver$|$)/].downcase.to_sym end end # Defines options and their default values. def default_options # {} end private :default_options # :call-seq: # new(**options) # # Called by the constructor of each subclass using super(). def initialize(options = nil) options ||= {} @logger = options[:logger] @session = options[:session] # Initializes each instance variable of the same name as option # keyword. default_options.each_pair { |key, default| instance_variable_set("@#{key}", options.fetch(key, default)) } end # Implements HTTP::CookieJar#save(). # # This is an abstract method that each subclass must override. def save(io, jar) # self end # Implements HTTP::CookieJar#load(). # # This is an abstract method that each subclass must override. def load(io, jar) # self end end
ruby
MIT
e5b73f3b0a3331a6591a928c1ad49dbe3aed4065
2026-01-04T17:56:01.207236Z
false
sparklemotion/http-cookie
https://github.com/sparklemotion/http-cookie/blob/e5b73f3b0a3331a6591a928c1ad49dbe3aed4065/lib/http/cookie_jar/cookiestxt_saver.rb
lib/http/cookie_jar/cookiestxt_saver.rb
# :markup: markdown require 'http/cookie_jar' # CookiestxtSaver saves and loads cookies in the cookies.txt format. class HTTP::CookieJar::CookiestxtSaver < HTTP::CookieJar::AbstractSaver # :singleton-method: new # :call-seq: # new(**options) # # Available option keywords are below: # # * `:header` # # Specifies the header line not including a line feed, which is # only used by #save(). None is output if nil is # given. (default: `"# HTTP Cookie File"`) # # * `:linefeed` # # Specifies the line separator (default: `"\n"`). ## def save(io, jar) io.puts @header if @header jar.each { |cookie| next if !@session && cookie.session? io.print cookie_to_record(cookie) } end def load(io, jar) io.each_line { |line| cookie = parse_record(line) and jar.add(cookie) } end private def default_options { :header => "# HTTP Cookie File", :linefeed => "\n", } end # :stopdoc: True = "TRUE" False = "FALSE" HTTPONLY_PREFIX = '#HttpOnly_' RE_HTTPONLY_PREFIX = /\A#{HTTPONLY_PREFIX}/ # :startdoc: # Serializes the cookie into a cookies.txt line. def cookie_to_record(cookie) cookie.instance_eval { [ @httponly ? HTTPONLY_PREFIX + dot_domain : dot_domain, @for_domain ? True : False, @path, @secure ? True : False, expires.to_i, @name, @value ] }.join("\t") << @linefeed end # Parses a line from cookies.txt and returns a cookie object if the # line represents a cookie record or returns nil otherwise. def parse_record(line) case line when RE_HTTPONLY_PREFIX httponly = true line = $' when /\A#/ return nil else httponly = false end domain, s_for_domain, # Whether this cookie is for domain path, # Path for which the cookie is relevant s_secure, # Requires a secure connection s_expires, # Time the cookie expires (Unix epoch time) name, value = line.split("\t", 7) return nil if value.nil? value.chomp! if (expires_seconds = s_expires.to_i).nonzero? expires = Time.at(expires_seconds) return nil if expires < Time.now end HTTP::Cookie.new(name, value, :domain => domain, :for_domain => s_for_domain == True, :path => path, :secure => s_secure == True, :httponly => httponly, :expires => expires) end end
ruby
MIT
e5b73f3b0a3331a6591a928c1ad49dbe3aed4065
2026-01-04T17:56:01.207236Z
false
devsisters/eclair
https://github.com/devsisters/eclair/blob/792ffb8f965e719cd6c9d240a017f84a515a71e0/lib/eclair.rb
lib/eclair.rb
# frozen_string_literal: true module Eclair end require "eclair/providers/ec2" # require "curses" # require "zlib" # require "aws-sdk" # require "string_scorer" # require "pry" # require "eclair/item" # require "eclair/helpers/benchmark_helper" # require "eclair/helpers/common_helper" # require "eclair/helpers/aws_helper" # require "eclair/config" # require "eclair/version" # require "eclair/less_viewer" # require "eclair/grid" # require "eclair/column" # require "eclair/cell" # require "eclair/group" # require "eclair/instance" # require "eclair/console" # require "eclair/color"
ruby
MIT
792ffb8f965e719cd6c9d240a017f84a515a71e0
2026-01-04T17:56:03.303615Z
false
devsisters/eclair
https://github.com/devsisters/eclair/blob/792ffb8f965e719cd6c9d240a017f84a515a71e0/lib/eclair/provider.rb
lib/eclair/provider.rb
# frozen_string_literal: true require "eclair/config" module Eclair module Provider include ConfigHelper extend self attr_accessor :items def filter_items search_buffer @items.select{ |item| item&.search_key&.include?(search_buffer.downcase) || item.selected } end def require_prepare raise "Not prepared" unless @prepared end end end
ruby
MIT
792ffb8f965e719cd6c9d240a017f84a515a71e0
2026-01-04T17:56:03.303615Z
false
devsisters/eclair
https://github.com/devsisters/eclair/blob/792ffb8f965e719cd6c9d240a017f84a515a71e0/lib/eclair/version.rb
lib/eclair/version.rb
# frozen_string_literal: true module Eclair VERSION = "3.0.4" end
ruby
MIT
792ffb8f965e719cd6c9d240a017f84a515a71e0
2026-01-04T17:56:03.303615Z
false
devsisters/eclair
https://github.com/devsisters/eclair/blob/792ffb8f965e719cd6c9d240a017f84a515a71e0/lib/eclair/less_viewer.rb
lib/eclair/less_viewer.rb
# frozen_string_literal: true module Eclair module LessViewer extend self class ColorPP < ::PP def self.pp(obj, out = $>, width = 79) q = ColorPP.new(out, width) q.guard_inspect_key { q.pp obj } q.flush out << "\n" end def text(str, width = str.length) super(CodeRay.scan(str, :ruby).term, width) end end def show obj IO.popen("less -R -C", "w") do |f| ColorPP.pp(obj, f) end end end end
ruby
MIT
792ffb8f965e719cd6c9d240a017f84a515a71e0
2026-01-04T17:56:03.303615Z
false
devsisters/eclair
https://github.com/devsisters/eclair/blob/792ffb8f965e719cd6c9d240a017f84a515a71e0/lib/eclair/item.rb
lib/eclair/item.rb
# frozen_string_literal: true require "eclair/config" module Eclair class Item include ConfigHelper attr_accessor :selected, :visible def initialize @selected = false @visible = true end def toggle_select @selected = !@selected end def select state @selected = state end def id raise "Not Implemented" end def command raise "Not Implemented" end def header raise "Not Implemented" end def title raise "Not Implemented" end def search_key raise "Not Implemented" end end end
ruby
MIT
792ffb8f965e719cd6c9d240a017f84a515a71e0
2026-01-04T17:56:03.303615Z
false
devsisters/eclair
https://github.com/devsisters/eclair/blob/792ffb8f965e719cd6c9d240a017f84a515a71e0/lib/eclair/grid.rb
lib/eclair/grid.rb
# frozen_string_literal: true require "eclair/group_item" require "eclair/color" module Eclair class Grid attr_reader :mode def initialize keyword = "" case config.provider when :ec2 require "eclair/providers/ec2" @provider = EC2Provider when :k8s require "eclair/providers/k8s" @provider = K8sProvider when :gce require "eclair/providers/gce" @provider = GCEProvider end @item_class = @provider.item_class @scroll = config.columns.times.map{0} @header_rows = 4 @cursor = [0,0] @cell_width = Curses.stdscr.maxx/config.columns @maxy = Curses.stdscr.maxy - @header_rows @mode = :assign @search_buffer = "" @provider.prepare keyword assign at(*@cursor).select(true) draw_all transit_mode(:nav) end def move key return unless at(*@cursor) x,y = @cursor mx,my = { Curses::KEY_UP => [0,-1], ?k => [0,-1], Curses::KEY_DOWN => [0,1], ?j => [0,1], Curses::KEY_LEFT => [-1,0], ?h => [-1,0], Curses::KEY_RIGHT => [1,0], ?l => [1,0], }[key] newx = x loop do newx = (newx + mx) % @grid.length break if @grid[newx].length > 0 end newy = (y + my - @scroll[x] + @scroll[newx]) if my != 0 newy %= @grid[newx].length end if newy >= @grid[newx].length newy = @grid[newx].length-1 end move_cursor(newx, newy) end def space if @mode == :nav transit_mode(:sel) end at(*@cursor)&.toggle_select if @mode == :sel && @provider.items.all?{|i| !i.selected} transit_mode(:nav) end draw(*@cursor) end def action targets = @provider.items.select{|i| i.selected && i.connectable?} return if targets.empty? Curses.close_screen if targets.length == 1 cmd = targets.first.command else cmds = [] target_cmd = "" targets.each_with_index do |target, i| if i == 0 if ENV['TMUX'] # Eclair called inside of tmux # Create new session and save window id window_name = `tmux new-window -P -- '#{target.command}'`.strip target_cmd = "-t #{window_name}" else # Eclair called from outside of tmux # Create new session and save session session_name = "eclair#{Time.now.to_i}" target_cmd = "-t #{session_name}" `tmux new-session -d -s #{session_name} -- '#{target.command}'` end else # Split layout and cmds << "split-window #{target_cmd} -- '#{target.command}'" cmds << "select-layout #{target_cmd} tiled" end end cmds << "set-window-option #{target_cmd} synchronize-panes on" cmds << "attach #{target_cmd}" unless ENV['TMUX'] cmd = "tmux #{cmds.join(" \\; ")}" end system(cmd) exit() resize end def resize Curses.clear @scroll.fill(0) @cell_width = Curses.stdscr.maxx/config.columns @maxy = Curses.stdscr.maxy - @header_rows rescroll(*@cursor) draw_all end def transit_mode to return if to == @mode case @mode when :nav at(*@cursor)&.select(false) when :sel when :search when :assign end @mode = to case @mode when :nav at(*@cursor)&.select(true) when :sel when :search when :assign move_cursor(0,0) end draw_all end def start_search transit_mode(:search) end def end_search if @provider.items.any?{|i| i.selected} transit_mode(:sel) else transit_mode(:nav) end end def clear_search @search_buffer = "" update_search end def append_search key return unless key if @search_buffer.length > 0 && (key == 127 || key == Curses::KEY_BACKSPACE || key == 8) #backspace @search_buffer = @search_buffer.chop elsif key.to_s.length == 1 begin @search_buffer = @search_buffer + key.to_s rescue return end else return end update_search end private def move_cursor x, y prev = @cursor.dup @cursor = [x, y] prev_item = at(*prev) curr_item = at(*@cursor) rescroll(*@cursor) if @mode == :nav prev_item.select(false) curr_item.select(true) end draw(*prev) if prev_item draw(*@cursor) if curr_item update_header(curr_item.header) if curr_item end def update_header str, pos = 0 Curses.setpos(0, 0) Curses.clrtoeol Curses.addstr(@mode.to_s) str.split("\n").map(&:strip).each_with_index do |line, i| Curses.setpos(i + pos + 1, 0) Curses.clrtoeol Curses.addstr(line) end end def update_search assign Curses.clear draw_all Curses.setpos(@header_rows - 1, 0) Curses.clrtoeol if @mode != :search && @search_buffer.empty? update_header('/: Start search') else update_header("/#{@search_buffer}") end end def rescroll x, y unless (@scroll[x]...@maxy+@scroll[x]).include? y if y < @scroll[x] @scroll[x] = y elsif y >= @maxy @scroll[x] = y - @maxy + 1 end (@scroll[x]...@maxy+@scroll[x]).each do |ty| draw_item(x, ty) end end end def at x, y @grid[x][y] end def make_label target ind = (@mode != :nav && target.selected) ? "*" : " " label = "#{target.label} #{ind}" label.slice(0, @cell_width).ljust(@cell_width) end def draw_all @grid.each_with_index do |column, x| column.each_with_index do |_, y| draw_item(x,y) end end case @mode when :nav, :sel update_header(at(*@cursor)&.header || "No Match") end end def color x, y if @cursor == [x,y] Color.fetch(Curses::COLOR_BLACK, Curses::COLOR_CYAN) else Color.fetch(*@grid[x][y].color) end end def draw_item x, y target = @grid[x].select{|item| item.visible}[y] drawy = y - @scroll[x] if drawy < 0 || drawy + @header_rows >= Curses.stdscr.maxy return end cell_color = color(x,y) Curses.setpos(drawy + @header_rows, x * @cell_width) Curses.attron(cell_color) do Curses.addstr make_label(target) end Curses.refresh end def draw x, y target = @grid[x][y] draw_item(x, y) if target.is_a?(GroupItem) (y+1).upto(y+target.length).each do |ny| draw_item(x, ny) end end end def assign old_mode = @mode transit_mode(:assign) @grid = config.columns.times.map{[]} visible_items = @provider.filter_items(@search_buffer) @groups = visible_items.group_by(&config.group_by) @groups.each do |name, items| group_name = "#{name} (#{items.length})" target = @grid.min_by(&:length) target << @provider.group_class.new(group_name, items) items.sort_by(&:label).each do |item| target << item end end transit_mode(old_mode) end def config Eclair.config end end end
ruby
MIT
792ffb8f965e719cd6c9d240a017f84a515a71e0
2026-01-04T17:56:03.303615Z
false
devsisters/eclair
https://github.com/devsisters/eclair/blob/792ffb8f965e719cd6c9d240a017f84a515a71e0/lib/eclair/color.rb
lib/eclair/color.rb
# frozen_string_literal: true require 'curses' module Eclair module Color extend self def storage @storage ||= {} end def fetch fg, bg, options = 0 @idx ||= 1 unless storage[[fg,bg]] Curses.init_pair(@idx, fg, bg) storage[[fg,bg]] = @idx @idx += 1 end Curses.color_pair(storage[[fg,bg]]) | options end end end
ruby
MIT
792ffb8f965e719cd6c9d240a017f84a515a71e0
2026-01-04T17:56:03.303615Z
false
devsisters/eclair
https://github.com/devsisters/eclair/blob/792ffb8f965e719cd6c9d240a017f84a515a71e0/lib/eclair/config.rb
lib/eclair/config.rb
# frozen_string_literal: true require 'curses' module Eclair module ConfigHelper def config Eclair.config end end class Config KEYS_DIR = "#{ENV['HOME']}/.ecl/keys" CACHE_DIR = "#{ENV['HOME']}/.ecl/.cache" def initialize @done = false @config_file = ENV["ECLRC"] || "#{ENV['HOME']}/.ecl/config.rb" @aws_region = nil @columns = 4 @group_by = lambda do |instance| if instance.security_groups.first instance.security_groups.first.group_name else "no_group" end end @ssh_username = lambda do |image| case image.name when /ubuntu/ "ubuntu" else "ec2-user" end end @ssh_command = "ssh" @ssh_keys = {} @ssh_ports = [22].freeze @ssh_options = "-o ConnectTimeout=1 -o StrictHostKeyChecking=no".freeze @dir_keys = {} @exec_format = "{ssh_command} {ssh_options} -p{port} {ssh_key} {username}@{host}" @provider = :ec2 @get_pods_option = "" @use_vpc_id_env = false instance_variables.each do |var| Config.class_eval do attr_accessor var.to_s.tr("@","").to_sym end end # Migrate old ~/.eclrc to ~/.ecl/config.rb old_conf = "#{ENV['HOME']}/.eclrc" new_dir = "#{ENV['HOME']}/.ecl" new_conf = "#{ENV['HOME']}/.ecl/config.rb" if !File.exist?(new_conf) && File.exist?(old_conf) FileUtils.mkdir_p new_dir FileUtils.mv old_conf, new_conf puts "#{old_conf} migrated to #{new_conf}" puts "Please re-run eclair" exit end unless File.exist? @config_file template_path = File.join(File.dirname(__FILE__), "..", "..", "templates", "eclrc.template") FileUtils.mkdir_p(File.dirname(@config_file)) FileUtils.cp(template_path, @config_file) puts "#{@config_file} successfully created. Edit it and run again!" exit end key_path = "#{new_dir}/keys" FileUtils.mkdir_p key_path unless Dir.exist? key_path # FileUtils.mkdir_p CACHE_DIR unless Dir.exist? CACHE_DIR end def after_load dir_keys = {} Dir["#{KEYS_DIR}/*"].each do |key| if File.file? key dir_keys[File.basename(key, ".*")] = key end end @ssh_keys.merge!(dir_keys) end end extend self def init_config @config = Config.new load @config.config_file raise unless @done @config.after_load end def config if @config.aws_region ::Aws.config.update(region: @config.aws_region) end @config end def profile ENV["ECL_PROFILE"] || "default" end def configure name = "default" if profile == name @done = true yield config end end end
ruby
MIT
792ffb8f965e719cd6c9d240a017f84a515a71e0
2026-01-04T17:56:03.303615Z
false
devsisters/eclair
https://github.com/devsisters/eclair/blob/792ffb8f965e719cd6c9d240a017f84a515a71e0/lib/eclair/group_item.rb
lib/eclair/group_item.rb
# frozen_string_literal: true module Eclair class GroupItem < Item attr_reader :label attr_accessor :visible def initialize label, items @label = label @items = items @visible = true end def toggle_select if @items.all?(&:selected) @items.each{|i| i.select(false) } else @items.each{|i| i.select(true) } end end def select state @items.each{|i| i.select(state) } end def length @items.length end def color [Curses::COLOR_WHITE, -1, Curses::A_BOLD] end end end
ruby
MIT
792ffb8f965e719cd6c9d240a017f84a515a71e0
2026-01-04T17:56:03.303615Z
false
devsisters/eclair
https://github.com/devsisters/eclair/blob/792ffb8f965e719cd6c9d240a017f84a515a71e0/lib/eclair/providers/k8s.rb
lib/eclair/providers/k8s.rb
# frozen_string_literal: true require "eclair/providers/k8s/k8s_provider"
ruby
MIT
792ffb8f965e719cd6c9d240a017f84a515a71e0
2026-01-04T17:56:03.303615Z
false
devsisters/eclair
https://github.com/devsisters/eclair/blob/792ffb8f965e719cd6c9d240a017f84a515a71e0/lib/eclair/providers/ec2.rb
lib/eclair/providers/ec2.rb
# frozen_string_literal: true require "eclair/providers/ec2/ec2_provider"
ruby
MIT
792ffb8f965e719cd6c9d240a017f84a515a71e0
2026-01-04T17:56:03.303615Z
false
devsisters/eclair
https://github.com/devsisters/eclair/blob/792ffb8f965e719cd6c9d240a017f84a515a71e0/lib/eclair/providers/gce.rb
lib/eclair/providers/gce.rb
# frozen_string_literal: true require "eclair/providers/gce/gce_provider"
ruby
MIT
792ffb8f965e719cd6c9d240a017f84a515a71e0
2026-01-04T17:56:03.303615Z
false
devsisters/eclair
https://github.com/devsisters/eclair/blob/792ffb8f965e719cd6c9d240a017f84a515a71e0/lib/eclair/providers/ec2/ec2_item.rb
lib/eclair/providers/ec2/ec2_item.rb
# frozen_string_literal: true require 'shellwords' require "aws-sdk-ec2" require "eclair/item" require "eclair/providers/ec2/ec2_provider" module Eclair class EC2Item < Item attr_reader :instance def initialize instance super() @instance = instance end def id @instance.id end def color if @selected [Curses::COLOR_YELLOW, -1, Curses::A_BOLD] elsif !connectable? [Curses::COLOR_BLACK, -1, Curses::A_BOLD] else [Curses::COLOR_WHITE, -1] end end def command hosts = [@instance.public_ip_address, @instance.private_ip_address].compact ports = config.ssh_ports ssh_options = config.ssh_options ssh_command = config.ssh_command username = config.ssh_username.call(image) key_cmd = config.ssh_keys[@instance.key_name] ? "-i #{config.ssh_keys[@instance.key_name]}" : "" format = config.exec_format joined_cmd = hosts.map do |host| ports.map do |port| { "{ssh_command}" => ssh_command, "{ssh_options}" => ssh_options, "{port}" => port, "{ssh_key}" => key_cmd, "{username}" => username, "{host}" => host, }.reduce(format) { |cmd,pair| cmd.sub(pair[0],pair[1].to_s) } end end.join(" || ") # puts joined_cmd "echo Attaching to #{Shellwords.escape(name)} \\[#{@instance.instance_id}\\] && #{joined_cmd}" end def image @image ||= provider.find_image_by_id(@instance.image_id) end def vpc @vpc ||= provider.find_vpc_by_id(@instance.vpc_id) end def header <<-EOS #{name} (#{@instance.instance_id}) [#{@instance.state[:name]}] #{@instance.private_ip_address} launched at #{@instance.launch_time.to_time} EOS end def label " - #{name} [#{launched_at}]" end def info { instance: @instance, image: provider.image_loaded? ? image : "ami info not loaded yet", security_groups: provider.security_group_loaded? ? security_groups : "sg info not loaded yet", } end def connectable? ![32, 48, 80].include?(@instance.state[:code]) end def name return @name if @name begin tag = @instance.tags.find{|t| t.key == "Name"} @name = tag ? tag.value : "noname" rescue @name = "terminated" end end def security_groups @security_groups ||= @instance.security_groups.map{|sg| provider.find_security_group_by_id(sg.group_id)} end def search_key name.downcase end private def launched_at diff = Time.now - @instance.launch_time { "year" => 31557600, "month" => 2592000, "day" => 86400, "hour" => 3600, "minute" => 60, "second" => 1 }.each do |unit,v| if diff >= v value = (diff/v).to_i return "#{value} #{unit}#{value > 1 ? "s" : ""}" end end "now" end def provider EC2Provider end end end
ruby
MIT
792ffb8f965e719cd6c9d240a017f84a515a71e0
2026-01-04T17:56:03.303615Z
false
devsisters/eclair
https://github.com/devsisters/eclair/blob/792ffb8f965e719cd6c9d240a017f84a515a71e0/lib/eclair/providers/ec2/ec2_group_item.rb
lib/eclair/providers/ec2/ec2_group_item.rb
# frozen_string_literal: true require "eclair/group_item" module Eclair class EC2GroupItem < GroupItem def header running = @items.count{|i| i.instance.state[:code] == 16} all = @items.count <<-EOS Group #{label} #{running} Instances Running / #{all} Instances Total EOS end end end
ruby
MIT
792ffb8f965e719cd6c9d240a017f84a515a71e0
2026-01-04T17:56:03.303615Z
false
devsisters/eclair
https://github.com/devsisters/eclair/blob/792ffb8f965e719cd6c9d240a017f84a515a71e0/lib/eclair/providers/ec2/ec2_provider.rb
lib/eclair/providers/ec2/ec2_provider.rb
# frozen_string_literal: true require "aws-sdk-ec2" require "eclair/provider" require "eclair/providers/ec2/ec2_item" require "eclair/providers/ec2/ec2_group_item" module Eclair module EC2Provider extend Provider extend self def group_class EC2GroupItem end def item_class EC2Item end def prepare keyword Thread.abort_on_exception = true @instances ||= fetch_instances keyword image_ids = @instances.map(&:image_id).uniq @image_thread = Thread.new do @images = fetch_images(image_ids) @id_to_image = @images.map{|i| [i.image_id, i]}.to_h end @sg_thread = Thread.new do @security_groups = fetch_security_groups @id_to_sg = @security_groups.map{|i| [i.group_id, i]}.to_h end @vpc_thread = Thread.new do @vpcs = fetch_vpcs @id_to_vpc = @vpcs.map{|i| [i.vpc_id, i]}.to_h end @items = @instances.map{|i| EC2Item.new(i)} @prepared = true end def image_loaded? !@sg_thread.alive? end def images @image_thread.join if @image_thread.alive? @images end def find_image_by_id id @image_thread.join if @image_thread.alive? @id_to_image[id] end def security_group_loaded? !@sg_thread.alive? end def security_groups @sg_thread.join if @sg_thread.alive? @security_groups end def find_security_group_by_id id @sg_thread.join if @sg_thread.alive? @id_to_sg[id] end def vpc_loaded? !@vpc_thread.alive? end def vpcs @vpc_thread.join if @vpc_thread.alive? @vpcs end def find_vpc_by_id id @vpc_thread.join if @vpc_thread.alive? @id_to_vpc[id] end private def ec2_client @ec2_client ||= Aws::EC2::Client.new end def fetch_instances keyword filter = if keyword.empty? then {} else { filters: [{name: "tag:Name", values: ["*#{keyword}*"]}] } end if config.use_vpc_id_env then if filter.empty? then filter = { filters: [{name: "vpc-id", values: [ENV['VPC_ID']]}] } else filter[:filters].push({name: "vpc-id", values: [ENV['VPC_ID']]}) end end ec2_client.describe_instances(filter).map{ |resp| resp.data.reservations.map do |rsv| rsv.instances end }.flatten end def fetch_security_groups ec2_client.describe_security_groups.map{ |resp| resp.security_groups }.flatten end def fetch_images image_ids ec2_client.describe_images(image_ids: image_ids).images.flatten end def fetch_vpcs ec2_client.describe_vpcs.map{|resp| resp.vpcs}.flatten end end end
ruby
MIT
792ffb8f965e719cd6c9d240a017f84a515a71e0
2026-01-04T17:56:03.303615Z
false
devsisters/eclair
https://github.com/devsisters/eclair/blob/792ffb8f965e719cd6c9d240a017f84a515a71e0/lib/eclair/providers/k8s/k8s_item.rb
lib/eclair/providers/k8s/k8s_item.rb
# frozen_string_literal: true require 'eclair/item' require 'eclair/providers/k8s/k8s_provider' require 'time' module Eclair class K8sItem < Item attr_reader :pod def initialize pod super() @pod = pod end def id @pod["metadata"]["uid"] end def color if @selected [Curses::COLOR_YELLOW, -1, Curses::A_BOLD] elsif !connectable? [Curses::COLOR_BLACK, -1, Curses::A_BOLD] else [Curses::COLOR_WHITE, -1] end end def exec_command @pod["metadata"]["labels"]["eclair_exec_command"] || "/bin/sh" end def command "kubectl exec --namespace #{namespace} -ti #{name} #{exec_command}" end def header <<-EOS #{name} launched at #{launch_time.to_time} EOS end def label " - #{name} [#{launched_at}]" end def namespace @pod["metadata"]["namespace"] end def name @pod["metadata"]["name"] end def connectable? status == "running" end def search_key name.downcase end private def status @pod["status"]["containerStatuses"].first["state"].keys.first rescue nil end def launch_time Time.parse(@pod["metadata"]["creationTimestamp"]) end def launched_at diff = Time.now - launch_time { "year" => 31557600, "month" => 2592000, "day" => 86400, "hour" => 3600, "minute" => 60, "second" => 1 }.each do |unit,v| if diff >= v value = (diff/v).to_i return "#{value} #{unit}#{value > 1 ? "s" : ""}" end end "now" end end end
ruby
MIT
792ffb8f965e719cd6c9d240a017f84a515a71e0
2026-01-04T17:56:03.303615Z
false
devsisters/eclair
https://github.com/devsisters/eclair/blob/792ffb8f965e719cd6c9d240a017f84a515a71e0/lib/eclair/providers/k8s/k8s_provider.rb
lib/eclair/providers/k8s/k8s_provider.rb
# frozen_string_literal: true require 'eclair/provider' require 'eclair/providers/k8s/k8s_item' require 'eclair/providers/k8s/k8s_group_item' require 'oj' module Eclair module K8sProvider extend Provider extend self def group_class K8sGroupItem end def item_class K8sItem end def prepare keyword pods = Oj.load(`kubectl get pods #{config.get_pods_option} -o json`)["items"].select{|i| i["metadata"]["name"].include? keyword or i["metadata"]["namespace"].include? keyword} @items = pods.map{|i| K8sItem.new(i)} end def items @items end private def config Eclair.config end end end
ruby
MIT
792ffb8f965e719cd6c9d240a017f84a515a71e0
2026-01-04T17:56:03.303615Z
false
devsisters/eclair
https://github.com/devsisters/eclair/blob/792ffb8f965e719cd6c9d240a017f84a515a71e0/lib/eclair/providers/k8s/k8s_group_item.rb
lib/eclair/providers/k8s/k8s_group_item.rb
# frozen_string_literal: true require "eclair/group_item" module Eclair class K8sGroupItem < GroupItem def header all = @items.count <<-EOS Group #{label} #{all} pods Total EOS end end end
ruby
MIT
792ffb8f965e719cd6c9d240a017f84a515a71e0
2026-01-04T17:56:03.303615Z
false
devsisters/eclair
https://github.com/devsisters/eclair/blob/792ffb8f965e719cd6c9d240a017f84a515a71e0/lib/eclair/providers/gce/gce_group_item.rb
lib/eclair/providers/gce/gce_group_item.rb
# frozen_string_literal: true require "eclair/group_item" module Eclair class GCEGroupItem < GroupItem def header all = @items.count <<-EOS Group #{label} #{all} instances Total EOS end end end
ruby
MIT
792ffb8f965e719cd6c9d240a017f84a515a71e0
2026-01-04T17:56:03.303615Z
false
devsisters/eclair
https://github.com/devsisters/eclair/blob/792ffb8f965e719cd6c9d240a017f84a515a71e0/lib/eclair/providers/gce/gce_provider.rb
lib/eclair/providers/gce/gce_provider.rb
# frozen_string_literal: true require 'eclair/provider' require 'eclair/providers/gce/gce_item' require 'eclair/providers/gce/gce_group_item' require 'oj' module Eclair module GCEProvider extend Provider extend self def group_class GCEGroupItem end def item_class GCEItem end def prepare keyword instances = Oj.load(`gcloud compute instances list --format=json`) @items = instances.map{|i| GCEItem.new(i)} end def items @items end private def config Eclair.config end end end
ruby
MIT
792ffb8f965e719cd6c9d240a017f84a515a71e0
2026-01-04T17:56:03.303615Z
false
devsisters/eclair
https://github.com/devsisters/eclair/blob/792ffb8f965e719cd6c9d240a017f84a515a71e0/lib/eclair/providers/gce/gce_item.rb
lib/eclair/providers/gce/gce_item.rb
# frozen_string_literal: true require 'eclair/item' require 'eclair/providers/gce/gce_provider' require 'time' module Eclair class GCEItem < Item attr_reader :instance def initialize instance super() @instance = instance end def id @instance["id"] end def color if @selected [Curses::COLOR_YELLOW, -1, Curses::A_BOLD] elsif !connectable? [Curses::COLOR_BLACK, -1, Curses::A_BOLD] else [Curses::COLOR_WHITE, -1] end end def header <<-EOS #{name} (#{public_ip_address} #{private_ip_address}) launched at #{launch_time.to_time} #{description} EOS end def label " - #{name} [#{launched_at}]" end def description @instance["description"] end def name @instance["name"] end def public_ip_address @instance.dig("networkInterfaces", 0, "accessConfigs", 0, "natIP") end def private_ip_address @instance.dig("networkInterfaces", 0, "networkIP") end def command hosts = [private_ip_address, public_ip_address].compact ports = config.ssh_ports ssh_options = config.ssh_options ssh_command = config.ssh_command username = "ubuntu" format = config.exec_format joined_cmd = hosts.map do |host| ports.map do |port| { "{ssh_command}" => ssh_command, "{ssh_options}" => ssh_options, "{port}" => port, "{username}" => username, "{host}" => host, "{ssh_key}" => "" }.reduce(format) { |cmd,pair| cmd.sub(pair[0],pair[1].to_s) } end end.join(" || ") # puts joined_cmd "echo Attaching to #{name} \\[#{name}\\] && #{joined_cmd}" end def connectable? status == "RUNNING" end def search_key name.downcase end private def status @instance["status"] end def launch_time Time.parse(@instance["creationTimestamp"]).localtime end def launched_at diff = Time.now - launch_time { "year" => 31557600, "month" => 2592000, "day" => 86400, "hour" => 3600, "minute" => 60, "second" => 1 }.each do |unit,v| if diff >= v value = (diff/v).to_i return "#{value} #{unit}#{value > 1 ? "s" : ""}" end end "now" end end end
ruby
MIT
792ffb8f965e719cd6c9d240a017f84a515a71e0
2026-01-04T17:56:03.303615Z
false
jm/matchy
https://github.com/jm/matchy/blob/2e01918ad8d601685386aa9ac5d547ffb9b70b27/setup.rb
setup.rb
# # setup.rb # # Copyright (c) 2000-2005 Minero Aoki # # This program is free software. # You can distribute/modify this program under the terms of # the GNU LGPL, Lesser General Public License version 2.1. # unless Enumerable.method_defined?(:map) # Ruby 1.4.6 module Enumerable alias map collect end end unless File.respond_to?(:read) # Ruby 1.6 def File.read(fname) open(fname) {|f| return f.read } end end unless Errno.const_defined?(:ENOTEMPTY) # Windows? module Errno class ENOTEMPTY # We do not raise this exception, implementation is not needed. end end end def File.binread(fname) open(fname, 'rb') {|f| return f.read } end # for corrupted Windows' stat(2) def File.dir?(path) File.directory?((path[-1,1] == '/') ? path : path + '/') end class ConfigTable include Enumerable def initialize(rbconfig) @rbconfig = rbconfig @items = [] @table = {} # options @install_prefix = nil @config_opt = nil @verbose = true @no_harm = false end attr_accessor :install_prefix attr_accessor :config_opt attr_writer :verbose def verbose? @verbose end attr_writer :no_harm def no_harm? @no_harm end def [](key) lookup(key).resolve(self) end def []=(key, val) lookup(key).set val end def names @items.map {|i| i.name } end def each(&block) @items.each(&block) end def key?(name) @table.key?(name) end def lookup(name) @table[name] or setup_rb_error "no such config item: #{name}" end def add(item) @items.push item @table[item.name] = item end def remove(name) item = lookup(name) @items.delete_if {|i| i.name == name } @table.delete_if {|name, i| i.name == name } item end def load_script(path, inst = nil) if File.file?(path) MetaConfigEnvironment.new(self, inst).instance_eval File.read(path), path end end def savefile '.config' end def load_savefile begin File.foreach(savefile()) do |line| k, v = *line.split(/=/, 2) self[k] = v.strip end rescue Errno::ENOENT setup_rb_error $!.message + "\n#{File.basename($0)} config first" end end def save @items.each {|i| i.value } File.open(savefile(), 'w') {|f| @items.each do |i| f.printf "%s=%s\n", i.name, i.value if i.value? and i.value end } end def load_standard_entries standard_entries(@rbconfig).each do |ent| add ent end end def standard_entries(rbconfig) c = rbconfig rubypath = File.join(c['bindir'], c['ruby_install_name'] + c['EXEEXT']) major = c['MAJOR'].to_i minor = c['MINOR'].to_i teeny = c['TEENY'].to_i version = "#{major}.#{minor}" # ruby ver. >= 1.4.4? newpath_p = ((major >= 2) or ((major == 1) and ((minor >= 5) or ((minor == 4) and (teeny >= 4))))) if c['rubylibdir'] # V > 1.6.3 libruby = "#{c['prefix']}/lib/ruby" librubyver = c['rubylibdir'] librubyverarch = c['archdir'] siteruby = c['sitedir'] siterubyver = c['sitelibdir'] siterubyverarch = c['sitearchdir'] elsif newpath_p # 1.4.4 <= V <= 1.6.3 libruby = "#{c['prefix']}/lib/ruby" librubyver = "#{c['prefix']}/lib/ruby/#{version}" librubyverarch = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}" siteruby = c['sitedir'] siterubyver = "$siteruby/#{version}" siterubyverarch = "$siterubyver/#{c['arch']}" else # V < 1.4.4 libruby = "#{c['prefix']}/lib/ruby" librubyver = "#{c['prefix']}/lib/ruby/#{version}" librubyverarch = "#{c['prefix']}/lib/ruby/#{version}/#{c['arch']}" siteruby = "#{c['prefix']}/lib/ruby/#{version}/site_ruby" siterubyver = siteruby siterubyverarch = "$siterubyver/#{c['arch']}" end parameterize = lambda {|path| path.sub(/\A#{Regexp.quote(c['prefix'])}/, '$prefix') } if arg = c['configure_args'].split.detect {|arg| /--with-make-prog=/ =~ arg } makeprog = arg.sub(/'/, '').split(/=/, 2)[1] else makeprog = 'make' end [ ExecItem.new('installdirs', 'std/site/home', 'std: install under libruby; site: install under site_ruby; home: install under $HOME')\ {|val, table| case val when 'std' table['rbdir'] = '$librubyver' table['sodir'] = '$librubyverarch' when 'site' table['rbdir'] = '$siterubyver' table['sodir'] = '$siterubyverarch' when 'home' setup_rb_error '$HOME was not set' unless ENV['HOME'] table['prefix'] = ENV['HOME'] table['rbdir'] = '$libdir/ruby' table['sodir'] = '$libdir/ruby' end }, PathItem.new('prefix', 'path', c['prefix'], 'path prefix of target environment'), PathItem.new('bindir', 'path', parameterize.call(c['bindir']), 'the directory for commands'), PathItem.new('libdir', 'path', parameterize.call(c['libdir']), 'the directory for libraries'), PathItem.new('datadir', 'path', parameterize.call(c['datadir']), 'the directory for shared data'), PathItem.new('mandir', 'path', parameterize.call(c['mandir']), 'the directory for man pages'), PathItem.new('sysconfdir', 'path', parameterize.call(c['sysconfdir']), 'the directory for system configuration files'), PathItem.new('localstatedir', 'path', parameterize.call(c['localstatedir']), 'the directory for local state data'), PathItem.new('libruby', 'path', libruby, 'the directory for ruby libraries'), PathItem.new('librubyver', 'path', librubyver, 'the directory for standard ruby libraries'), PathItem.new('librubyverarch', 'path', librubyverarch, 'the directory for standard ruby extensions'), PathItem.new('siteruby', 'path', siteruby, 'the directory for version-independent aux ruby libraries'), PathItem.new('siterubyver', 'path', siterubyver, 'the directory for aux ruby libraries'), PathItem.new('siterubyverarch', 'path', siterubyverarch, 'the directory for aux ruby binaries'), PathItem.new('rbdir', 'path', '$siterubyver', 'the directory for ruby scripts'), PathItem.new('sodir', 'path', '$siterubyverarch', 'the directory for ruby extentions'), PathItem.new('rubypath', 'path', rubypath, 'the path to set to #! line'), ProgramItem.new('rubyprog', 'name', rubypath, 'the ruby program using for installation'), ProgramItem.new('makeprog', 'name', makeprog, 'the make program to compile ruby extentions'), SelectItem.new('shebang', 'all/ruby/never', 'ruby', 'shebang line (#!) editing mode'), BoolItem.new('without-ext', 'yes/no', 'no', 'does not compile/install ruby extentions') ] end private :standard_entries def load_multipackage_entries multipackage_entries().each do |ent| add ent end end def multipackage_entries [ PackageSelectionItem.new('with', 'name,name...', '', 'ALL', 'package names that you want to install'), PackageSelectionItem.new('without', 'name,name...', '', 'NONE', 'package names that you do not want to install') ] end private :multipackage_entries ALIASES = { 'std-ruby' => 'librubyver', 'stdruby' => 'librubyver', 'rubylibdir' => 'librubyver', 'archdir' => 'librubyverarch', 'site-ruby-common' => 'siteruby', # For backward compatibility 'site-ruby' => 'siterubyver', # For backward compatibility 'bin-dir' => 'bindir', 'bin-dir' => 'bindir', 'rb-dir' => 'rbdir', 'so-dir' => 'sodir', 'data-dir' => 'datadir', 'ruby-path' => 'rubypath', 'ruby-prog' => 'rubyprog', 'ruby' => 'rubyprog', 'make-prog' => 'makeprog', 'make' => 'makeprog' } def fixup ALIASES.each do |ali, name| @table[ali] = @table[name] end @items.freeze @table.freeze @options_re = /\A--(#{@table.keys.join('|')})(?:=(.*))?\z/ end def parse_opt(opt) m = @options_re.match(opt) or setup_rb_error "config: unknown option #{opt}" m.to_a[1,2] end def dllext @rbconfig['DLEXT'] end def value_config?(name) lookup(name).value? end class Item def initialize(name, template, default, desc) @name = name.freeze @template = template @value = default @default = default @description = desc end attr_reader :name attr_reader :description attr_accessor :default alias help_default default def help_opt "--#{@name}=#{@template}" end def value? true end def value @value end def resolve(table) @value.gsub(%r<\$([^/]+)>) { table[$1] } end def set(val) @value = check(val) end private def check(val) setup_rb_error "config: --#{name} requires argument" unless val val end end class BoolItem < Item def config_type 'bool' end def help_opt "--#{@name}" end private def check(val) return 'yes' unless val case val when /\Ay(es)?\z/i, /\At(rue)?\z/i then 'yes' when /\An(o)?\z/i, /\Af(alse)\z/i then 'no' else setup_rb_error "config: --#{@name} accepts only yes/no for argument" end end end class PathItem < Item def config_type 'path' end private def check(path) setup_rb_error "config: --#{@name} requires argument" unless path path[0,1] == '$' ? path : File.expand_path(path) end end class ProgramItem < Item def config_type 'program' end end class SelectItem < Item def initialize(name, selection, default, desc) super @ok = selection.split('/') end def config_type 'select' end private def check(val) unless @ok.include?(val.strip) setup_rb_error "config: use --#{@name}=#{@template} (#{val})" end val.strip end end class ExecItem < Item def initialize(name, selection, desc, &block) super name, selection, nil, desc @ok = selection.split('/') @action = block end def config_type 'exec' end def value? false end def resolve(table) setup_rb_error "$#{name()} wrongly used as option value" end undef set def evaluate(val, table) v = val.strip.downcase unless @ok.include?(v) setup_rb_error "invalid option --#{@name}=#{val} (use #{@template})" end @action.call v, table end end class PackageSelectionItem < Item def initialize(name, template, default, help_default, desc) super name, template, default, desc @help_default = help_default end attr_reader :help_default def config_type 'package' end private def check(val) unless File.dir?("packages/#{val}") setup_rb_error "config: no such package: #{val}" end val end end class MetaConfigEnvironment def initialize(config, installer) @config = config @installer = installer end def config_names @config.names end def config?(name) @config.key?(name) end def bool_config?(name) @config.lookup(name).config_type == 'bool' end def path_config?(name) @config.lookup(name).config_type == 'path' end def value_config?(name) @config.lookup(name).config_type != 'exec' end def add_config(item) @config.add item end def add_bool_config(name, default, desc) @config.add BoolItem.new(name, 'yes/no', default ? 'yes' : 'no', desc) end def add_path_config(name, default, desc) @config.add PathItem.new(name, 'path', default, desc) end def set_config_default(name, default) @config.lookup(name).default = default end def remove_config(name) @config.remove(name) end # For only multipackage def packages raise '[setup.rb fatal] multi-package metaconfig API packages() called for single-package; contact application package vendor' unless @installer @installer.packages end # For only multipackage def declare_packages(list) raise '[setup.rb fatal] multi-package metaconfig API declare_packages() called for single-package; contact application package vendor' unless @installer @installer.packages = list end end end # class ConfigTable # This module requires: #verbose?, #no_harm? module FileOperations def mkdir_p(dirname, prefix = nil) dirname = prefix + File.expand_path(dirname) if prefix $stderr.puts "mkdir -p #{dirname}" if verbose? return if no_harm? # Does not check '/', it's too abnormal. dirs = File.expand_path(dirname).split(%r<(?=/)>) if /\A[a-z]:\z/i =~ dirs[0] disk = dirs.shift dirs[0] = disk + dirs[0] end dirs.each_index do |idx| path = dirs[0..idx].join('') Dir.mkdir path unless File.dir?(path) end end def rm_f(path) $stderr.puts "rm -f #{path}" if verbose? return if no_harm? force_remove_file path end def rm_rf(path) $stderr.puts "rm -rf #{path}" if verbose? return if no_harm? remove_tree path end def remove_tree(path) if File.symlink?(path) remove_file path elsif File.dir?(path) remove_tree0 path else force_remove_file path end end def remove_tree0(path) Dir.foreach(path) do |ent| next if ent == '.' next if ent == '..' entpath = "#{path}/#{ent}" if File.symlink?(entpath) remove_file entpath elsif File.dir?(entpath) remove_tree0 entpath else force_remove_file entpath end end begin Dir.rmdir path rescue Errno::ENOTEMPTY # directory may not be empty end end def move_file(src, dest) force_remove_file dest begin File.rename src, dest rescue File.open(dest, 'wb') {|f| f.write File.binread(src) } File.chmod File.stat(src).mode, dest File.unlink src end end def force_remove_file(path) begin remove_file path rescue end end def remove_file(path) File.chmod 0777, path File.unlink path end def install(from, dest, mode, prefix = nil) $stderr.puts "install #{from} #{dest}" if verbose? return if no_harm? realdest = prefix ? prefix + File.expand_path(dest) : dest realdest = File.join(realdest, File.basename(from)) if File.dir?(realdest) str = File.binread(from) if diff?(str, realdest) verbose_off { rm_f realdest if File.exist?(realdest) } File.open(realdest, 'wb') {|f| f.write str } File.chmod mode, realdest File.open("#{objdir_root()}/InstalledFiles", 'a') {|f| if prefix f.puts realdest.sub(prefix, '') else f.puts realdest end } end end def diff?(new_content, path) return true unless File.exist?(path) new_content != File.binread(path) end def command(*args) $stderr.puts args.join(' ') if verbose? system(*args) or raise RuntimeError, "system(#{args.map{|a| a.inspect }.join(' ')}) failed" end def ruby(*args) command config('rubyprog'), *args end def make(task = nil) command(*[config('makeprog'), task].compact) end def extdir?(dir) File.exist?("#{dir}/MANIFEST") or File.exist?("#{dir}/extconf.rb") end def files_of(dir) Dir.open(dir) {|d| return d.select {|ent| File.file?("#{dir}/#{ent}") } } end DIR_REJECT = %w( . .. CVS SCCS RCS CVS.adm .svn ) def directories_of(dir) Dir.open(dir) {|d| return d.select {|ent| File.dir?("#{dir}/#{ent}") } - DIR_REJECT } end end # This module requires: #srcdir_root, #objdir_root, #relpath module HookScriptAPI def get_config(key) @config[key] end alias config get_config # obsolete: use metaconfig to change configuration def set_config(key, val) @config[key] = val end # # srcdir/objdir (works only in the package directory) # def curr_srcdir "#{srcdir_root()}/#{relpath()}" end def curr_objdir "#{objdir_root()}/#{relpath()}" end def srcfile(path) "#{curr_srcdir()}/#{path}" end def srcexist?(path) File.exist?(srcfile(path)) end def srcdirectory?(path) File.dir?(srcfile(path)) end def srcfile?(path) File.file?(srcfile(path)) end def srcentries(path = '.') Dir.open("#{curr_srcdir()}/#{path}") {|d| return d.to_a - %w(. ..) } end def srcfiles(path = '.') srcentries(path).select {|fname| File.file?(File.join(curr_srcdir(), path, fname)) } end def srcdirectories(path = '.') srcentries(path).select {|fname| File.dir?(File.join(curr_srcdir(), path, fname)) } end end class ToplevelInstaller Version = '3.4.1' Copyright = 'Copyright (c) 2000-2005 Minero Aoki' TASKS = [ [ 'all', 'do config, setup, then install' ], [ 'config', 'saves your configurations' ], [ 'show', 'shows current configuration' ], [ 'setup', 'compiles ruby extentions and others' ], [ 'install', 'installs files' ], [ 'test', 'run all tests in test/' ], [ 'clean', "does `make clean' for each extention" ], [ 'distclean',"does `make distclean' for each extention" ] ] def ToplevelInstaller.invoke config = ConfigTable.new(load_rbconfig()) config.load_standard_entries config.load_multipackage_entries if multipackage? config.fixup klass = (multipackage?() ? ToplevelInstallerMulti : ToplevelInstaller) klass.new(File.dirname($0), config).invoke end def ToplevelInstaller.multipackage? File.dir?(File.dirname($0) + '/packages') end def ToplevelInstaller.load_rbconfig if arg = ARGV.detect {|arg| /\A--rbconfig=/ =~ arg } ARGV.delete(arg) load File.expand_path(arg.split(/=/, 2)[1]) $".push 'rbconfig.rb' else require 'rbconfig' end ::Config::CONFIG end def initialize(ardir_root, config) @ardir = File.expand_path(ardir_root) @config = config # cache @valid_task_re = nil end def config(key) @config[key] end def inspect "#<#{self.class} #{__id__()}>" end def invoke run_metaconfigs case task = parsearg_global() when nil, 'all' parsearg_config init_installers exec_config exec_setup exec_install else case task when 'config', 'test' ; when 'clean', 'distclean' @config.load_savefile if File.exist?(@config.savefile) else @config.load_savefile end __send__ "parsearg_#{task}" init_installers __send__ "exec_#{task}" end end def run_metaconfigs @config.load_script "#{@ardir}/metaconfig" end def init_installers @installer = Installer.new(@config, @ardir, File.expand_path('.')) end # # Hook Script API bases # def srcdir_root @ardir end def objdir_root '.' end def relpath '.' end # # Option Parsing # def parsearg_global while arg = ARGV.shift case arg when /\A\w+\z/ setup_rb_error "invalid task: #{arg}" unless valid_task?(arg) return arg when '-q', '--quiet' @config.verbose = false when '--verbose' @config.verbose = true when '--help' print_usage $stdout exit 0 when '--version' puts "#{File.basename($0)} version #{Version}" exit 0 when '--copyright' puts Copyright exit 0 else setup_rb_error "unknown global option '#{arg}'" end end nil end def valid_task?(t) valid_task_re() =~ t end def valid_task_re @valid_task_re ||= /\A(?:#{TASKS.map {|task,desc| task }.join('|')})\z/ end def parsearg_no_options unless ARGV.empty? task = caller(0).first.slice(%r<`parsearg_(\w+)'>, 1) setup_rb_error "#{task}: unknown options: #{ARGV.join(' ')}" end end alias parsearg_show parsearg_no_options alias parsearg_setup parsearg_no_options alias parsearg_test parsearg_no_options alias parsearg_clean parsearg_no_options alias parsearg_distclean parsearg_no_options def parsearg_config evalopt = [] set = [] @config.config_opt = [] while i = ARGV.shift if /\A--?\z/ =~ i @config.config_opt = ARGV.dup break end name, value = *@config.parse_opt(i) if @config.value_config?(name) @config[name] = value else evalopt.push [name, value] end set.push name end evalopt.each do |name, value| @config.lookup(name).evaluate value, @config end # Check if configuration is valid set.each do |n| @config[n] if @config.value_config?(n) end end def parsearg_install @config.no_harm = false @config.install_prefix = '' while a = ARGV.shift case a when '--no-harm' @config.no_harm = true when /\A--prefix=/ path = a.split(/=/, 2)[1] path = File.expand_path(path) unless path[0,1] == '/' @config.install_prefix = path else setup_rb_error "install: unknown option #{a}" end end end def print_usage(out) out.puts 'Typical Installation Procedure:' out.puts " $ ruby #{File.basename $0} config" out.puts " $ ruby #{File.basename $0} setup" out.puts " # ruby #{File.basename $0} install (may require root privilege)" out.puts out.puts 'Detailed Usage:' out.puts " ruby #{File.basename $0} <global option>" out.puts " ruby #{File.basename $0} [<global options>] <task> [<task options>]" fmt = " %-24s %s\n" out.puts out.puts 'Global options:' out.printf fmt, '-q,--quiet', 'suppress message outputs' out.printf fmt, ' --verbose', 'output messages verbosely' out.printf fmt, ' --help', 'print this message' out.printf fmt, ' --version', 'print version and quit' out.printf fmt, ' --copyright', 'print copyright and quit' out.puts out.puts 'Tasks:' TASKS.each do |name, desc| out.printf fmt, name, desc end fmt = " %-24s %s [%s]\n" out.puts out.puts 'Options for CONFIG or ALL:' @config.each do |item| out.printf fmt, item.help_opt, item.description, item.help_default end out.printf fmt, '--rbconfig=path', 'rbconfig.rb to load',"running ruby's" out.puts out.puts 'Options for INSTALL:' out.printf fmt, '--no-harm', 'only display what to do if given', 'off' out.printf fmt, '--prefix=path', 'install path prefix', '' out.puts end # # Task Handlers # def exec_config @installer.exec_config @config.save # must be final end def exec_setup @installer.exec_setup end def exec_install @installer.exec_install end def exec_test @installer.exec_test end def exec_show @config.each do |i| printf "%-20s %s\n", i.name, i.value if i.value? end end def exec_clean @installer.exec_clean end def exec_distclean @installer.exec_distclean end end # class ToplevelInstaller class ToplevelInstallerMulti < ToplevelInstaller include FileOperations def initialize(ardir_root, config) super @packages = directories_of("#{@ardir}/packages") raise 'no package exists' if @packages.empty? @root_installer = Installer.new(@config, @ardir, File.expand_path('.')) end def run_metaconfigs @config.load_script "#{@ardir}/metaconfig", self @packages.each do |name| @config.load_script "#{@ardir}/packages/#{name}/metaconfig" end end attr_reader :packages def packages=(list) raise 'package list is empty' if list.empty? list.each do |name| raise "directory packages/#{name} does not exist"\ unless File.dir?("#{@ardir}/packages/#{name}") end @packages = list end def init_installers @installers = {} @packages.each do |pack| @installers[pack] = Installer.new(@config, "#{@ardir}/packages/#{pack}", "packages/#{pack}") end with = extract_selection(config('with')) without = extract_selection(config('without')) @selected = @installers.keys.select {|name| (with.empty? or with.include?(name)) \ and not without.include?(name) } end def extract_selection(list) a = list.split(/,/) a.each do |name| setup_rb_error "no such package: #{name}" unless @installers.key?(name) end a end def print_usage(f) super f.puts 'Inluded packages:' f.puts ' ' + @packages.sort.join(' ') f.puts end # # Task Handlers # def exec_config run_hook 'pre-config' each_selected_installers {|inst| inst.exec_config } run_hook 'post-config' @config.save # must be final end def exec_setup run_hook 'pre-setup' each_selected_installers {|inst| inst.exec_setup } run_hook 'post-setup' end def exec_install run_hook 'pre-install' each_selected_installers {|inst| inst.exec_install } run_hook 'post-install' end def exec_test run_hook 'pre-test' each_selected_installers {|inst| inst.exec_test } run_hook 'post-test' end def exec_clean rm_f @config.savefile run_hook 'pre-clean' each_selected_installers {|inst| inst.exec_clean } run_hook 'post-clean' end def exec_distclean rm_f @config.savefile run_hook 'pre-distclean' each_selected_installers {|inst| inst.exec_distclean } run_hook 'post-distclean' end # # lib # def each_selected_installers Dir.mkdir 'packages' unless File.dir?('packages') @selected.each do |pack| $stderr.puts "Processing the package `#{pack}' ..." if verbose? Dir.mkdir "packages/#{pack}" unless File.dir?("packages/#{pack}") Dir.chdir "packages/#{pack}" yield @installers[pack] Dir.chdir '../..' end end def run_hook(id) @root_installer.run_hook id end # module FileOperations requires this def verbose? @config.verbose? end # module FileOperations requires this def no_harm? @config.no_harm? end end # class ToplevelInstallerMulti class Installer FILETYPES = %w( bin lib ext data conf man ) include FileOperations include HookScriptAPI def initialize(config, srcroot, objroot) @config = config @srcdir = File.expand_path(srcroot) @objdir = File.expand_path(objroot) @currdir = '.' end def inspect "#<#{self.class} #{File.basename(@srcdir)}>" end def noop(rel) end # # Hook Script API base methods # def srcdir_root @srcdir end def objdir_root @objdir end def relpath @currdir end # # Config Access # # module FileOperations requires this def verbose? @config.verbose? end # module FileOperations requires this def no_harm? @config.no_harm? end def verbose_off begin save, @config.verbose = @config.verbose?, false yield ensure @config.verbose = save end end # # TASK config # def exec_config exec_task_traverse 'config' end alias config_dir_bin noop alias config_dir_lib noop def config_dir_ext(rel) extconf if extdir?(curr_srcdir()) end alias config_dir_data noop alias config_dir_conf noop alias config_dir_man noop def extconf ruby "#{curr_srcdir()}/extconf.rb", *@config.config_opt end # # TASK setup # def exec_setup exec_task_traverse 'setup' end def setup_dir_bin(rel) files_of(curr_srcdir()).each do |fname| update_shebang_line "#{curr_srcdir()}/#{fname}" end end alias setup_dir_lib noop def setup_dir_ext(rel) make if extdir?(curr_srcdir()) end alias setup_dir_data noop alias setup_dir_conf noop alias setup_dir_man noop def update_shebang_line(path) return if no_harm? return if config('shebang') == 'never' old = Shebang.load(path) if old $stderr.puts "warning: #{path}: Shebang line includes too many args. It is not portable and your program may not work." if old.args.size > 1 new = new_shebang(old) return if new.to_s == old.to_s else return unless config('shebang') == 'all' new = Shebang.new(config('rubypath')) end $stderr.puts "updating shebang: #{File.basename(path)}" if verbose? open_atomic_writer(path) {|output| File.open(path, 'rb') {|f| f.gets if old # discard output.puts new.to_s output.print f.read } } end def new_shebang(old) if /\Aruby/ =~ File.basename(old.cmd) Shebang.new(config('rubypath'), old.args) elsif File.basename(old.cmd) == 'env' and old.args.first == 'ruby' Shebang.new(config('rubypath'), old.args[1..-1]) else return old unless config('shebang') == 'all' Shebang.new(config('rubypath')) end end def open_atomic_writer(path, &block) tmpfile = File.basename(path) + '.tmp' begin File.open(tmpfile, 'wb', &block) File.rename tmpfile, File.basename(path) ensure File.unlink tmpfile if File.exist?(tmpfile) end end class Shebang def Shebang.load(path) line = nil File.open(path) {|f| line = f.gets } return nil unless /\A#!/ =~ line parse(line) end def Shebang.parse(line) cmd, *args = *line.strip.sub(/\A\#!/, '').split(' ') new(cmd, args) end def initialize(cmd, args = []) @cmd = cmd @args = args end attr_reader :cmd attr_reader :args def to_s "#! #{@cmd}" + (@args.empty? ? '' : " #{@args.join(' ')}") end end # # TASK install # def exec_install rm_f 'InstalledFiles' exec_task_traverse 'install' end def install_dir_bin(rel) install_files targetfiles(), "#{config('bindir')}/#{rel}", 0755 end def install_dir_lib(rel) install_files libfiles(), "#{config('rbdir')}/#{rel}", 0644 end def install_dir_ext(rel) return unless extdir?(curr_srcdir()) install_files rubyextentions('.'), "#{config('sodir')}/#{File.dirname(rel)}", 0555 end def install_dir_data(rel) install_files targetfiles(), "#{config('datadir')}/#{rel}", 0644 end def install_dir_conf(rel) # FIXME: should not remove current config files # (rename previous file to .old/.org) install_files targetfiles(), "#{config('sysconfdir')}/#{rel}", 0644 end def install_dir_man(rel) install_files targetfiles(), "#{config('mandir')}/#{rel}", 0644 end def install_files(list, dest, mode) mkdir_p dest, @config.install_prefix list.each do |fname| install fname, dest, mode, @config.install_prefix end end def libfiles glob_reject(%w(*.y *.output), targetfiles()) end def rubyextentions(dir) ents = glob_select("*.#{@config.dllext}", targetfiles()) if ents.empty? setup_rb_error "no ruby extention exists: 'ruby #{$0} setup' first" end ents end def targetfiles mapdir(existfiles() - hookfiles()) end def mapdir(ents) ents.map {|ent| if File.exist?(ent) then ent # objdir else "#{curr_srcdir()}/#{ent}" # srcdir end } end # picked up many entries from cvs-1.11.1/src/ignore.c JUNK_FILES = %w( core RCSLOG tags TAGS .make.state .nse_depinfo #* .#* cvslog.* ,* .del-* *.olb *~ *.old *.bak *.BAK *.orig *.rej _$* *$ *.org *.in .* ) def existfiles glob_reject(JUNK_FILES, (files_of(curr_srcdir()) | files_of('.'))) end def hookfiles %w( pre-%s post-%s pre-%s.rb post-%s.rb ).map {|fmt|
ruby
MIT
2e01918ad8d601685386aa9ac5d547ffb9b70b27
2026-01-04T17:56:08.640464Z
true
jm/matchy
https://github.com/jm/matchy/blob/2e01918ad8d601685386aa9ac5d547ffb9b70b27/countloc.rb
countloc.rb
# This is here because OptionsParser is SO slow. def extract_path(argv) if argv[1].nil? if argv[0] =~ /-a/ return "/**/*.rb" elsif argv[0] if argv[0] =~ /\.rb$/ return argv[0] end return argv[0] + "/**/*.rb" else return "/**/*.rb" end elsif argv[1] =~ /\.rb$/ return argv[1] else return argv[1] + "/**/*.rb" end end def all? ARGV.join =~ /-a/ end def comment?(line) line =~ /^\s*#/ end def blank?(line) line =~ /^\s*$/ end def puke(header, locs, comments, blanks) puts header + ":" puts "#{locs} loc" puts "#{comments} lines of comments" puts "#{blanks} blank lines" end dir = File.dirname(__FILE__) full_path = File.join(dir,extract_path(ARGV)) gloc = gcmts = gblanks = 0 Dir[File.expand_path("#{full_path}")].uniq.each do |file| if file =~ /.*\.rb$/ loc = cmts = blanks = 0 File.open(file, "r") do |f| while f.gets if comment?($_) cmts += 1 elsif blank?($_) blanks += 1 else loc += 1 end end end gcmts += cmts gloc += loc gblanks += blanks puke(file, loc, cmts, blanks) if all? end end puke("Total", gloc, gcmts, gblanks)
ruby
MIT
2e01918ad8d601685386aa9ac5d547ffb9b70b27
2026-01-04T17:56:08.640464Z
false
jm/matchy
https://github.com/jm/matchy/blob/2e01918ad8d601685386aa9ac5d547ffb9b70b27/test/test_enumerable_expectations.rb
test/test_enumerable_expectations.rb
require File.dirname(__FILE__) + '/test_helper.rb' class TestEnumerableExpectations < Test::Unit::TestCase def test_include [1,2,3,4].should include(4) end def test_include_fail lambda { [1,2,3,4].should include(6) }.should raise_error(Test::Unit::AssertionFailedError) end def test_exclude [1,2,3,4].should exclude(9) end def test_exclude_fail lambda { [1,2,3,4].should exclude(4) }.should raise_error(Test::Unit::AssertionFailedError) end def test_multi_include [1,2,3,4].should include(1,2) end def test_multi_include_fail lambda { [1,2,3,4].should include(6,7,8) }.should raise_error(Test::Unit::AssertionFailedError) end def test_multi_exclude [1,2,3,4].should exclude(13,14) end def test_multi_exclude_fail lambda { [1,2,3,4].should exclude(2,3,4) }.should raise_error(Test::Unit::AssertionFailedError) end def test_negative_include [1,2,3,4].should_not include(9) end def test_negative_include_fail lambda { [1,2,3,4].should_not include(4) }.should raise_error(Test::Unit::AssertionFailedError) end def test_negative_exclude [1,2,3,4].should_not exclude(3) end def test_negative_exclude_fail lambda { [1,2,3,4].should_not exclude(6,7) }.should raise_error(Test::Unit::AssertionFailedError) end def test_include_fail_message obj = include(1) obj.matches?([4,5,6]) obj.failure_message.should be("Expected [4, 5, 6] to include [1].") end def test_include_negative_fail_message obj = include(1) obj.matches?([4,5,6]) obj.negative_failure_message.should be("Expected [4, 5, 6] to not include [1].") end def test_exclude_fail_message obj = exclude(4) obj.matches?([4,5,6]) obj.failure_message.should be("Expected [4, 5, 6] to exclude [4].") end def test_exclude_negative_fail_message obj = exclude(4) obj.matches?([4,5,6]) obj.negative_failure_message.should be("Expected [4, 5, 6] to not exclude [4].") end end
ruby
MIT
2e01918ad8d601685386aa9ac5d547ffb9b70b27
2026-01-04T17:56:08.640464Z
false
jm/matchy
https://github.com/jm/matchy/blob/2e01918ad8d601685386aa9ac5d547ffb9b70b27/test/ruby1.9.compatibility_tests.rb
test/ruby1.9.compatibility_tests.rb
# Eval this file with ruby 1.9 require 'test/unit' require File.dirname(__FILE__) + '/../lib/matchy.rb' class TestAThing < Test::Unit::TestCase def setup @obj = Object.new end # == def test_operator_eql_eql 1.should == 1 end def test_operator_eql_eql_fails lambda {1.should == 2}.should raise_error end def test_operator_eql_eql_negative 1.should_not == 2 end def test_operator_eql_eql_negative_fails lambda {1.should_not == 1}.should raise_error end # === def test_operator_eql_eql_eql 1.should === 1 end def test_operator_eql_eql_eql_fails lambda {1.should === 2}.should raise_error end def test_operator_eql_eql_eql_negative 1.should_not === 2 end def test_operator_eql_eql_eql_negative_fails lambda {1.should_not === 1}.should raise_error end # =~ def test_operator_eql_match "string".should =~ /in/ end def test_operator_eql_match_fails lambda {"string".should =~ /an/}.should raise_error end def test_operator_eql_match_negative "string".should_not =~ /an/ end def test_operator_eql_match_negative_fails lambda {"string".should_not =~ /in/}.should raise_error end # <= def test_operator_lt_eql 1.should <= 2 end def test_operator_lt_eql_fails lambda {1.should <= 0}.should raise_error end def test_operator_lt_eql_negative 1.should_not <= 0 end def test_operator_lt_eql_negative_fails lambda {1.should_not <= 2}.should raise_error end # >= def test_operator_gt_eql 1.should >= 0 end def test_operator_gt_eql_fails lambda {1.should >= 2}.should raise_error end def test_operator_gt_eql_negative 1.should_not >= 2 end def test_operator_gt_eql_negative_fails lambda {1.should_not >= 0}.should raise_error end # < def test_operator_lt 1.should < 2 end def test_operator_lt_fails lambda {1.should < 0}.should raise_error end def test_operator_lt_negative 1.should_not < 0 end def test_operator_lt_negative_fails lambda {1.should_not < 2}.should raise_error end # > def test_operator_gt 1.should > 0 end def test_operator_gt_fails lambda {1.should > 2}.should raise_error end def test_operator_gt_negative 1.should_not > 2 end def test_operator_gt_negative_fails lambda {1.should_not > 0}.should raise_error end # be() def test_be 1.should be(1) end def test_be_fails lambda {1.should be(2)}.should raise_error end def test_be_negative 1.should_not be(2) end def test_be_negative_fails lambda {1.should_not be(1)}.should raise_error end # be_something def test_positive_be_something_method_missing_pass def @obj.something? true end @obj.should be_something end def test_positive_be_something_method_missing_fails def @obj.something? false end lambda {@obj.should be_something}.should raise_error(Test::Unit::AssertionFailedError) end def test_negative_be_something_method_missing_pass def @obj.something? false end @obj.should_not be_something end def test_negative_be_something_method_missing_fails def @obj.something? true end lambda {@obj.should_not be_something}.should raise_error(Test::Unit::AssertionFailedError) end def test_be_something_method_missing_fail_message obj = "foo" def obj.something? true end matcher_obj = be_something obj.should matcher_obj matcher_obj.failure_message.should be("Expected \"foo\" to return true for something?, with 'no args'.") end def test_be_something_method_missing_negative_fail_message obj = "foo" def obj.something? false end matcher_obj = be_something obj.should_not matcher_obj matcher_obj.negative_failure_message.should =~ /Expected \"foo\" to not return true for something?/ end # be_something(arg) def test_positive_be_something_with_arg_method_missing_pass def @obj.something?(arg) true end @obj.should be_something(1) end def test_positive_be_something_with_arg_method_missing_fails def @obj.something?(arg) false end lambda {@obj.should be_something(1)}.should raise_error(Test::Unit::AssertionFailedError) end def test_negative_be_something_method_missing_pass def @obj.something?(arg) false end @obj.should_not be_something(1) end def test_negative_be_something_method_missing_fails def @obj.something?(arg) true end lambda {@obj.should_not be_something(1)}.should raise_error(Test::Unit::AssertionFailedError) end def test_be_something_method_missing_fail_message obj = "foo" def obj.something?(arg) true end matcher_obj = be_something(1) obj.should matcher_obj matcher_obj.failure_message.should be("Expected \"foo\" to return true for something?, with '1'.") end def test_be_something_method_missing_negative_fail_message obj = "foo" def obj.something?(arg) false end matcher_obj = be_something(1) obj.should_not matcher_obj matcher_obj.negative_failure_message.should be("Expected \"foo\" to not return true for something?, with '1'.") end # change def test_change var = 1 lambda {var += 1}.should change {var} end def test_change_fails var = 1 lambda do lambda { }.should change {var} end.should raise_error end def test_change_by var = 1 lambda {var += 1}.should change {var}.by(1) end def test_change_by_fails var = 1 lambda do lambda {var += 2}.should change {var}.by(1) end.should raise_error end def test_change_by_at_least var = 1 lambda {var += 1}.should change {var}.by_at_least(1) end def test_change_by_at_least_fails var = 1 lambda do lambda {var += 0.9}.should change {var}.by_at_least(1) end.should raise_error end def test_change_by_at_most var = 1 lambda {var += 1}.should change {var}.by_at_most(1) end def test_change_by_at_most_fails var = 1 lambda do lambda {var += 1.1}.should change {var}.by_at_most(1) end.should raise_error end def test_change_from_to var = 1 lambda {var += 1}.should change {var}.from(1).to(2) end def test_change_from_to_fails var = 1 lambda do lambda {var += 1.1}.should change {var}.from(1).to(2) end.should raise_error end # def_matcher def test_def_matcher_defines_method def_matcher :method_ do |given, matcher, args| end self.should respond_to(:method_) end def test_def_matcher_object_responds_to_matches def_matcher :method_ do |given, matcher, args| end method_.should respond_to(:matches?) end def test_def_matcher_fail_positive def_matcher :matcher do |given, matcher, args| false end lambda {1.should matcher}.should raise_error end def test_def_matcher_pass_positive def_matcher :matcher do |given, matcher, args| true end 1.should matcher end def test_def_matcher_fail_negative def_matcher :matcher do |given, matcher, args| true end lambda {1.should_not matcher}.should raise_error end def test_def_matcher_pass_negative def_matcher :matcher do |given, matcher, args| false end 1.should_not matcher end def test_def_matcher_takes_arguments def_matcher :matcher do |given, matcher, args| $args = args true end @obj.should matcher(1,2,3) $args.should eql([1,2,3]) end def test_def_matcher_received_method def_matcher :matcher do |given, matcher, args| $msgs = matcher.msgs true end @obj.should matcher.method1 $msgs[0].name.should eql(:method1) end def test_def_matcher_received_method_takes_args def_matcher :matcher do |given, matcher, args| $msgs = matcher.msgs true end @obj.should matcher.method1(1,2,3) $msgs[0].args.should eql([1,2,3]) end def test_def_matcher_received_method_takes_block def_matcher :matcher do |given, matcher, args| $msgs = matcher.msgs true end @obj.should matcher.method1 { "Hello, World!"} $msgs[0].block.call.should eql("Hello, World!") end def test_def_matcher_received_method_chained def_matcher :matcher do |given, matcher, args| $msgs = matcher.msgs true end @obj.should matcher.method1(1,2,3) { "Hello, World!"}. method2(4,5,6) { "Hello chained messages" } $msgs[0].name.should eql(:method1) $msgs[1].name.should eql(:method2) $msgs[0].args.should eql([1,2,3]) $msgs[1].args.should eql([4,5,6]) $msgs[0].block.call.should eql("Hello, World!") $msgs[1].block.call.should eql("Hello chained messages") end # include/exclude def test_include [1,2,3,4].should include(4) end def test_include_fail lambda { [1,2,3,4].should include(6) }.should raise_error(Test::Unit::AssertionFailedError) end def test_exclude [1,2,3,4].should exclude(9) end def test_exclude_fail lambda { [1,2,3,4].should exclude(4) }.should raise_error(Test::Unit::AssertionFailedError) end def test_multi_include [1,2,3,4].should include(1,2) end def test_multi_include_fail lambda { [1,2,3,4].should include(6,7,8) }.should raise_error(Test::Unit::AssertionFailedError) end def test_multi_exclude [1,2,3,4].should exclude(13,14) end def test_multi_exclude_fail lambda { [1,2,3,4].should exclude(2,3,4) }.should raise_error(Test::Unit::AssertionFailedError) end def test_negative_include [1,2,3,4].should_not include(9) end def test_negative_include_fail lambda { [1,2,3,4].should_not include(4) }.should raise_error(Test::Unit::AssertionFailedError) end def test_negative_exclude [1,2,3,4].should_not exclude(3) end def test_negative_exclude_fail lambda { [1,2,3,4].should_not exclude(6,7) }.should raise_error(Test::Unit::AssertionFailedError) end def test_include_fail_message obj = include(1) obj.matches?([4,5,6]) obj.failure_message.should be("Expected [4, 5, 6] to include [1].") end def test_include_negative_fail_message obj = include(1) obj.matches?([4,5,6]) obj.negative_failure_message.should be("Expected [4, 5, 6] to not include [1].") end def test_exclude_fail_message obj = exclude(4) obj.matches?([4,5,6]) obj.failure_message.should be("Expected [4, 5, 6] to exclude [4].") end def test_exclude_negative_fail_message obj = exclude(4) obj.matches?([4,5,6]) obj.negative_failure_message.should be("Expected [4, 5, 6] to not exclude [4].") end # raise_error def test_raises_error lambda { raise "FAIL" }.should raise_error end def test_raises_error_fail lambda { lambda { "WIN" }.should raise_error }.should raise_error(Test::Unit::AssertionFailedError) end def test_raise_error_negative_raises_error lambda { "WIN" }.should_not raise_error end def test_raise_error_negative_raises_error_fail lambda { lambda { raise "FAIL" }.should_not raise_error }.should raise_error(Test::Unit::AssertionFailedError) end def test_raise_error_raises_specific_error lambda { raise TypeError }.should raise_error(TypeError) end def test_raise_error_raises_specific_error_fail_with_no_error lambda { lambda { "WIN" }.should raise_error(TypeError) }.should raise_error(Test::Unit::AssertionFailedError) end def test_raise_error_raises_specific_error_fail_with_different_error lambda { lambda { raise StandardError }.should raise_error(TypeError) }.should raise_error(Test::Unit::AssertionFailedError) end def test_raise_error_error_fail_message obj = raise_error(TypeError) obj.matches?(lambda { raise NameError }) obj.failure_message.should =~ /Expected #<(.*)> to raise TypeError, but NameError was raised instead./ end def test_raise_error_error_fail_message_when_no_error obj = raise_error(TypeError) obj.matches?(lambda { "moop" }) obj.failure_message.should =~ /Expected #<(.*)> to raise TypeError, but none was raised./ end def test_raise_error_error_negative_fail_message obj = raise_error(TypeError) obj.matches?(lambda { raise TypeError }) obj.negative_failure_message.should =~ /Expected #<(.*)> to not raise TypeError./ end def test_raise_error_string_argument_message lambda {raise "message"}.should raise_error("message") end def test_string_argument_message_fails_no_error lambda do lambda { 1 }.should raise_error("message") end.should raise_error end def test_raise_error_string_argument_message_fails_wrong_message lambda do lambda { raise "other message" }.should raise_error("message") end.should raise_error end def test_raise_error_regexp_argument_message lambda {raise "message"}.should raise_error(/essa/) end def test_raise_error_regexp_argument_message_fails_no_error lambda do lambda { 1 }.should raise_error(/essa/) end.should raise_error end def test_raise_error_regexp_argument_message_fails_wrong_message lambda do lambda { raise "other message" }.should raise_error(/abc/) end.should raise_error(/matching/) end # throw def test_throws_symbol lambda { throw :win }.should throw_symbol(:win) end def test_throws_symbol_fails_with_different_symbol lambda { lambda { throw :fail }.should throw_symbol(:win) }.should raise_error(Test::Unit::AssertionFailedError) end def test_negative_throws_symbol lambda { "not this time!" }.should_not throw_symbol(:win) end def test_negative_throws_symbol_fails_with_different_symbol lambda{ lambda { throw :fail }.should_not throw_symbol(:fail) }.should raise_error(Test::Unit::AssertionFailedError) end def test_throw_fail_message obj = throw_symbol(:fail) obj.matches?(lambda { throw :lame }) obj.failure_message.should =~ /Expected #<(.*)> to throw :fail, but :lame was thrown instead./ end def test_throw_fail_message_when_no_symbol obj = throw_symbol(:fail) obj.matches?(lambda { "moop" }) obj.failure_message.should =~ /Expected #<(.*)> to throw :fail, but no symbol was thrown./ end def test_throw_negative_fail_message obj = throw_symbol(:fail) obj.matches?(lambda { throw :fail }) obj.negative_failure_message.should =~ /Expected #<(.*)> to not throw :fail./ end end
ruby
MIT
2e01918ad8d601685386aa9ac5d547ffb9b70b27
2026-01-04T17:56:08.640464Z
false
jm/matchy
https://github.com/jm/matchy/blob/2e01918ad8d601685386aa9ac5d547ffb9b70b27/test/test_error_expectations.rb
test/test_error_expectations.rb
require File.dirname(__FILE__) + '/test_helper.rb' class TestErrorExpectations < Test::Unit::TestCase def test_raises_error lambda { raise "FAIL" }.should raise_error end def test_raises_error_fail lambda { lambda { "WIN" }.should raise_error }.should raise_error(Test::Unit::AssertionFailedError) end def test_negative_raises_error lambda { "WIN" }.should_not raise_error end def test_negative_raises_error_fail lambda { lambda { raise "FAIL" }.should_not raise_error }.should raise_error(Test::Unit::AssertionFailedError) end def test_raises_specific_error lambda { raise TypeError }.should raise_error(TypeError) end def test_raises_specific_error_fail_with_no_error lambda { lambda { "WIN" }.should raise_error(TypeError) }.should raise_error(Test::Unit::AssertionFailedError) end def test_raises_specific_error_fail_with_different_error lambda { lambda { raise StandardError }.should raise_error(TypeError) }.should raise_error(Test::Unit::AssertionFailedError) end def test_throws_symbol lambda { throw :win }.should throw_symbol(:win) end def test_throws_symbol_fails_with_different_symbol lambda { lambda { throw :fail }.should throw_symbol(:win) }.should raise_error(Test::Unit::AssertionFailedError) end def test_negative_throws_symbol lambda { "not this time!" }.should_not throw_symbol(:win) end def test_negative_throws_symbol_fails_with_different_symbol lambda{ lambda { throw :fail }.should_not throw_symbol(:fail) }.should raise_error(Test::Unit::AssertionFailedError) end def test_error_fail_message obj = raise_error(TypeError) obj.matches?(lambda { raise NameError }) obj.failure_message.should =~ /Expected #<(.*)> to raise TypeError, but NameError was raised instead./ end def test_error_fail_message_when_no_error obj = raise_error(TypeError) obj.matches?(lambda { "moop" }) obj.failure_message.should =~ /Expected #<(.*)> to raise TypeError, but none was raised./ end def test_error_negative_fail_message obj = raise_error(TypeError) obj.matches?(lambda { raise TypeError }) obj.negative_failure_message.should =~ /Expected #<(.*)> to not raise TypeError./ end def test_throw_fail_message obj = throw_symbol(:fail) obj.matches?(lambda { throw :lame }) obj.failure_message.should =~ /Expected #<(.*)> to throw :fail, but :lame was thrown instead./ end def test_throw_fail_message_when_no_symbol obj = throw_symbol(:fail) obj.matches?(lambda { "moop" }) obj.failure_message.should =~ /Expected #<(.*)> to throw :fail, but no symbol was thrown./ end def test_throw_negative_fail_message obj = throw_symbol(:fail) obj.matches?(lambda { throw :fail }) obj.negative_failure_message.should =~ /Expected #<(.*)> to not throw :fail./ end def test_string_argument_message lambda {raise "message"}.should raise_error("message") end def test_string_argument_message_fails_no_error lambda do lambda { 1 }.should raise_error("message") end.should raise_error end def test_string_argument_message_fails_wrong_message lambda do lambda { raise "other message" }.should raise_error("message") end.should raise_error end def test_regexp_argument_message lambda {raise "message"}.should raise_error(/essa/) end def test_regexp_argument_message_fails_no_error lambda do lambda { 1 }.should raise_error(/essa/) end.should raise_error end def test_regexp_argument_message_fails_wrong_message lambda do lambda { raise "other message" }.should raise_error(/abc/) end.should raise_error(/matching/) end end
ruby
MIT
2e01918ad8d601685386aa9ac5d547ffb9b70b27
2026-01-04T17:56:08.640464Z
false
jm/matchy
https://github.com/jm/matchy/blob/2e01918ad8d601685386aa9ac5d547ffb9b70b27/test/test_minitest_compatibility.rb
test/test_minitest_compatibility.rb
require 'rubygems' require 'minitest/unit' load File.dirname(__FILE__) + '/../lib/matchy.rb' MiniTest::Unit.autorun class TestAThing < MiniTest::Unit::TestCase def test_equal_equal 1.should == 1 end def test_equal_equal_fails #1.should == 2 lambda{ 1.should == 2 }.should raise_error end def test_equal_equal_negative 1.should_not == 2 end def test_equal_equal_negative_fails lambda{ 1.should_not == 1 }.should raise_error end end
ruby
MIT
2e01918ad8d601685386aa9ac5d547ffb9b70b27
2026-01-04T17:56:08.640464Z
false