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
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/app/models/passkit/pass.rb
app/models/passkit/pass.rb
module Passkit class Pass < ActiveRecord::Base validates_uniqueness_of :serial_number validates_presence_of :klass belongs_to :generator, polymorphic: true, optional: true has_many :registrations, foreign_key: :passkit_pass_id has_many :devices, through: :registrations delegate :apple_team_identifier, :app_launch_url, :associated_store_identifiers, :auxiliary_fields, :back_fields, :background_color, :barcode, :barcodes, :beacons, :boarding_pass, :description, :expiration_date, :file_name, :foreground_color, :format_version, :grouping_identifier, :header_fields, :label_color, :language, :locations, :logo_text, :max_distance, :nfc, :organization_name, :pass_path, :pass_type, :pass_type_identifier, :primary_fields, :relevant_date, :secondary_fields, :semantics, :sharing_prohibited, :suppress_strip_shine, :user_info, :voided, :web_service_url, to: :instance before_validation on: :create do self.authentication_token ||= SecureRandom.hex loop do self.serial_number = SecureRandom.uuid break unless self.class.exists?(serial_number: serial_number) end end def instance @instance ||= klass.constantize.new(generator) end def last_update instance.last_update || updated_at end end end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/app/models/passkit/log.rb
app/models/passkit/log.rb
module Passkit class Log < ActiveRecord::Base end end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/app/models/passkit/registration.rb
app/models/passkit/registration.rb
module Passkit class Registration < ActiveRecord::Base belongs_to :device, foreign_key: :passkit_device_id belongs_to :pass, foreign_key: :passkit_pass_id end end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/app/models/passkit/device.rb
app/models/passkit/device.rb
module Passkit class Device < ActiveRecord::Base validates_uniqueness_of :identifier has_many :registrations, foreign_key: :passkit_device_id has_many :passes, through: :registrations end end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/app/mailers/passkit/example_mailer.rb
app/mailers/passkit/example_mailer.rb
module Passkit class ExampleMailer < ActionMailer::Base def example_email @passkit_url_generator = Passkit::UrlGenerator.new(Passkit::ExampleStoreCard, nil) mail(to: "passkit@example.com", subject: "Here is an example of a passkit email") end end end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/test/test_passkit.rb
test/test_passkit.rb
# frozen_string_literal: true require "test_helper" class TestPasskit < Minitest::Test def test_that_it_has_a_version_number refute_nil ::Passkit::VERSION end end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/test/rails_helper.rb
test/rails_helper.rb
# frozen_string_literal: true # # $LOAD_PATH.unshift File.expand_path("../lib", __dir__) # require "passkit" # # require "minitest/autorun" # Configure Rails Environment ENV["RAILS_ENV"] = "test" require "dotenv/load" require_relative "../test/dummy/config/environment" ActiveRecord::Migrator.migrations_paths = [File.expand_path("../test/dummy/db/migrate", __dir__)] ActiveRecord::Migrator.migrations_paths << File.expand_path("../db/migrate", __dir__) require "rails/test_help" require "capybara/rails" Capybara.server = :webrick # Load fixtures from the engine if ActiveSupport::TestCase.respond_to?(:fixture_path=) 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
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/test/test_helper.rb
test/test_helper.rb
# frozen_string_literal: true $LOAD_PATH.unshift File.expand_path("../lib", __dir__) require "dotenv/load" require "passkit" require "minitest/autorun"
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/test/example_qr_code_pass.rb
test/example_qr_code_pass.rb
# frozen_string_literal: true module Passkit class ExampleQrCodePass < BasePass def header_fields [{ key: "value", label: "Value", value: 100, currencyCode: "CHF" }] end def back_fields [{ key: "code", label: "Code", value: "https://github.com/coorasse/passkit" }, { key: "website", label: "Website", value: "https://github.com/coorasse/passkit" }] end def auxiliary_fields [{ key: "name", label: "full Name", value: "Alessandro Rodi" }] end end end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/test/system/logs_dashboard_test.rb
test/system/logs_dashboard_test.rb
require "rails_helper" class LogsDashboardTest < ActionDispatch::SystemTestCase include Passkit::Engine.routes.url_helpers setup do @routes = Passkit::Engine.routes end def authorize visit "http://#{ENV["PASSKIT_DASHBOARD_USERNAME"]}:#{ENV["PASSKIT_DASHBOARD_PASSWORD"]}@#{Capybara.current_session.server.host}:#{Capybara.current_session.server.port}/passkit/dashboard/logs" end test "visiting the logs dashboard" do Passkit::Log.create!(content: "[today] shit happened") Passkit::Log.create!(content: "[tomorrow] shit will happen") authorize visit dashboard_logs_path assert_selector "h1", text: "Passkit Logs" assert_content "shit happened" assert_content "shit will happen" assert_no_content "today" assert_no_content "tomorrow" end end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/test/api/v1/test_registrations_controller.rb
test/api/v1/test_registrations_controller.rb
# frozen_string_literal: true require "rails_helper" class TestRegistrationsController < ActionDispatch::IntegrationTest include Passkit::Engine.routes.url_helpers setup do @routes = Passkit::Engine.routes end def test_create Passkit::Factory.create_pass(Passkit::ExampleStoreCard) Passkit::Factory.create_pass(Passkit::ExampleStoreCard) pass1 = Passkit::Pass.first pass2 = Passkit::Pass.last assert_equal 2, Passkit::Pass.count register_pass(pass1) assert_equal 1, pass1.devices.count register_pass(pass2) assert_equal 1, pass2.devices.count end def test_show end def test_destroy Passkit::Factory.create_pass(Passkit::ExampleStoreCard) pass = Passkit::Pass.first register_pass(pass) destroy_registration(pass.registrations.first) assert_equal 0, pass.devices.count assert_equal 0, Passkit::Registration.count assert_equal 1, Passkit::Pass.count assert_equal 1, Passkit::Device.count end private def register_pass(pass) post device_register_path(device_id: 1, pass_type_id: pass.pass_type_identifier, serial_number: pass.serial_number), params: {pushToken: "1234567890"}.to_json, headers: {"Authorization" => "ApplePass #{pass.authentication_token}"} end def destroy_registration(registration) delete device_unregister_path(device_id: registration.device.id, pass_type_id: registration.pass.pass_type_identifier, serial_number: registration.pass.serial_number), params: {}.to_json, headers: {"Authorization" => "ApplePass #{registration.pass.authentication_token}"} end end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/test/api/v1/test_passes_controller.rb
test/api/v1/test_passes_controller.rb
# frozen_string_literal: true require "rails_helper" class TestPassesController < ActionDispatch::IntegrationTest include Passkit::Engine.routes.url_helpers setup do @routes = Passkit::Engine.routes end def test_create payload = Passkit::PayloadGenerator.encrypted(Passkit::ExampleStoreCard) get passes_api_path(payload) assert_equal 1, Passkit::Pass.count assert_response :success zip_file = Zip::File.open_buffer(StringIO.new(response.body)) assert_equal 7, zip_file.size end def test_create_collection payload = Passkit::PayloadGenerator.encrypted(Passkit::UserTicket, User.find(1), :tickets) get passes_api_path(payload) assert_response :success assert_equal 2, Passkit::Pass.count unzipped_passes = Zip::File.open_buffer(StringIO.new(response.body)) assert_equal 2, unzipped_passes.size # the main zip file contains two passes unzipped_pass = Zip::File.open_buffer(unzipped_passes.first.zipfile) assert_includes unzipped_passes.first.name, '.pkpass' end def test_show _pkpass = Passkit::Factory.create_pass(Passkit::ExampleStoreCard) assert_equal 1, Passkit::Pass.count pass = Passkit::Pass.last get pass_path(pass_type_id: ENV["PASSKIT_PASS_TYPE_IDENTIFIER"], serial_number: pass.serial_number) assert_response :unauthorized get pass_path(pass_type_id: ENV["PASSKIT_PASS_TYPE_IDENTIFIER"], serial_number: pass.serial_number), headers: {"Authorization" => "ApplePass #{pass.authentication_token}"} assert_response :success get pass_path(pass_type_id: ENV["PASSKIT_PASS_TYPE_IDENTIFIER"], serial_number: pass.serial_number), headers: {"Authorization" => "ApplePass #{pass.authentication_token}", "If-Modified-Since" => Time.zone.now.httpdate} assert_equal "", response.body assert_equal pass.last_update.httpdate, response.headers["Last-Modified"] assert_response :not_modified end end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/test/api/v1/test_logs_controller.rb
test/api/v1/test_logs_controller.rb
# frozen_string_literal: true require "rails_helper" class TestLogsController < ActionDispatch::IntegrationTest include Passkit::Engine.routes.url_helpers setup do @routes = Passkit::Engine.routes end def test_show post log_url, params: {"logs" => ["message 1", "message 2", "message 3"]} assert_equal 3, Passkit::Log.count assert_response :success assert_equal "{}", response.body end end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/test/dummy/app/jobs/application_job.rb
test/dummy/app/jobs/application_job.rb
class ApplicationJob < ActiveJob::Base # Automatically retry jobs that encountered a deadlock # retry_on ActiveRecord::Deadlocked # Most jobs are safe to ignore if the underlying records are no longer available # discard_on ActiveJob::DeserializationError end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/test/dummy/app/helpers/application_helper.rb
test/dummy/app/helpers/application_helper.rb
module ApplicationHelper end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/test/dummy/app/controllers/application_controller.rb
test/dummy/app/controllers/application_controller.rb
class ApplicationController < ActionController::Base end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/test/dummy/app/models/ticket.rb
test/dummy/app/models/ticket.rb
class Ticket < ApplicationRecord belongs_to :user end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/test/dummy/app/models/application_record.rb
test/dummy/app/models/application_record.rb
class ApplicationRecord < ActiveRecord::Base primary_abstract_class end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/test/dummy/app/models/user.rb
test/dummy/app/models/user.rb
class User < ApplicationRecord has_many :tickets end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/test/dummy/app/lib/passkit/user_ticket.rb
test/dummy/app/lib/passkit/user_ticket.rb
module Passkit class UserTicket < BasePass def pass_type :eventTicket end def organization_name "Passkit" end def description "A basic description for a pass" end # A pass can have up to ten relevant locations # # @see https://developer.apple.com/library/archive/documentation/UserExperience/Conceptual/PassKit_PG/Creating.html def locations [ { latitude: 41.2273414693647, longitude: -95.92925748878405 }, # North Entrance { latitude: 41.22476226066285, longitude: -95.92879374051269 } # Main Entrance ] end def file_name @file_name ||= SecureRandom.uuid end # QRCode by default def barcodes [ { messageEncoding: "iso-8859-1", format: "PKBarcodeFormatQR", message: "https://github.com/coorasse/passkit", altText: "https://github.com/coorasse/passkit" } ] end # Barcode example # def barcode # { messageEncoding: 'iso-8859-1', # format: 'PKBarcodeFormatCode128', # message: '12345', # altText: '12345' } # end def logo_text "Loyalty Card" end def expiration_date # Expire the pass tomorrow (Time.current + 60*60*24).strftime('%Y-%m-%dT%H:%M:%S%:z') end def semantics { balance: { amount: "100", currencyCode: "USD" } } end def header_fields [{ key: "balance", label: "Balance", value: 100, currencyCode: "$" }] end def back_fields [{ key: "example1", label: "Code", value: "0123456789" }, { key: "example2", label: "Creator", value: "https://github.com/coorasse" }, { key: "example3", label: "Contact", value: "rodi@hey.com" }] end def auxiliary_fields [{ key: "name", label: "Name", value: @generator.name }, { key: "email", label: "Email", value: "#{@generator.name}@hey.com" }] end private def folder_name 'user_store_card' end end end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/test/dummy/app/lib/passkit/user_store_card.rb
test/dummy/app/lib/passkit/user_store_card.rb
module Passkit class UserStoreCard < BasePass def pass_type :storeCard end def organization_name "Passkit" end def description "A basic description for a pass" end # A pass can have up to ten relevant locations # # @see https://developer.apple.com/library/archive/documentation/UserExperience/Conceptual/PassKit_PG/Creating.html def locations [ { latitude: 41.2273414693647, longitude: -95.92925748878405 }, # North Entrance { latitude: 41.22476226066285, longitude: -95.92879374051269 } # Main Entrance ] end def file_name @file_name ||= SecureRandom.uuid end # QRCode by default def barcodes [ { messageEncoding: "iso-8859-1", format: "PKBarcodeFormatQR", message: "https://github.com/coorasse/passkit", altText: "https://github.com/coorasse/passkit" } ] end # Barcode example # def barcode # { messageEncoding: 'iso-8859-1', # format: 'PKBarcodeFormatCode128', # message: '12345', # altText: '12345' } # end def logo_text "Loyalty Card" end def expiration_date # Expire the pass tomorrow (Time.current + 60*60*24).strftime('%Y-%m-%dT%H:%M:%S%:z') end def semantics { balance: { amount: "100", currencyCode: "USD" } } end def header_fields [{ key: "balance", label: "Balance", value: 100, currencyCode: "$" }] end def back_fields [{ key: "example1", label: "Code", value: "0123456789" }, { key: "example2", label: "Creator", value: "https://github.com/coorasse" }, { key: "example3", label: "Contact", value: "rodi@hey.com" }] end def auxiliary_fields [{ key: "name", label: "Name", value: @generator.name }, { key: "email", label: "Email", value: "rodi@hey.com" }, { key: "phone", label: "Phone", value: "+41 1234567890" }] end private def folder_name self.class.name.demodulize.underscore end end end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/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
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/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
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/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
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/test/dummy/db/seeds.rb
test/dummy/db/seeds.rb
@user1 = User.create!(name: "First User") @user2 = User.create!(name: "Second User") Ticket.create!(name: "Ticket1", user: @user1) Ticket.create!(name: "Ticket2", user: @user1) Ticket.create!(name: "Ticket3", user: @user2)
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/test/dummy/db/schema.rb
test/dummy/db/schema.rb
# This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # This file is the source Rails uses to define your schema when running `bin/rails # db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to # be faster and is potentially less error prone than running all of your # migrations from scratch. Old migrations may fail to apply correctly if those # migrations use external dependencies or application code. # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema[7.1].define(version: 2024_04_11_013721) do create_table "passkit_devices", force: :cascade do |t| t.string "identifier" t.string "push_token" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "passkit_logs", force: :cascade do |t| t.text "content" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "passkit_passes", force: :cascade do |t| t.string "generator_type" t.string "klass" t.bigint "generator_id" t.string "serial_number" t.string "authentication_token" t.json "data" t.integer "version" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index ["generator_type", "generator_id"], name: "index_passkit_passes_on_generator" end create_table "passkit_registrations", force: :cascade do |t| t.integer "passkit_pass_id" t.integer "passkit_device_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index ["passkit_device_id"], name: "index_passkit_registrations_on_passkit_device_id" t.index ["passkit_pass_id"], name: "index_passkit_registrations_on_passkit_pass_id" end create_table "tickets", force: :cascade do |t| t.string "name" t.integer "user_id", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index ["user_id"], name: "index_tickets_on_user_id" end create_table "users", force: :cascade do |t| t.string "name" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_foreign_key "tickets", "users" end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/test/dummy/db/migrate/20220923124956_create_passkit_tables.rb
test/dummy/db/migrate/20220923124956_create_passkit_tables.rb
class CreatePasskitTables < ActiveRecord::Migration[7.0] def change create_table :passkit_passes do |t| t.string :generator_type t.string :klass t.bigint :generator_id t.string :serial_number t.string :authentication_token t.json :data t.integer :version t.timestamps null: false t.index [:generator_type, :generator_id], name: "index_passkit_passes_on_generator" end create_table :passkit_devices do |t| t.string :identifier t.string :push_token t.timestamps null: false end create_table :passkit_registrations do |t| t.belongs_to :passkit_pass, index: true t.belongs_to :passkit_device, index: true t.timestamps null: false end create_table :passkit_logs do |t| t.text :content t.timestamps null: false end end end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/test/dummy/db/migrate/20240411013721_create_tickets.rb
test/dummy/db/migrate/20240411013721_create_tickets.rb
class CreateTickets < ActiveRecord::Migration[7.1] def change create_table :tickets do |t| t.string :name t.references :user, null: false, foreign_key: true t.timestamps end end end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/test/dummy/db/migrate/20240411013524_create_users.rb
test/dummy/db/migrate/20240411013524_create_users.rb
class CreateUsers < ActiveRecord::Migration[7.1] def change create_table :users do |t| t.string :name t.timestamps end end end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/test/dummy/config/application.rb
test/dummy/config/application.rb
require_relative "boot" require "rails/all" # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) require "passkit" module Dummy class Application < Rails::Application config.load_defaults Rails::VERSION::STRING.to_f # For compatibility with applications that use this config config.action_controller.include_all_helpers = false # Configuration for the application, engines, and railties goes here. # # These settings can be overridden in specific environments using the files # in config/environments, which are processed later. # # config.time_zone = "Central Time (US & Canada)" # config.eager_load_paths << Rails.root.join("extras") end end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/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
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/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. # max_threads_count = ENV.fetch("RAILS_MAX_THREADS", 5) min_threads_count = ENV.fetch("RAILS_MIN_THREADS", max_threads_count) threads min_threads_count, max_threads_count # Specifies the `worker_timeout` threshold that Puma will use to wait before # terminating a worker in development environments. # worker_timeout 3600 if ENV.fetch("RAILS_ENV", "development") == "development" # 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 `pidfile` that Puma will use. pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" } # Specifies the number of `workers` to boot in clustered mode. # Workers are forked web server 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. # # preload_app! # Allow puma to be restarted by `bin/rails restart` command. plugin :tmp_restart
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/test/dummy/config/routes.rb
test/dummy/config/routes.rb
Rails.application.routes.draw do mount Passkit::Engine => "/passkit" end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/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
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/test/dummy/config/initializers/content_security_policy.rb
test/dummy/config/initializers/content_security_policy.rb
# Be sure to restart your server when you modify this file. # Define an application-wide content security policy. # See the Securing Rails Applications Guide for more information: # https://guides.rubyonrails.org/security.html#content-security-policy-header # Rails.application.configure do # config.content_security_policy do |policy| # policy.default_src :self, :https # policy.font_src :self, :https, :data # policy.img_src :self, :https, :data # policy.object_src :none # policy.script_src :self, :https # policy.style_src :self, :https # # Specify URI for violation reports # # policy.report_uri "/csp-violation-report-endpoint" # end # # # Generate session nonces for permitted importmap and inline scripts # config.content_security_policy_nonce_generator = ->(request) { request.session.id.to_s } # config.content_security_policy_nonce_directives = %w(script-src) # # # Report violations without enforcing the policy. # # config.content_security_policy_report_only = true # end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/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 parameters to be filtered from the log file. Use this to limit dissemination of # sensitive information. See the ActiveSupport::ParameterFilter documentation for supported # notations and behaviors. Rails.application.config.filter_parameters += [ :passw, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn ]
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/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
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/test/dummy/config/initializers/permissions_policy.rb
test/dummy/config/initializers/permissions_policy.rb
# Define an application-wide HTTP permissions policy. For further # information see https://developers.google.com/web/updates/2018/06/feature-policy # # Rails.application.config.permissions_policy do |f| # f.camera :none # f.gyroscope :none # f.microphone :none # f.usb :none # f.fullscreen :self # f.payment :self, "https://secure.example.com" # end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/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 the app/assets # folder are already added. # Rails.application.config.assets.precompile += %w( admin.js admin.css )
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/test/dummy/config/initializers/passkit.rb
test/dummy/config/initializers/passkit.rb
Passkit.configure do |config| config.available_passes['Passkit::UserStoreCard'] = -> { User.create!(name: "ExampleName") } end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/test/dummy/config/environments/test.rb
test/dummy/config/environments/test.rb
require "active_support/core_ext/integer/time" # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Turn false under Spring and add config.action_view.cache_template_loading = true. config.cache_classes = true # Eager loading loads your whole application. When running a single test locally, # this probably isn't necessary. It's a good idea to do in a continuous integration # system, or in some way before deploying your code. config.eager_load = ENV["CI"].present? # Configure public file server for tests with Cache-Control for performance. config.public_file_server.enabled = true config.public_file_server.headers = { "Cache-Control" => "public, max-age=#{1.hour.to_i}" } # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false config.cache_store = :null_store # 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 # Store uploaded files on the local file system in a temporary directory. config.active_storage.service = :test 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 # Raise exceptions for disallowed deprecations. config.active_support.disallowed_deprecation = :raise # Tell Active Support which deprecation messages to disallow. config.active_support.disallowed_deprecation_warnings = [] # Raises error for missing translations. # config.i18n.raise_on_missing_translations = true # Annotate rendered view with file names. # config.action_view.annotate_rendered_view_with_filenames = true end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/test/dummy/config/environments/development.rb
test/dummy/config/environments/development.rb
require "active_support/core_ext/integer/time" Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded any time # it changes. 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 server timing config.server_timing = true # Enable/disable caching. By default caching is disabled. # Run rails dev:cache to toggle caching. if Rails.root.join("tmp/caching-dev.txt").exist? config.action_controller.perform_caching = true config.action_controller.enable_fragment_cache_logging = true config.cache_store = :memory_store config.public_file_server.headers = { "Cache-Control" => "public, max-age=#{2.days.to_i}" } else config.action_controller.perform_caching = false config.cache_store = :null_store end # Store uploaded files on the local file system (see config/storage.yml for options). config.active_storage.service = :local # 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 exceptions for disallowed deprecations. config.active_support.disallowed_deprecation = :raise # Tell Active Support which deprecation messages to disallow. config.active_support.disallowed_deprecation_warnings = [] # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Highlight code that triggered database queries in logs. config.active_record.verbose_query_logs = true # Suppress logger output for asset requests. config.assets.quiet = true # Raises error for missing translations. # config.i18n.raise_on_missing_translations = true # Annotate rendered view with file names. # config.action_view.annotate_rendered_view_with_filenames = true # Uncomment if you wish to allow Action Cable access from any origin. # config.action_cable.disable_request_forgery_protection = true config.hosts << URI.parse(ENV.fetch("PASSKIT_WEB_SERVICE_HOST")).host end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/test/dummy/config/environments/production.rb
test/dummy/config/environments/production.rb
require "active_support/core_ext/integer/time" Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.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 # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). # config.require_master_key = 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 CSS using a preprocessor. # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = false # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.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 # Store uploaded files on the local file system (see config/storage.yml for options). config.active_storage.service = :local # 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 # Include generic and useful information about system operation, but avoid logging too much # information to avoid inadvertent exposure of personally identifiable information (PII). config.log_level = :info # 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_production" 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 # Don't log any deprecations. config.active_support.report_deprecations = false # 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
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/lib/passkit.rb
lib/passkit.rb
# frozen_string_literal: true require "rails" require "passkit/engine" require "zeitwerk" loader = Zeitwerk::Loader.for_gem loader.ignore("#{__dir__}/generators") loader.setup module Passkit class Error < StandardError; end class << self attr_accessor :configuration end def self.configure self.configuration ||= Configuration.new yield(configuration) if block_given? end class Configuration attr_accessor :available_passes, :web_service_host, :certificate_key, :private_p12_certificate, :apple_intermediate_certificate, :apple_team_identifier, :pass_type_identifier DEFAULT_AUTHENTICATION = proc do authenticate_or_request_with_http_basic("Passkit Dashboard. Login required") do |username, password| username == ENV["PASSKIT_DASHBOARD_USERNAME"] && password == ENV["PASSKIT_DASHBOARD_PASSWORD"] end end def authenticate_dashboard_with(&block) @authenticate = block if block @authenticate || DEFAULT_AUTHENTICATION end def initialize @available_passes = {"Passkit::ExampleStoreCard" => -> {}} @web_service_host = ENV["PASSKIT_WEB_SERVICE_HOST"] || (raise "Please set PASSKIT_WEB_SERVICE_HOST") raise("PASSKIT_WEB_SERVICE_HOST must start with https://") unless @web_service_host.start_with?("https://") @certificate_key = ENV["PASSKIT_CERTIFICATE_KEY"] || (raise "Please set PASSKIT_CERTIFICATE_KEY") @private_p12_certificate = ENV["PASSKIT_PRIVATE_P12_CERTIFICATE"] || (raise "Please set PASSKIT_PRIVATE_P12_CERTIFICATE") @apple_intermediate_certificate = ENV["PASSKIT_APPLE_INTERMEDIATE_CERTIFICATE"] || (raise "Please set PASSKIT_APPLE_INTERMEDIATE_CERTIFICATE") @apple_team_identifier = ENV["PASSKIT_APPLE_TEAM_IDENTIFIER"] || (raise "Please set PASSKIT_APPLE_TEAM_IDENTIFIER") @pass_type_identifier = ENV["PASSKIT_PASS_TYPE_IDENTIFIER"] || (raise "Please set PASSKIT_PASS_TYPE_IDENTIFIER") end end end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/lib/generators/passkit/install_generator.rb
lib/generators/passkit/install_generator.rb
# frozen_string_literal: true require "rails/generators/base" require "rails/generators/migration" module Passkit module Generators class InstallGenerator < Rails::Generators::Base include Rails::Generators::Migration source_root File.expand_path("../../templates", __FILE__) # Implement the required interface for Rails::Generators::Migration. def self.next_migration_number(dirname) next_migration_number = current_migration_number(dirname) + 1 ActiveRecord::Migration.next_migration_number(next_migration_number) end desc "Copy all files to your application." def generate_files migration_template "create_passkit_tables.rb", "db/migrate/create_passkit_tables.rb" copy_file "passkit.rb", "config/initializers/passkit.rb" end end end end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/lib/generators/templates/passkit.rb
lib/generators/templates/passkit.rb
Passkit.configure do |config| # config.available_passes['Passkit::YourPass'] = -> { User.create } end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/lib/passkit/version.rb
lib/passkit/version.rb
# frozen_string_literal: true module Passkit VERSION = "0.7.0" end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/lib/passkit/base_pass.rb
lib/passkit/base_pass.rb
module Passkit class BasePass def initialize(generator = nil) @generator = generator end def format_version ENV["PASSKIT_FORMAT_VERSION"] || 1 end def apple_team_identifier ENV["PASSKIT_APPLE_TEAM_IDENTIFIER"] || raise(Error.new("Missing environment variable: PASSKIT_APPLE_TEAM_IDENTIFIER")) end def pass_type_identifier ENV["PASSKIT_PASS_TYPE_IDENTIFIER"] || raise(Error.new("Missing environment variable: PASSKIT_PASS_TYPE_IDENTIFIER")) end def language nil end def last_update @generator&.updated_at end def pass_path rails_folder = Rails.root.join("private/passkit/#{folder_name}") # if folder exists, otherwise is in the gem itself under lib/passkit/base_pass if File.directory?(rails_folder) rails_folder else File.join(File.dirname(__FILE__), folder_name) end end def pass_type :storeCard # :coupon # :eventTicket # :generic # :boardingPass end def web_service_url raise Error.new("Missing environment variable: PASSKIT_WEB_SERVICE_HOST") unless ENV["PASSKIT_WEB_SERVICE_HOST"] "#{ENV["PASSKIT_WEB_SERVICE_HOST"]}/passkit/api" end # The foreground color, used for the values of fields shown on the front of the pass. def foreground_color # black "rgb(0, 0, 0)" end # The background color, used for the background of the front and back of the pass. # If you provide a background image, any background color is ignored. def background_color # white "rgb(255, 255, 255)" end # The label color, used for the labels of fields shown on the front of the pass. def label_color # black "rgb(0, 0, 0)" end # The organization name is displayed on the lock screen when your pass is relevant and by apps such as Mail which # act as a conduit for passes. The value for the organizationName key in the pass specifies the organization name. # Choose a name that users recognize and associate with your organization or company. def organization_name "Passkit" end # The description lets VoiceOver make your pass accessible to blind and low-vision users. The value for the # description key in the pass specifies the description. # @see https://developer.apple.com/library/archive/documentation/UserExperience/Conceptual/PassKit_PG/Creating.html def description "A basic description for a pass" end # An array of up to 10 latitudes and longitudes. iOS uses these locations to determine when to display the pass on the lock screen # # @see https://developer.apple.com/library/archive/documentation/UserExperience/Conceptual/PassKit_PG/Creating.html def locations [] end def voided false end # After base files are copied this is called to allow for adding custom images def add_other_files(path) end # Distance in meters from locations; if blank uses pass default. # The system uses the smaller of either this distance or the default distance. def max_distance end # URL to launch the associated app (nil by default) # Returns a String def app_launch_url end # A list of Apple App Store identifiers for apps associated # with the pass. The first one that is compatible with the # device is picked. # Returns an array of numbers def associated_store_identifiers [] end # An array of barcodes, the first one that can # be displayed on the device is picked. # Returns an array of hashes representing Pass.Barcodes def barcodes [] end # List of iBeacon identifiers to identify when the # pass should be displayed. # Returns an array of hashes representing Pass.Beacons def beacons [] end # Information specific to a boarding pass # Returns a hash representing Pass.BoardingPass # https://developer.apple.com/documentation/walletpasses/pass/boardingpass # i.e {transitType: 'PKTransitTypeGeneric'} def boarding_pass {} end # Date and time the pass expires, must include # days, hours and minutes (seconds are optional) # Returns a String representing the date and time in W3C format ('%Y-%m-%dT%H:%M:%S%:z') # For example, 1980-05-07T10:30-05:00. def expiration_date end # A key to identify group multiple passes together # (e.g. a number of boarding passes for the same trip) # Returns a String def grouping_identifier end # Information specific to Value Added Service Protocol # transactions # Returns a hash representing Pass.NFC def nfc end # Date and time when the pass becomes relevant and should be # displayed, must include days, hours and minutes # (seconds are optional) # Returns a String representing the date and time in W3C format ('%Y-%m-%dT%H:%M:%S%:z') def relevant_date end # Machine readable metadata that the device can use # to suggest actions # Returns a hash representing SemanticTags def semantics end # Display the strip image without a shine effect # Returns a boolean def suppress_strip_shine true end # JSON dictionary to display custom information for # companion apps. Data isn't displayed to the user. e.g. # a machine readable version of the user's favourite coffee def user_info end def file_name @file_name ||= SecureRandom.uuid end # QRCode by default def barcode { messageEncoding: "iso-8859-1", format: "PKBarcodeFormatQR", message: "https://github.com/coorasse/passkit", altText: "https://github.com/coorasse/passkit" } end # Barcode example # def barcode # { messageEncoding: 'iso-8859-1', # format: 'PKBarcodeFormatCode128', # message: '12345', # altText: '12345' } # end def logo_text "Logo text" end def header_fields [] end def primary_fields [] end def secondary_fields [] end def auxiliary_fields [] end def back_fields [] end def sharing_prohibited false end private def folder_name self.class.name.demodulize.underscore end end end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/lib/passkit/example_store_card.rb
lib/passkit/example_store_card.rb
module Passkit class ExampleStoreCard < BasePass def pass_type :storeCard # :coupon end def foreground_color "rgb(0, 0, 0)" end def background_color "rgb(255, 255, 255)" end def organization_name "Passkit" end def description "A basic description for a pass" end # A pass can have up to ten relevant locations # # @see https://developer.apple.com/library/archive/documentation/UserExperience/Conceptual/PassKit_PG/Creating.html def locations [] end def voided false end def file_name @file_name ||= SecureRandom.uuid end # QRCode by default def barcodes [ { messageEncoding: "iso-8859-1", format: "PKBarcodeFormatQR", message: "https://github.com/coorasse/passkit", altText: "https://github.com/coorasse/passkit" } ] end # Barcode example # def barcode # { messageEncoding: 'iso-8859-1', # format: 'PKBarcodeFormatCode128', # message: '12345', # altText: '12345' } # end def logo_text "Loyalty Card" end def relevant_date Time.current.strftime('%Y-%m-%dT%H:%M:%S%:z') end def expiration_date # Expire the pass tomorrow (Time.current + 1.day).strftime('%Y-%m-%dT%H:%M:%S%:z') end def semantics { balance: { amount: "100", currencyCode: "USD" } } end def header_fields [{ key: "balance", label: "Balance", value: 100, currencyCode: "$" }] end def back_fields [{ key: "example1", label: "Code", value: "0123456789" }, { key: "example2", label: "Creator", value: "https://github.com/coorasse" }, { key: "example3", label: "Contact", value: "rodi@hey.com" }] end def auxiliary_fields [{ key: "name", label: "Name", value: "Alessandro Rodi" }, { key: "email", label: "Email", value: "rodi@hey.com" }, { key: "phone", label: "Phone", value: "+41 1234567890" }] end private def folder_name self.class.name.demodulize.underscore end end end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/lib/passkit/url_encrypt.rb
lib/passkit/url_encrypt.rb
module Passkit class UrlEncrypt class << self def encrypt(payload) string = payload.to_json cipher = cypher.encrypt cipher.key = encryption_key s = cipher.update(string) + cipher.final s.unpack1("H*").upcase end def decrypt(string) cipher = cypher.decrypt cipher.key = encryption_key s = [string].pack("H*").unpack("C*").pack("c*") JSON.parse(cipher.update(s) + cipher.final, symbolize_names: true) end private def encryption_key key = ENV.fetch("PASSKIT_URL_ENCRYPTION_KEY") { Rails.application.secret_key_base } key[0..15] end def cypher OpenSSL::Cipher.new("AES-128-CBC") end end end end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/lib/passkit/generator.rb
lib/passkit/generator.rb
require "zip" module Passkit class Generator TMP_FOLDER = Rails.root.join("tmp/passkit").freeze def initialize(pass) @pass = pass @generator = pass.generator end def generate_and_sign check_necessary_files create_temporary_directory copy_pass_to_tmp_location @pass.instance.add_other_files(@temporary_path) clean_ds_store_files I18n.with_locale(@pass.language) do generate_json_pass end generate_json_manifest sign_manifest compress_pass_file end def self.compress_passes_files(files) zip_path = TMP_FOLDER.join("#{SecureRandom.uuid}.pkpasses") zipped_file = File.open(zip_path, "w") Zip::OutputStream.open(zipped_file.path) do |z| files.each do |file| z.put_next_entry(File.basename(file)) z.print File.read(file) end end zip_path end private def check_necessary_files raise "icon.png is not present in #{@pass.pass_path}" unless File.exist?(File.join(@pass.pass_path, "icon.png")) end def create_temporary_directory FileUtils.mkdir_p(TMP_FOLDER) unless File.directory?(TMP_FOLDER) @temporary_path = TMP_FOLDER.join(@pass.file_name.to_s) FileUtils.rm_rf(@temporary_path) if File.directory?(@temporary_path) end def copy_pass_to_tmp_location FileUtils.cp_r(@pass.pass_path, @temporary_path) end def clean_ds_store_files Dir.glob(@temporary_path.join("**/.DS_Store")).each { |file| File.delete(file) } end def generate_json_pass pass = { formatVersion: @pass.format_version, teamIdentifier: @pass.apple_team_identifier, authenticationToken: @pass.authentication_token, backgroundColor: @pass.background_color, description: @pass.description, foregroundColor: @pass.foreground_color, labelColor: @pass.label_color, locations: @pass.locations, logoText: @pass.logo_text, organizationName: @pass.organization_name, passTypeIdentifier: @pass.pass_type_identifier, serialNumber: @pass.serial_number, sharingProhibited: @pass.sharing_prohibited, suppressStripShine: @pass.suppress_strip_shine, voided: @pass.voided, webServiceURL: @pass.web_service_url } pass[:maxDistance] = @pass.max_distance if @pass.max_distance # If the newer barcodes attribute has been used, then # include the list of barcodes, otherwise fall back to # the original barcode attribute barcodes = @pass.barcodes || [] if barcodes.empty? pass[:barcode] = @pass.barcode else pass[:barcodes] = @pass.barcodes end pass[:appLaunchURL] = @pass.app_launch_url if @pass.app_launch_url pass[:associatedStoreIdentifiers] = @pass.associated_store_identifiers unless @pass.associated_store_identifiers.empty? pass[:beacons] = @pass.beacons unless @pass.beacons.empty? pass[:expirationDate] = @pass.expiration_date if @pass.expiration_date pass[:groupingIdentifier] = @pass.grouping_identifier if @pass.grouping_identifier pass[:nfc] = @pass.nfc if @pass.nfc pass[:relevantDate] = @pass.relevant_date if @pass.relevant_date pass[:semantics] = @pass.semantics if @pass.semantics pass[:userInfo] = @pass.user_info if @pass.user_info pass[@pass.pass_type] = { headerFields: @pass.header_fields, primaryFields: @pass.primary_fields, secondaryFields: @pass.secondary_fields, auxiliaryFields: @pass.auxiliary_fields, backFields: @pass.back_fields } pass[:boardingPass].merge(@pass.boarding_pass) if @pass.pass_type == :boardingPass && @pass.boarding_pass File.write(@temporary_path.join("pass.json"), pass.to_json) end # rubocop:enable Metrics/AbcSize def generate_json_manifest manifest = {} Dir.glob(@temporary_path.join("**")).each do |file| manifest[File.basename(file)] = Digest::SHA1.hexdigest(File.read(file)) end @manifest_url = @temporary_path.join("manifest.json") File.write(@manifest_url, manifest.to_json) end CERTIFICATE = Rails.root.join(ENV["PASSKIT_PRIVATE_P12_CERTIFICATE"]) INTERMEDIATE_CERTIFICATE = Rails.root.join(ENV["PASSKIT_APPLE_INTERMEDIATE_CERTIFICATE"]) CERTIFICATE_PASSWORD = ENV["PASSKIT_CERTIFICATE_KEY"] # :nocov: def sign_manifest p12_certificate = OpenSSL::PKCS12.new(File.read(CERTIFICATE), CERTIFICATE_PASSWORD) intermediate_certificate = OpenSSL::X509::Certificate.new(File.read(INTERMEDIATE_CERTIFICATE)) flag = OpenSSL::PKCS7::DETACHED | OpenSSL::PKCS7::BINARY signed = OpenSSL::PKCS7.sign(p12_certificate.certificate, p12_certificate.key, File.read(@manifest_url), [intermediate_certificate], flag) @signature_url = @temporary_path.join("signature") File.open(@signature_url, "w") { |f| f.syswrite signed.to_der } end # :nocov: def compress_pass_file zip_path = TMP_FOLDER.join("#{@pass.file_name}.pkpass") zipped_file = File.open(zip_path, "w") Zip::OutputStream.open(zipped_file.path) do |z| Dir.glob(@temporary_path.join("**")).each do |file| z.put_next_entry(File.basename(file)) z.print File.read(file) end end zip_path end end end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/lib/passkit/factory.rb
lib/passkit/factory.rb
module Passkit class Factory class << self # generator is an optional ActiveRecord object, the application data for the pass def create_pass(pass_class, generator = nil) pass = Passkit::Pass.create!(klass: pass_class, generator: generator) Passkit::Generator.new(pass).generate_and_sign end end end end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/lib/passkit/payload_generator.rb
lib/passkit/payload_generator.rb
module Passkit class PayloadGenerator VALIDITY = 30.days def self.encrypted(pass_class, generator = nil, collection_name = nil) UrlEncrypt.encrypt(hash(pass_class, generator, collection_name)) end def self.hash(pass_class, generator = nil, collection_name = nil) valid_until = VALIDITY.from_now {valid_until: valid_until, generator_class: generator&.class&.name, generator_id: generator&.id, pass_class: pass_class.name, collection_name: collection_name} end end end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/lib/passkit/url_generator.rb
lib/passkit/url_generator.rb
module Passkit class UrlGenerator include Passkit::Engine.routes.url_helpers def initialize(pass_class, generator = nil, collection_name = nil) @url = passes_api_url(host: ENV["PASSKIT_WEB_SERVICE_HOST"], payload: PayloadGenerator.encrypted(pass_class, generator, collection_name)) end def ios @url end WALLET_PASS_PREFIX = "https://walletpass.io?u=".freeze # @see https://walletpasses.io/developer/ def android "#{WALLET_PASS_PREFIX}#{@url}" end end end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/lib/passkit/engine.rb
lib/passkit/engine.rb
# frozen_string_literal: true module Passkit class Engine < ::Rails::Engine isolate_namespace Passkit end end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
coorasse/passkit
https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/config/routes.rb
config/routes.rb
# frozen_string_literal: true Passkit::Engine.routes.draw do scope :api, constraints: {pass_type_id: /.*/} do scope :v1 do resources :devices, only: [] do post "registrations/:pass_type_id/:serial_number" => "api/v1/registrations#create", :as => :register delete "registrations/:pass_type_id/:serial_number" => "api/v1/registrations#destroy", :as => :unregister get "registrations/:pass_type_id" => "api/v1/registrations#show", :as => :registrations end get "passes/:pass_type_id/:serial_number" => "api/v1/passes#show", :as => :pass get "passes/:payload", to: "api/v1/passes#create", as: :passes_api post "log" => "api/v1/logs#create", :as => :log end end namespace :dashboard do resources :previews, only: [:index, :show], param: :class_name resources :logs, only: [:index] resources :passes, only: [:index] end end
ruby
MIT
83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f
2026-01-04T17:57:15.346461Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/benchmark/msgpack-pooling.rb
benchmark/msgpack-pooling.rb
#!/usr/bin/env ruby # frozen_string_literal: true require "bundler/setup" require "paquito" require "benchmark/ips" BASELINE = Paquito::CodecFactory.build([Symbol], pool: false) POOLED = Paquito::CodecFactory.build([Symbol], pool: 1) PAYLOAD = BASELINE.dump(:foo) MARSHAL_PAYLOAD = Marshal.dump(:foo) Benchmark.ips do |x| x.report("marshal") { Marshal.load(MARSHAL_PAYLOAD) } x.report("msgpack") { BASELINE.load(PAYLOAD) } x.report("pooled") { POOLED.load(PAYLOAD) } x.compare!(order: :baseline) end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/benchmark/string-bypass.rb
benchmark/string-bypass.rb
#!/usr/bin/env ruby # frozen_string_literal: true require "bundler/setup" require "paquito" require "benchmark/ips" CODEC = Paquito::CodecFactory.build([]) VERSIONED = Paquito::SingleBytePrefixVersion.new(0, 0 => CODEC) BYPASS = Paquito::SingleBytePrefixVersionWithStringBypass.new(0, 0 => CODEC) [100, 10_000, 1_000_000].each do |size| string = Random.bytes(size).freeze msgpack_payload = VERSIONED.dump(string).freeze bypass_payload = BYPASS.dump(string).freeze marshal_payload = Marshal.dump(string).freeze puts " === Read #{size}B ===" Benchmark.ips do |x| x.report("marshal") { Marshal.load(marshal_payload) } x.report("msgpack") { VERSIONED.load(msgpack_payload) } x.report("bypass") { BYPASS.load(bypass_payload) } x.compare!(order: :baseline) end puts " === Write #{size}B ===" Benchmark.ips do |x| x.report("marshal") { Marshal.dump(string) } x.report("msgpack") { VERSIONED.dump(string) } x.report("bypass") { BYPASS.dump(string) } x.compare!(order: :baseline) end puts end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/benchmark/flat-entry-coder.rb
benchmark/flat-entry-coder.rb
#!/usr/bin/env ruby # frozen_string_literal: true require "bundler/setup" require "paquito" require "active_support" require "benchmark/ips" CODEC = Paquito::CodecFactory.build ORIGINAL = Paquito::SingleBytePrefixVersion.new( 0, 0 => Paquito.chain( Paquito::CacheEntryCoder, CODEC, ), ) FLAT = Paquito::FlatCacheEntryCoder.new( Paquito::SingleBytePrefixVersionWithStringBypass.new( 0, 0 => CODEC, ), ) entries = { small_string: "Hello World!", bytes_1mb: Random.bytes(1_000_000), int_array: 1000.times.to_a, } entries.each do |name, object| entry = ActiveSupport::Cache::Entry.new(object, expires_at: 15.minutes.from_now.to_f) original_payload = ORIGINAL.dump(entry).freeze flat_payload = FLAT.dump(entry).freeze puts " === Read #{name} ===" Benchmark.ips do |x| x.report("original") { ORIGINAL.load(original_payload) } x.report("flat") { FLAT.load(flat_payload) } x.compare!(order: :baseline) end puts " === Write #{name} ===" Benchmark.ips do |x| x.report("original") { ORIGINAL.dump(entry) } x.report("flat") { FLAT.dump(entry) } x.compare!(order: :baseline) end puts end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/test/test_helper.rb
test/test_helper.rb
# frozen_string_literal: true # Load Sorbet runtime early so that all conditional requires # from this gem are loaded properly below require "sorbet-runtime" require "zlib" require "json" require "yaml" require "bigdecimal" $LOAD_PATH.unshift(File.expand_path("../lib", __dir__)) require "paquito" require "minitest/autorun" class PaquitoTest < Minitest::Test class << self # Stolen from Active Support def test(name, &block) test_name = "test_#{name.gsub(/\s+/, "_")}".to_sym defined = method_defined?(test_name) raise "#{test_name} is already defined in #{self}" if defined if block_given? define_method(test_name, &block) else define_method(test_name) do flunk("No implementation provided for #{name}") end end end end private def with_env(key, value) old_env_id = ENV[key] if value.nil? ENV.delete(key) else ENV[key] = value.to_s end yield ensure ENV[key] = old_env_id end def update_env(other) original = ENV.to_h ENV.update(other) yield ensure ENV.replace(original) end end Dir[File.expand_path("support/*.rb", __dir__)].sort.each do |support| require support end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/test/activerecord/codec_factory_test.rb
test/activerecord/codec_factory_test.rb
# frozen_string_literal: true require "test_helper" class PaquitoCodecFactoryTest < PaquitoTest test "correctly encodes ActiveRecord::Base objects" do codec = Paquito::CodecFactory.build([ActiveRecord::Base]) value = Shop.new decoded_value = codec.load(codec.dump(value)) assert_equal value.attributes, decoded_value.attributes end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/test/activerecord/test_helper.rb
test/activerecord/test_helper.rb
# frozen_string_literal: true require File.expand_path("../test_helper.rb", __dir__) require "active_record" ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:") Dir[File.expand_path("support/*.rb", __dir__)].sort.each do |support| require support end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/test/activerecord/active_record_coder_test.rb
test/activerecord/active_record_coder_test.rb
# frozen_string_literal: true require "test_helper" class PaquitoActiveRecordCodecTest < PaquitoTest def setup @codec = Paquito::ActiveRecordCoder end test "correctly encodes AR object with no associations" do shop = Shop.find_by!(name: "Snow Devil") encoded_value = @codec.dump(shop) recovered_value = @codec.load(encoded_value) assert_equal(shop, recovered_value) end test "correctly encodes AR object with associations" do shop = Shop.preload(:products, :domain, :owner, :current_features).find_by!(name: "Snow Devil") assert_equal(true, shop.association(:products).loaded?) # has_many assert_equal(true, shop.association(:current_features).loaded?) # has_many through assert_equal(true, shop.association(:owner).loaded?) # belongs_to assert_equal(true, shop.association(:domain).loaded?) # has_one encoded_value = @codec.dump(shop) recovered_value = @codec.load(encoded_value) assert_equal(true, recovered_value.association(:products).loaded?) # has_many assert_equal(true, recovered_value.association(:current_features).loaded?) # has_many through assert_equal(true, recovered_value.association(:owner).loaded?) # belongs_to assert_equal(true, recovered_value.association(:domain).loaded?) # has_one refute_empty shop.products assert_equal shop.products.first, recovered_value.products.first end test "encodes wether the record was persisted or not" do shop = Shop.find_by!(name: "Snow Devil") assert_predicate shop, :persisted? recovered_shop = @codec.load(@codec.dump(shop)) assert_predicate recovered_shop, :persisted? new_shop = @codec.load([0, ["Shop", {}, true]]) refute_predicate new_shop, :persisted? recovered_shop = @codec.load(@codec.dump(new_shop)) refute_predicate recovered_shop, :persisted? end test "format is stable across payload commits" do shop = Shop.preload(:products).find_by!(name: "Snow Devil") recovered_shop = @codec.load(@codec.dump(shop)) recovered_shop.save assert_equal(shop, recovered_shop) assert_equal(shop.products, recovered_shop.products) end test "raises ClassMissingError if class is not defined" do serial = [0, ["Foo", {}]] codec = @codec error = assert_raises(Paquito::ActiveRecordCoder::ClassMissingError) do codec.load(serial) end assert_equal "undefined class: Foo", error.message end test "raises AssociationMissingError if association is undefined" do serial = [ [0, [[:foo, [[1, [[:shop, 0]]]]]]], ["Shop", {}], ["Product", {}], ] codec = @codec error = assert_raises(Paquito::ActiveRecordCoder::AssociationMissingError) do codec.load(serial) end assert_equal "undefined association: foo", error.message end test "raises ColumnsDigestMismatch if columns hash digest does not match" do shop = Shop.find_by!(name: "Snow Devil") hash_data = "id:INTEGER,name:varchar,settings:BLOB,owner_id:INTEGER" correct_hash = ::Digest::MD5.digest(hash_data).unpack1("s") serial = [ [0], ["Shop", shop.attributes_for_database, false, correct_hash], ] assert_equal(shop, @codec.load(serial)) incorrect_hash = 10 serial = [ [0], ["Shop", shop.attributes_for_database, false, incorrect_hash], ] error = assert_raises(Paquito::ActiveRecordCoder::ColumnsDigestMismatch) do @codec.load(serial) end assert_equal( "\"#{incorrect_hash}\" does not match the expected digest of \"#{correct_hash}\"", error.message, ) end test "works with json column with symbol keys assigned" do extension = Extension.new(executable: { a: "b" }) codec_reloaded = @codec.load(@codec.dump(extension)) assert_equal({ "a" => "b" }, codec_reloaded.attributes["executable"]) end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/test/activerecord/serialized_column_test.rb
test/activerecord/serialized_column_test.rb
# frozen_string_literal: true require "test_helper" class PaquitoSerializedColumnTest < PaquitoTest def setup @settings = { currency: "€" }.freeze @model = Shop.create!(name: "Test", settings: @settings) end test "deserialize the payload" do assert_equal "#\xE2\x98\xA01\xE2\x98\xA2\n\x81\xD7\x00currency\xA3\xE2\x82\xAC".b, @model.settings_before_type_cast assert_equal(@settings, @model.settings) end test "serialize default values as `nil`" do @model.update!(settings: {}) assert_nil @model.settings_before_type_cast end test "initialize with the default values" do @model.update_column(:settings, nil) @model.reload assert_equal({}, @model.settings) end test "raises when trying to serialize a different type" do error = assert_raises(ActiveRecord::SerializationTypeMismatch) do @model.update(settings: []) end assert_equal "settings was supposed to be a Hash, but was a Array. -- []", error.message end class ClassWithRequiredArguments def initialize(foo) end end test "enforce 0 arity on the type constructor" do error = assert_raises(ArgumentError) do Paquito::SerializedColumn.new(JSON, ClassWithRequiredArguments) end assert_equal( "Cannot serialize PaquitoSerializedColumnTest::ClassWithRequiredArguments. " \ "Classes passed to `serialize` must have a 0 argument constructor.", error.message, ) end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/test/activerecord/codec_factory_active_record_test.rb
test/activerecord/codec_factory_active_record_test.rb
# frozen_string_literal: true require "test_helper" class PaquitoCodecFactoryActiveRecordTest < PaquitoTest test "MessagePack factory correctly encodes AR::Base objects" do shop = Shop.preload(:products, :domain).first codec = Paquito::CodecFactory.build([ActiveRecord::Base]) assert_equal(true, shop.association(:products).loaded?) assert_equal(true, shop.association(:domain).loaded?) encoded_value = codec.dump(shop) recovered_value = codec.load(encoded_value) assert_equal(true, recovered_value.association(:products).loaded?) assert_equal(true, recovered_value.association(:domain).loaded?) shop.save reencoded_value = codec.dump(shop) assert_equal(shop, codec.load(reencoded_value)) end test "MessagePack factory supports encoding scheme either with or without columns hash" do shop = Shop.preload(:products, :domain).first payload_without_columns_hash = "\xC8\x01\x1A\x06\x95\x92\x00\x92\x92\xC7\x06\x00domain\x92\x01\x91\x92\xD6\x00"\ "shop\x00\x92\xD7\x00products\x92\x92\x02\x91\x92\xD6\x00shop\x00\x92\x03\x91\x92\xD6\x00"\ "shop\x00\x92\xA4Shop\x84\xA2id\x01\xA4name\xAASnow Devil\xA8settings\xC4\x18#\xE2\x98\xA0"\ "1\xE2\x98\xA2\n\x81\xD7\x00currency\xA3\xE2\x82\xAC\xA8owner_id\xC0\x92\xA6Domain\x83\xA7"\ "shop_id\x01\xA2id\x01\xA4name\xABexample.com\x92\xA7Product\x84\xA7shop_id\x01\xA2id\x01\xA4"\ "name\xAFCheap Snowboard\xA8quantity\x18\x92\xA7Product\x84\xA7shop_id\x01\xA2id\x02\xA4name"\ "\xB3Expensive Snowboard\xA8quantity\x02".b codec = Paquito::CodecFactory.build([ActiveRecord::Base]) recovered_value = codec.load(payload_without_columns_hash) assert_equal(shop, recovered_value) assert_equal(true, recovered_value.association(:products).loaded?) assert_equal(true, recovered_value.association(:domain).loaded?) encoded_value = codec.dump(shop) assert_equal(shop, codec.load(encoded_value)) payload_with_columns_hash = "\xC8\x01*\x06\x95\x92\x00\x92\x92\xC7\x06\x00domain\x92\x01\x91\x92\xD6\x00shop"\ "\x00\x92\xD7\x00products\x92\x92\x02\x91\x92\xD6\x00shop\x00\x92\x03\x91\x92\xD6\x00shop\x00\x94\xA4Shop"\ "\x84\xA2id\x01\xA4name\xAASnow Devil\xA8settings\xC4\x18#\xE2\x98\xA01\xE2\x98\xA2\n\x81\xD7\x00currency\xA3"\ "\xE2\x82\xAC\xA8owner_id\xC0\xC2\xCD>\xAD\x94\xA6Domain\x83\xA7shop_id\x01\xA2id\x01\xA4name\xABexample.com"\ "\xC2\xCD\x14\x16\x94\xA7Product\x84\xA7shop_id\x01\xA2id\x01\xA4name\xAFCheap Snowboard\xA8quantity\x18\xC2"\ "\xD1\x9DF\x94\xA7Product\x84\xA7shop_id\x01\xA2id\x02\xA4name\xB3Expensive Snowboard\xA8quantity\x02\xC2\xD1"\ "\x9DF".b assert_equal(payload_with_columns_hash, encoded_value) assert_equal(shop, codec.load(payload_with_columns_hash)) end test "MessagePack factory handles serialized records with more elements" do shop = Shop.preload(:products, :domain).first payload = "\xC8\x01*\x06\x95\x92\x00\x92\x92\xC7\x06\x00domain\x92\x01\x91\x92\xD6\x00shop"\ "\x00\x92\xD7\x00products\x92\x92\x02\x91\x92\xD6\x00shop\x00\x92\x03\x91\x92\xD6\x00shop\x00\x94\xA4Shop"\ "\x84\xA2id\x01\xA4name\xAASnow Devil\xA8settings\xC4\x18#\xE2\x98\xA01\xE2\x98\xA2\n\x81\xD7\x00currency\xA3"\ "\xE2\x82\xAC\xA8owner_id\xC0\xC2\xCD>\xAD\x94\xA6Domain\x83\xA7shop_id\x01\xA2id\x01\xA4name\xABexample.com"\ "\xC2\xCD\x14\x16\x94\xA7Product\x84\xA7shop_id\x01\xA2id\x01\xA4name\xAFCheap Snowboard\xA8quantity\x18\xC2"\ "\xD1\x9DF\x94\xA7Product\x84\xA7shop_id\x01\xA2id\x02\xA4name\xB3Expensive Snowboard\xA8quantity\x02\xC2\xD1"\ "\x9DF".b codec = Paquito::CodecFactory.build([ActiveRecord::Base]) recovered_value = codec.load(payload) assert_equal(shop, recovered_value) end test "MessagePack factory handle binary columns in AR::Base objects" do model = Shop.first assert_instance_of ::ActiveModel::Type::Binary::Data, model.attributes_for_database.fetch("settings") payload = Paquito::ActiveRecordCoder.dump(model) assert_equal model, Paquito::ActiveRecordCoder.load(payload) raw_attributes = payload.dig(1, 1) assert_instance_of String, raw_attributes["settings"] codec = Paquito::CodecFactory.build([ActiveRecord::Base]) reloaded_model = codec.load(codec.dump(model)) assert_equal model.settings, reloaded_model.settings assert_equal model.settings_before_type_cast, reloaded_model.settings_before_type_cast end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/test/activerecord/support/models.rb
test/activerecord/support/models.rb
# frozen_string_literal: true ActiveRecord::Schema.define do create_table :users, force: true do |t| t.string(:email) end create_table :features, force: true do |t| t.string(:name) end create_table :shops, force: true do |t| t.string(:name) t.binary(:settings) t.references(:owner) end create_table :shop_features, force: true do |t| t.references(:shop) t.references(:feature) end create_table :extensions, force: true do |t| t.json(:executable) end create_table :products, force: true do |t| t.references(:shop) t.string(:name) t.integer(:quantity) end create_table :domains, force: true do |t| t.references(:shop) t.string(:name) end end class User < ActiveRecord::Base has_many :shops, inverse_of: :owner end class Feature < ActiveRecord::Base end class ShopFeature < ActiveRecord::Base belongs_to :shop belongs_to :feature end class Shop < ActiveRecord::Base belongs_to :owner, class_name: "User" has_one :domain has_many :products has_many :shop_features has_many :current_features, class_name: "Feature", through: :shop_features, source: :feature serialize :settings, coder: Paquito::SerializedColumn.new( Paquito::CommentPrefixVersion.new( 1, 0 => YAML, 1 => Paquito::CodecFactory.build([Symbol]), ), Hash, attribute_name: :settings, ) end class Product < ActiveRecord::Base belongs_to :shop end class Domain < ActiveRecord::Base belongs_to :shop end class Extension < ActiveRecord::Base end online_store = Feature.create!(name: "Online Store") snow_devil = Shop.create!(name: "Snow Devil", settings: { currency: "€" }) ShopFeature.create!(shop: snow_devil, feature: online_store) snow_devil.create_domain!(name: "example.com") snow_devil.products.create!(name: "Cheap Snowboard", quantity: 24) snow_devil.products.create!(name: "Expensive Snowboard", quantity: 2)
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/test/vanilla/comment_prefix_version_test.rb
test/vanilla/comment_prefix_version_test.rb
# frozen_string_literal: true require "test_helper" class PaquitoCommentPrefixVersionTest < PaquitoTest def setup @coder = Paquito::CommentPrefixVersion.new( 1, 0 => YAML, 1 => JSON, 2 => MessagePack, ) end test "#dump use the current version" do assert_equal "#☠1☢\n{\"foo\":42}", @coder.dump({ foo: 42 }) end test "#dump handle binary data" do coder = Paquito::CommentPrefixVersion.new(1, 1 => MessagePack) expected = { "foo" => 42 } assert_equal expected, coder.load(coder.dump(expected)) end test "#load respects the version prefix" do assert_equal({ foo: 42 }, @coder.load("#☠0☢\n---\n:foo: 42")) end test "#load assumes version 0 if the comment prefix is missing" do assert_equal({ foo: 42 }, @coder.load("---\n:foo: 42")) assert_raises Psych::BadAlias do @coder.load("foo:\n<<: *bar") end end test "#load handle empty strings" do @coder.load("") end test "#load raises an error on unknown versions" do error = assert_raises(Paquito::UnsupportedCodec) do @coder.load("#☠9☢\nblahblah") end assert_equal "Unsupported packer version 9", error.message end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/test/vanilla/conditional_compressor_test.rb
test/vanilla/conditional_compressor_test.rb
# frozen_string_literal: true require "test_helper" class ConditionalCompressorTest < PaquitoTest def setup @coder = Paquito::ConditionalCompressor.new( Zlib, 4, ) end test "it does not compress when under the threshold" do assert_equal "\x00foo".b, @coder.dump("foo") end test "it does compress when over the threshold" do string = "foobar" * 25 assert_equal "\x01#{Zlib.deflate(string)}".b, @coder.dump(string) end test "it does not compress if the compressed payload is larger" do string = "foobar" assert Zlib.deflate(string).bytesize > string.bytesize assert_equal "\x00#{string}".b, @coder.dump(string) end test "it decompress regardless of the size" do assert_equal "foo", @coder.load("\x01#{Zlib.deflate("foo")}") assert_equal "foobar", @coder.load("\x01#{Zlib.deflate("foobar")}") assert_equal "foo", @coder.load("\x00foo") assert_equal "foobar", @coder.load("\x00foobar") end test "it accept coders with the #deflate and #inflate interface" do @coder = Paquito::ConditionalCompressor.new(Zlib, 4) string = "foobar" * 25 assert_equal "\x01#{Zlib.deflate(string)}".b, @coder.dump(string) end test "it raises UnpackError when the byte prefix is corrupted" do @coder = Paquito::ConditionalCompressor.new(Zlib, 4) error = assert_raises(Paquito::UnpackError) do @coder.load("\x02foobar".b) end assert_includes error.message, "invalid ConditionalCompressor version" end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/test/vanilla/single_byte_prefix_version_test.rb
test/vanilla/single_byte_prefix_version_test.rb
# frozen_string_literal: true require "test_helper" class PaquitoSingleBytePrefixVersionTest < PaquitoTest def setup @coder = Paquito::SingleBytePrefixVersion.new( 1, 0 => YAML, 1 => JSON, 2 => MessagePack, ) end test "#dump use the current version" do assert_equal "\x01{\"foo\":42}".b, @coder.dump({ foo: 42 }) end test "#load respects the version prefix" do assert_equal({ foo: 42 }, @coder.load("\x00---\n:foo: 42")) end test "#load raises an error on unknown versions" do error = assert_raises(Paquito::UnsupportedCodec) do @coder.load("#{42.chr}blahblah") end assert_equal "Unsupported packer version 42", error.message end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/test/vanilla/safe_yaml_test.rb
test/vanilla/safe_yaml_test.rb
# frozen_string_literal: true require "test_helper" class SafeYAMLTest < PaquitoTest def setup @coder = Paquito::SafeYAML.new( permitted_classes: ["Hash", "Set", "Integer"], deprecated_classes: ["BigDecimal"], aliases: true, ) end test "#load accepts deprecated classes" do expected = BigDecimal("12.34") assert_equal expected, @coder.load(YAML.dump(expected)) end test "#load accepts permitted classes" do expected = Set[1, 2] assert_equal expected, @coder.load(YAML.dump(expected)) end test "#load translate errors" do error = assert_raises(Paquito::UnsupportedType) do @coder.load(YAML.dump(Time.new)) end assert_equal "Tried to load unspecified class: Time", error.message error = assert_raises(Paquito::UnpackError) do @coder.load("<<: *foo") end assert_includes ["Unknown alias: foo", "An alias referenced an unknown anchor: foo"], error.message assert_raises Paquito::UnpackError do @coder.load("*>>") end end test "#dump rejects deprecated classes" do error = assert_raises(Paquito::UnsupportedType) do @coder.dump(BigDecimal("12.34")) end assert_equal 'Tried to dump unspecified class: "BigDecimal"', error.message end test "#dump accepts permitted classes" do expected = Set[1, 2] assert_equal expected, @coder.load(@coder.dump(expected)) end test "#dump rejects objects that respond to #encode_with" do not_permitted_test_type = Class.new do def self.name "NotPermittedClass" end def encode_with(coder) coder["a"] = 1 end end object_to_dump = not_permitted_test_type.new assert(object_to_dump.respond_to?(:encode_with)) error = assert_raises(Paquito::UnsupportedType) do @coder.dump(object_to_dump) end assert_equal 'Tried to dump unspecified class: "NotPermittedClass"', error.message end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/test/vanilla/codec_factory_test.rb
test/vanilla/codec_factory_test.rb
# frozen_string_literal: true require "test_helper" module Paquito module SharedCodecFactoryTests # The difference is in the prefix which contains details about the internal representation (27 vs 9). # However both versions can read each others fine, so it's not a problem. RUBY_3_0_BIG_DECIMAL = "\xC7\n\x0427:0.123e3".b.freeze RUBY_3_1_BIG_DECIMAL = "\xC7\t\x049:0.123e3".b.freeze BIG_DECIMAL_PAYLOAD = BigDecimal::VERSION >= "3.1" ? RUBY_3_1_BIG_DECIMAL : RUBY_3_0_BIG_DECIMAL OBJECTS = { symbol: :symbol, string: "string", array: [:a, "b"], time: Time.new(2000, 1, 1, 2, 2, 2, "+00:00"), datetime: DateTime.new(2000, 1, 1, 4, 5, 6, "UTC"), date: Date.new(2000, 1, 1), hash: { a: [:a] }, }.freeze V0_PAYLOAD = "\x87\xC7\x06\x00symbol\xC7\x06\x00symbol\xC7\x06\x00string\xA6string\xC7\x05\x00array\x92" \ "\xD4\x00a\xA1b\xD6\x00time\xC7\f\x01\x1A`m8\x00\x00\x00\x00\x01\x00\x00\x00\xD7\x00datetime\xC7\x14" \ "\x02\xD0\a\x01\x01\x04\x05\x06\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x01\xD6\x00date\xD6" \ "\x03\xD0\a\x01\x01\xD6\x00hash\x81\xD4\x00a\x91\xD4\x00a".b.freeze V1_PAYLOAD = "\x87\xC7\x06\x00symbol\xC7\x06\x00symbol\xC7\x06\x00string\xA6string\xC7\x05\x00array\x92" \ "\xD4\x00a\xA1b\xD6\x00time\xC7\a\v\xCE8m`\x1A\x00\x00\xD7\x00datetime\xC7\v\f\xCD\a\xD0\x01\x01\x04" \ "\x05\x06\x01\x00\x01\xD6\x00date\xD6\x03\xD0\a\x01\x01\xD6\x00hash\x81\xD4\x00a\x91\xD4\x00a".b.freeze ObjectOne = Struct.new(:foo, :bar) do def as_pack [foo, bar] end def self.from_pack(payload) new(*payload) end end ObjectTwo = Struct.new(:baz, :qux) do def as_pack members.zip(values).to_h end def self.from_pack(payload) new(payload[:baz], payload[:qux]) end end def self.included(base = nil, &block) if base && !block_given? base.class_eval(&@included) elsif base.nil? && block_given? @included = block else raise "Can't pass both a base and and block" end end included do test "correctly encodes Symbol objects" do codec = Paquito::CodecFactory.build([Symbol]) assert_equal("\xC7\x05\x00hello".b, codec.dump(:hello)) assert_equal(:hello, codec.load(codec.dump(:hello))) end test "correctly encodes Time objects" do codec = Paquito::CodecFactory.build([Time]) value = Time.at(Rational(1_486_570_508_539_759, 1_000_000)).utc encoded_value = codec.dump(value) assert_equal("\xC7\v\v\xCEX\x9BD\f\xCE ,\x11\x98\x00".b, encoded_value) recovered_value = codec.load(encoded_value) assert_equal(value.nsec, recovered_value.nsec) assert_equal(value, recovered_value) end test "does not mutate Time objects" do time = Time.at(1_671_439_400, in: "+12:30") time_state = time.inspect assert_equal time_state, time.inspect @codec.dump(time) assert_equal time_state, time.inspect end test "correctly encodes DateTime objects" do codec = Paquito::CodecFactory.build([DateTime]) value = DateTime.new(2017, 2, 8, 11, 25, 12.571685, "EST") encoded_value = codec.dump(value) assert_equal("\xC7\x13\f\xCD\a\xE1\x02\b\v\x19\xCE\x00&]\xA1\xCE\x00\x03\r@\xFB\x18".b, encoded_value) assert_equal(value, codec.load(encoded_value)) now = DateTime.now assert_equal(now, codec.load(codec.dump(now))) end test "correctly encodes Date objects" do codec = Paquito::CodecFactory.build([Date]) value = Date.new(2017, 2, 8) encoded_value = codec.dump(value) assert_equal("\xD6\x03\xE1\a\x02\b".b, encoded_value) recovered_value = codec.load(encoded_value) assert_equal(value, recovered_value) end test "BigDecimal serialization is stable" do assert_equal( BIG_DECIMAL_PAYLOAD, @codec.dump(BigDecimal(123)), ) assert_equal( BigDecimal(123), @codec.load(RUBY_3_0_BIG_DECIMAL), ) assert_equal( BigDecimal(123), @codec.load(RUBY_3_1_BIG_DECIMAL), ) end test "reject malformed payloads with Paquito::PackError" do assert_raises Paquito::UnpackError do @codec.load("\x00\x00") end end test "correctly encodes BigDecimal objects" do codec = Paquito::CodecFactory.build([BigDecimal]) value = BigDecimal("123456789123456789.123456789123456789") encoded_value = codec.dump(value) assert_equal("\xC7,\x0445:0.123456789123456789123456789123456789e18".b, encoded_value) recovered_value = codec.load(encoded_value) assert_equal(value, recovered_value) end test "correctly encodes Set objects" do codec = Paquito::CodecFactory.build([Set]) value = Set.new([1, 2, [3, 4, Set.new([5])]]) encoded_value = codec.dump(value) assert_equal "\xC7\n\t\x93\x01\x02\x93\x03\x04\xD5\t\x91\x05".b, encoded_value recovered_value = codec.load(encoded_value) assert_equal(value, recovered_value) end test "supports freeze on load" do # without extra types codec = Paquito::CodecFactory.build([]) assert_equal(false, codec.load(codec.dump("foo")).frozen?) codec = Paquito::CodecFactory.build([], freeze: true) assert_equal(true, codec.load(codec.dump("foo")).frozen?) # with extra types codec = Paquito::CodecFactory.build([BigDecimal]) assert_equal(false, codec.load(codec.dump("foo")).frozen?) codec = Paquito::CodecFactory.build([BigDecimal], freeze: true) assert_equal(true, codec.load(codec.dump("foo")).frozen?) end test "does not enforce strictness of Hash type without serializable_type option" do codec = Paquito::CodecFactory.build([]) type_subclass = Class.new(Hash) object = type_subclass.new assert_equal Hash, codec.load(codec.dump(object)).class end test "enforces strictness of Hash type with serializable_type option" do codec = Paquito::CodecFactory.build([], serializable_type: true) type_subclass = Class.new(Hash) object = type_subclass.new assert_raises(Paquito::PackError) { codec.dump(object) } end test "rejects unknown types with Paquito::PackError" do codec = Paquito::CodecFactory.build([]) assert_raises(Paquito::PackError) do codec.dump(Time.now) end end test "rejects undeclared types with serializable_type option" do codec = Paquito::CodecFactory.build([], serializable_type: true) undeclared_type = Class.new(Object) do def to_msgpack(_) end end object = undeclared_type.new assert_raises(Paquito::PackError) { codec.dump(object) } end test "serializes any object defining Object#as_pack and Object.from_pack with serializable_type option" do codec = Paquito::CodecFactory.build([Symbol], serializable_type: true) object = ObjectOne.new( "foo", { "bar" => ObjectTwo.new("baz", "qux") }, ) decoded = codec.load(codec.dump(object)) assert_equal object, decoded end test "handles class name changes by raising defined exception" do codec = Paquito::CodecFactory.build([Symbol], serializable_type: true) klass = ObjectOne object = ObjectOne.new("foo", "bar") serial = codec.dump(object) begin SharedCodecFactoryTests.send(:remove_const, :ObjectOne) assert_raises(Paquito::ClassMissingError) do codec.load(serial) end ensure SharedCodecFactoryTests.const_set(:ObjectOne, klass) unless SharedCodecFactoryTests.const_defined?(:ObjectOne) end end test "MessagePack errors are encapsulated" do error = assert_raises(Paquito::PackError) do @codec.dump(2**128) end assert_includes error.message, "RangeError, bignum too big to convert" payload = @codec.dump("foo") error = assert_raises(Paquito::UnpackError) do @codec.load(payload.byteslice(0..-2)) end assert_includes error.message, "EOFError, end of buffer reached" end if defined? MessagePack::Bigint test "bigint support" do @codec = Paquito::CodecFactory.build([Integer]) bigint = 2**150 assert_equal bigint, @codec.load(@codec.dump(bigint)) end end test "loading of V0 types is stable" do assert_equal(OBJECTS, @codec.load(V0_PAYLOAD)) end test "loading of V1 types is stable" do assert_equal(OBJECTS, @codec.load(V1_PAYLOAD)) end end end class CodecFactoryV0Test < PaquitoTest include SharedCodecFactoryTests def setup @codec = Paquito::CodecFactory.build([Symbol, Time, DateTime, Date, BigDecimal], pool: 1, format_version: 0) end test "issue#26 version 0 Time serializer may break if denominator is too big" do time = Time.at(Rational(1, 2**33)) assert_raises Paquito::PackError do @codec.dump(time) end assert_raises Paquito::UnpackError do @codec.load("\xC7\f\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00") end end test "dumping of V0 types is stable" do assert_equal(V0_PAYLOAD, @codec.dump(OBJECTS)) end end class CodecFactoryV1Test < PaquitoTest include SharedCodecFactoryTests def setup @codec = Paquito::CodecFactory.build([Symbol, Time, DateTime, Date, BigDecimal], pool: 1, format_version: 1) end test "preserve Time#zone" do with_env("TZ", "EST") do now = Time.now assert_equal "EST", now.zone time_state = now.inspect time_copy = @codec.load(@codec.dump(now)) assert_equal time_state, time_copy.inspect skip("Time#zone can't be restored https://bugs.ruby-lang.org/issues/19253") assert_equal "EST", time_copy.zone end end test "dumping of V1 types is stable" do assert_equal(V1_PAYLOAD, @codec.dump(OBJECTS)) end end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/test/vanilla/single_byte_prefix_version_with_string_bypass_test.rb
test/vanilla/single_byte_prefix_version_with_string_bypass_test.rb
# frozen_string_literal: true require "test_helper" class PaquitoSingleBytePrefixVersionWithStringBypassTest < PaquitoTest def setup @coder = Paquito::SingleBytePrefixVersionWithStringBypass.new( 1, { 0 => YAML, 1 => JSON, 2 => MessagePack }, ) end test "#dump use the current version" do assert_equal "\x01{\"foo\":42}".b, @coder.dump({ foo: 42 }) end test "#load respects the version prefix" do assert_equal({ foo: 42 }, @coder.load("\x00---\n:foo: 42")) end test "#load raises an error on unknown versions" do error = assert_raises(Paquito::UnsupportedCodec) do @coder.load("#{42.chr}blahblah") end assert_equal "Unsupported packer version 42", error.message end test "#load preserve string encoding" do utf8_str = "a" * 200 assert_equal Encoding::UTF_8, utf8_str.encoding roundtrip = @coder.load(@coder.dump(utf8_str)) assert_equal utf8_str, roundtrip assert_equal Encoding::UTF_8, roundtrip.encoding binary_str = Random.bytes(200) assert_equal Encoding::BINARY, binary_str.encoding roundtrip = @coder.load(@coder.dump(binary_str)) assert_equal binary_str, roundtrip assert_equal Encoding::BINARY, binary_str.encoding ascii_str = ("a" * 200).force_encoding(Encoding::US_ASCII) assert_equal Encoding::US_ASCII, ascii_str.encoding roundtrip = @coder.load(@coder.dump(ascii_str)) assert_equal ascii_str, roundtrip assert_equal Encoding::US_ASCII, ascii_str.encoding end test "supports multi-byte UTF-8" do utf8_str = "本" roundtrip = @coder.load(@coder.dump(utf8_str)) assert_equal utf8_str, roundtrip end test "UTF8 version prefix is stable" do assert_equal "#{255.chr}foo", @coder.dump("foo") end test "BINARY version prefix is stable" do assert_equal "#{254.chr}foo", @coder.dump("foo".b) end test "ASCII version prefix is stable" do assert_equal "#{253.chr}foo", @coder.dump("foo".encode(Encoding::ASCII)) end test "with a string_coder" do @coder_with_compression = Paquito::SingleBytePrefixVersionWithStringBypass.new( 1, { 0 => YAML, 1 => JSON, 2 => MessagePack }, Paquito::ConditionalCompressor.new(Zlib, 5), ) assert_equal "#{255.chr}#{0.chr}foo".b, @coder_with_compression.dump("foo") str = "AAAAAAAAAAAA" assert_equal "#{255.chr}#{1.chr}#{Zlib.deflate(str)}".b, @coder_with_compression.dump(str) end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/test/vanilla/struct_test.rb
test/vanilla/struct_test.rb
# frozen_string_literal: true require "test_helper" class PaquitoStructTest < PaquitoTest FooStruct = Paquito::Struct.new(:foo, :bar) BarStruct = Paquito::Struct.new(:foo, :bar, keyword_init: true) BazStruct = Paquito::Struct.new(:baz, keyword_init: true) test "with keyword_init: false" do digest = pack_digest(FooStruct) assert_equal FooStruct.new("foo", "bar"), FooStruct.from_pack([digest, "foo", "bar"]) instance = FooStruct.new("baz", "qux") assert_equal [digest, "baz", "qux"], instance.as_pack end test "with keyword_init: true" do digest = pack_digest(BarStruct) assert_equal BarStruct.new(foo: "foo", bar: "bar"), BarStruct.from_pack([digest, "foo", "bar"]) instance = BarStruct.new(foo: "baz", bar: "qux") assert_equal [digest, "baz", "qux"], instance.as_pack end test "raises VersionMismatchError when version does not match payload" do digest = pack_digest(BazStruct) BazStruct.from_pack([digest, ["foo"]]) # nothing raised assert_raises(Paquito::VersionMismatchError) do BazStruct.from_pack([123, ["foo"]]) end end test "accepts block argument" do struct = Paquito::Struct.new(:foo) do def bar "bar" end end instance = struct.new("foo") assert_equal "foo", instance.foo assert_equal "bar", instance.bar end private def pack_digest(klass) Paquito::Struct.digest(klass.members) end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/test/vanilla/translate_errors_test.rb
test/vanilla/translate_errors_test.rb
# frozen_string_literal: true require "test_helper" class TranslateErrorsTest < PaquitoTest def setup @coder = Paquito::TranslateErrors.new(Marshal) end test "#load translate any error to Paquito::UnpackError" do assert_raises Paquito::UnpackError do @coder.load("\x00") end end test "#dump translate any error to Paquito::PackError" do assert_raises Paquito::PackError do @coder.dump(-> {}) end end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/test/vanilla/typed_struct_test.rb
test/vanilla/typed_struct_test.rb
# frozen_string_literal: true require "test_helper" class PaquitoTypedStructTest < PaquitoTest class FooStruct < T::Struct include Paquito::TypedStruct prop :foo, String prop :bar, Integer end test "#as_pack returns array of digest and struct values" do digest = pack_digest(FooStruct) assert_equal [digest, "foo", 1], FooStruct.new(foo: "foo", bar: 1).as_pack end test ".from_pack returns object from array of digest and struct values" do digest = pack_digest(FooStruct) unpacked = FooStruct.from_pack([digest, "foo", 1]) assert_instance_of FooStruct, unpacked assert_equal "foo", unpacked.foo assert_equal 1, unpacked.bar end test ".from_pack raises VersionMismatchError when version does not match payload" do digest = pack_digest(FooStruct) FooStruct.from_pack([digest, "foo", 1]) assert_raises(Paquito::VersionMismatchError) do FooStruct.from_pack([123, "foo", 1]) end end private def pack_digest(klass) Paquito::Struct.digest(klass.props.keys) end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/test/vanilla/test_helper.rb
test/vanilla/test_helper.rb
# frozen_string_literal: true require File.expand_path("../test_helper.rb", __dir__) Dir[File.expand_path("support/*.rb", __dir__)].sort.each do |support| require support end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/test/vanilla/allow_nil_test.rb
test/vanilla/allow_nil_test.rb
# frozen_string_literal: true require "test_helper" class AllowNilTest < PaquitoTest def setup @coder = Paquito.allow_nil(Marshal) end test "#load returns nil if passed nil" do assert_nil @coder.load(nil) end test "#dump returns nil if passed nil" do assert_nil @coder.dump(nil) end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/test/activesupport/cache_entry_coder_test.rb
test/activesupport/cache_entry_coder_test.rb
# frozen_string_literal: true require "test_helper" class PaquitoCacheEntryCoderTest < PaquitoTest def setup @coder = Paquito.chain( Paquito::CacheEntryCoder, JSON, ) @cache_dir = Dir.mktmpdir @store = ActiveSupport::Cache::FileStore.new(@cache_dir, coder: @coder) end def test_simple_key @store.write("foo", "bar") assert_equal(["bar"].to_json, raw_cache_read("foo")) end def test_simple_key_with_expriry @store.write("foo", "bar", expires_in: 5.minutes) value, expiry = JSON.parse(raw_cache_read("foo")) assert_equal("bar", value) assert_instance_of(Float, expiry) end def test_simple_key_with_version @store.write("foo", "bar", version: "v1") value, expiry, version = JSON.parse(raw_cache_read("foo")) assert_equal("bar", value) assert_nil(expiry) assert_equal("v1", version) end private def raw_cache_read(key) File.read(Dir[File.join(@cache_dir, "**", key)].first) end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/test/activesupport/codec_factory_test.rb
test/activesupport/codec_factory_test.rb
# frozen_string_literal: true require "test_helper" module Paquito module ActiveSupportSharedCodecFactoryTests OBJECTS = { hwia: ActiveSupport::HashWithIndifferentAccess.new("foo" => "bar"), time_with_zone: ActiveSupport::TimeWithZone.new( Time.new(2000, 1, 1, 2, 2, 2, "UTC"), ActiveSupport::TimeZone["Japan"], ), } TYPES = [Symbol, ActiveSupport::HashWithIndifferentAccess, ActiveSupport::TimeWithZone].freeze V0_PAYLOAD = "\x82\xD6\x00hwia\xC7\t\a\x81\xA3foo\xA3bar\xC7\x0E\x00" \ "time_with_zone\xC7\x11\b\x1A`m8\x00\x00\x00\x00\x00\x00\x00\x00Japan".b.freeze V1_PAYLOAD = "\x82\xD6\x00hwia\xC7\t\a\x81\xA3foo\xA3bar\xC7\x0E\x00" \ "time_with_zone\xC7\f\r\xCE8m`\x1A\x00\xA5Japan".b.freeze def self.included(base = nil, &block) if base && !block_given? base.class_eval(&@included) elsif base.nil? && block_given? @included = block else raise "Can't pass both a base and and block" end end included do test "correctly supports ActiveSupport::HashWithIndifferentAccess objects" do hash = { 1 => ActiveSupport::HashWithIndifferentAccess.new("foo" => "bar") } decoded_hash = @codec.load(@codec.dump(hash)) assert_equal Hash, decoded_hash.class assert_equal ActiveSupport::HashWithIndifferentAccess, decoded_hash[1].class assert_equal hash, decoded_hash assert_equal "bar", decoded_hash[1][:foo] end test "does not support ActiveSupport::HashWithIndifferentAccess subclasses" do hwia_subclass = Class.new(ActiveSupport::HashWithIndifferentAccess) object = hwia_subclass.new assert_raises(Paquito::PackError) { @codec.dump(object) } end test "loading of V0 types is stable" do assert_equal(OBJECTS, @codec.load(V0_PAYLOAD)) end test "loading of V1 types is stable" do assert_equal(OBJECTS, @codec.load(V1_PAYLOAD)) end end end class ActiveSupportCodecFactoryV0Test < PaquitoTest include ActiveSupportSharedCodecFactoryTests def setup @codec = Paquito::CodecFactory.build(TYPES, format_version: 0) end test "dumping of V0 types is stable" do assert_equal(V0_PAYLOAD, @codec.dump(OBJECTS)) end test "correctly encodes ActiveSupport::TimeWithZone objects" do utc_time = Time.utc(2000, 1, 1, 0, 0, 0, 0.5) time_zone = ActiveSupport::TimeZone["Japan"] with_env("TZ", "America/Los_Angeles") do value = ActiveSupport::TimeWithZone.new(utc_time, time_zone) encoded_value = @codec.dump(value) assert_equal("\xC7\x11\b\x80Cm8\x00\x00\x00\x00\xF4\x01\x00\x00Japan".b, encoded_value) decoded_value = @codec.load(encoded_value) assert_instance_of(ActiveSupport::TimeWithZone, decoded_value) assert_equal(utc_time, decoded_value.utc) assert_equal("JST", decoded_value.zone) assert_equal(500, decoded_value.nsec) assert_instance_of(Time, decoded_value.utc) assert_equal(value, decoded_value) end end end class ActiveSupportCodecFactoryV1Test < PaquitoTest include ActiveSupportSharedCodecFactoryTests def setup @codec = Paquito::CodecFactory.build(TYPES, format_version: 1) end test "dumping of V1 types is stable" do assert_equal(V1_PAYLOAD, @codec.dump(OBJECTS)) end test "correctly encodes ActiveSupport::TimeWithZone objects" do utc_time = Time.utc(2000, 1, 1, 0, 0, 0, 0.5) time_zone = ActiveSupport::TimeZone["Japan"] with_env("TZ", "America/Los_Angeles") do value = ActiveSupport::TimeWithZone.new(utc_time, time_zone) encoded_value = @codec.dump(value) assert_equal("\xC7\x0E\r\xCE8mC\x80\xCD\x01\xF4\xA5Japan".b, encoded_value) decoded_value = @codec.load(encoded_value) assert_instance_of(ActiveSupport::TimeWithZone, decoded_value) assert_equal(utc_time, decoded_value.utc) assert_equal("JST", decoded_value.zone) assert_equal(500, decoded_value.nsec) assert_instance_of(Time, decoded_value.utc) assert_equal(value, decoded_value) end end end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/test/activesupport/test_helper.rb
test/activesupport/test_helper.rb
# frozen_string_literal: true require "active_support/all" require File.expand_path("../test_helper.rb", __dir__) Dir[File.expand_path("support/*.rb", __dir__)].sort.each do |support| require support end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/test/activesupport/flat_cache_entry_coder_test.rb
test/activesupport/flat_cache_entry_coder_test.rb
# frozen_string_literal: true require "test_helper" class FlatPaquitoCacheEntryCoderTest < PaquitoTest def setup @coder = Paquito::FlatCacheEntryCoder.new(JSON) @cache_dir = Dir.mktmpdir @store = ActiveSupport::Cache::FileStore.new(@cache_dir, coder: @coder) end def test_simple_key @store.write("foo", "bar") assert_equal("bar", @store.read("foo")) entry = read_entry("foo") assert_nil(entry.expires_at) assert_nil(entry.version) end def test_simple_key_with_expriry @store.write("foo", "bar", expires_in: 5.minutes) assert_equal("bar", @store.read("foo")) entry = read_entry("foo") assert_in_delta(5.minutes.from_now.to_f, entry.expires_at, 0.5) assert_nil(entry.version) end def test_simple_key_with_version @store.write("foo", "bar", version: "v1") assert_equal("bar", @store.read("foo")) entry = read_entry("foo") assert_nil(entry.expires_at) assert_equal("v1", entry.version) end private def read_entry(key) @store.send(:read_entry, @store.send(:normalize_key, key, {})) end def raw_cache_read(key) File.read(Dir[File.join(@cache_dir, "**", key)].first) end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/lib/paquito.rb
lib/paquito.rb
# frozen_string_literal: true require "digest/md5" require "bigdecimal" require "date" require "set" require "yaml" require "msgpack" require "paquito/version" require "paquito/deflater" require "paquito/compressor" require "paquito/allow_nil" require "paquito/translate_errors" require "paquito/safe_yaml" require "paquito/conditional_compressor" require "paquito/single_byte_prefix_version" require "paquito/single_byte_prefix_version_with_string_bypass" require "paquito/comment_prefix_version" require "paquito/types" require "paquito/codec_factory" require "paquito/struct" require "paquito/typed_struct" require "paquito/serialized_column" module Paquito autoload :CacheEntryCoder, "paquito/cache_entry_coder" autoload :FlatCacheEntryCoder, "paquito/flat_cache_entry_coder" autoload :ActiveRecordCoder, "paquito/active_record_coder" DEFAULT_FORMAT_VERSION = 1 @format_version = DEFAULT_FORMAT_VERSION class << self attr_accessor :format_version def cast(coder) if coder.respond_to?(:load) && coder.respond_to?(:dump) coder elsif coder.respond_to?(:deflate) && coder.respond_to?(:inflate) Deflater.new(coder) elsif coder.respond_to?(:compress) && coder.respond_to?(:decompress) Compressor.new(coder) else raise TypeError, "Coders must respond to #dump and #load, #{coder.inspect} doesn't" end end def chain(*coders) CoderChain.new(*coders) end def allow_nil(coder) AllowNil.new(coder) end end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/lib/paquito/active_record_coder.rb
lib/paquito/active_record_coder.rb
# frozen_string_literal: true gem "activerecord", ">= 7.0" require "paquito/errors" module Paquito class ActiveRecordCoder EMPTY_HASH = {}.freeze class << self def dump(record) instances = InstanceTracker.new serialized_associations = serialize_associations(record, instances) serialized_records = instances.map { |r| serialize_record(r) } [serialized_associations, *serialized_records] end def load(payload) instances = InstanceTracker.new serialized_associations, *serialized_records = payload serialized_records.each { |attrs| instances.push(deserialize_record(*attrs)) } deserialize_associations(serialized_associations, instances) end private # Records without associations, or which have already been visited before, # are serialized by their id alone. # # Records with associations are serialized as a two-element array including # their id and the record's association cache. # def serialize_associations(record, instances) return unless record if (id = instances.lookup(record)) payload = id else payload = instances.push(record) cached_associations = record.class.reflect_on_all_associations.select do |reflection| record.association_cached?(reflection.name) end unless cached_associations.empty? serialized_associations = cached_associations.map do |reflection| association = record.association(reflection.name) serialized_target = if reflection.collection? association.target.map { |target_record| serialize_associations(target_record, instances) } else serialize_associations(association.target, instances) end [reflection.name, serialized_target] end payload = [payload, serialized_associations] end end payload end def deserialize_associations(payload, instances) return unless payload id, associations = payload record = instances.fetch(id) associations&.each do |name, serialized_target| begin association = record.association(name) rescue ActiveRecord::AssociationNotFoundError raise AssociationMissingError, "undefined association: #{name}" end target = if association.reflection.collection? serialized_target.map! { |serialized_record| deserialize_associations(serialized_record, instances) } else deserialize_associations(serialized_target, instances) end association.target = target end record end def serialize_record(record) [ record.class.name, attributes_for_database(record), record.new_record?, columns_digest(record.class), ] end def attributes_for_database(record) attributes = record.attributes_for_database attributes.transform_values! { |attr| attr.is_a?(::ActiveModel::Type::Binary::Data) ? attr.to_s : attr } attributes end def deserialize_record(class_name, attributes_from_database, new_record = false, hash = nil, *) begin klass = Object.const_get(class_name) rescue NameError raise ClassMissingError, "undefined class: #{class_name}" end if hash && (hash != (expected_digest = columns_digest(klass))) raise ColumnsDigestMismatch, "\"#{hash}\" does not match the expected digest of \"#{expected_digest}\"" end # Ideally we'd like to call `klass.instantiate`, however it doesn't allow to pass # wether the record was persisted or not. attributes = klass.attributes_builder.build_from_database(attributes_from_database, EMPTY_HASH) klass.allocate.init_with_attributes(attributes, new_record) end def columns_digest(klass) str = klass.columns_hash.map { |name, column| [name, column.sql_type].join(":") }.join(",") ::Digest::MD5.digest(str).unpack1("s") end end class Error < ::Paquito::Error end class ClassMissingError < Error end class AssociationMissingError < Error end class ColumnsDigestMismatch < Error end class InstanceTracker def initialize @instances = [] @ids = {}.compare_by_identity end def map(&block) @instances.map(&block) end def fetch(*args, &block) @instances.fetch(*args, &block) end ruby2_keywords :fetch if respond_to?(:ruby2_keywords, true) def push(instance) id = @ids[instance] = @instances.size @instances << instance id end def lookup(instance) @ids[instance] end end end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/lib/paquito/version.rb
lib/paquito/version.rb
# frozen_string_literal: true module Paquito VERSION = "1.0.0" end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/lib/paquito/typed_struct.rb
lib/paquito/typed_struct.rb
# typed: true # frozen_string_literal: true return unless defined?(T::Props) module Paquito # To make a T::Struct class serializable, include Paquito::TypedStruct: # # class MyStruct < T::Struct # include Paquito::TypedStruct # # prop :foo, String # prop :bar, Integer # end # # my_struct = MyStruct.new(foo: "foo", bar: 1) # my_struct.as_pack # => [26450, "foo", 1] # # MyStruct.from_pack([26450, "foo", 1]) # => <MyStruct bar=1, foo="foo"> # module TypedStruct extend T::Sig include T::Props::Plugin sig { returns(Array).checked(:never) } def as_pack decorator = self.class.decorator props = decorator.props.keys values = props.map { |prop| decorator.get(self, prop) } [self.class.pack_digest, *values] end module ClassMethods extend T::Sig sig { params(packed: Array).returns(T.untyped).checked(:never) } def from_pack(packed) digest, *values = packed if pack_digest != digest raise(VersionMismatchError, "#{self} digests do not match") end new(**props.keys.zip(values).to_h) end sig { returns(Integer).checked(:never) } def pack_digest @pack_digest ||= Paquito::Struct.digest(props.keys) end end end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/lib/paquito/codec_factory.rb
lib/paquito/codec_factory.rb
# frozen_string_literal: true require "paquito/types" require "paquito/coder_chain" module Paquito class CodecFactory def self.build(types = [], freeze: false, serializable_type: false, pool: 1, format_version: Paquito.format_version) factory = if types.empty? && !serializable_type MessagePack::DefaultFactory else MessagePack::Factory.new end Types.register(factory, types, format_version: format_version) unless types.empty? Types.register_serializable_type(factory) if serializable_type if pool && pool > 0 && factory.respond_to?(:pool) factory = factory.freeze.pool(pool, freeze: freeze) freeze = false end MessagePackCodec.new(factory, freeze: freeze) end class MessagePackCodec def initialize(factory, freeze: false) @factory = factory @freeze = freeze end def dump(object) @factory.dump(object) rescue NoMethodError => error raise PackError.new(error.message, error.receiver) rescue RangeError => error raise PackError, "#{error.class.name}, #{error.message}" end def load(payload) if @freeze @factory.load(payload, freeze: @freeze) else @factory.load(payload) end rescue MessagePack::UnpackError => error raise UnpackError, error.message rescue IOError => error raise UnpackError, "#{error.class.name}, #{error.message}" end end end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/lib/paquito/coder_chain.rb
lib/paquito/coder_chain.rb
# frozen_string_literal: true module Paquito class CoderChain def initialize(*coders) @coders = coders.flatten.map { |c| Paquito.cast(c) } @reverse_coders = @coders.reverse end def dump(object) payload = object @coders.each { |c| payload = c.dump(payload) } payload end def load(payload) object = payload @reverse_coders.each { |c| object = c.load(object) } object end end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/lib/paquito/struct.rb
lib/paquito/struct.rb
# frozen_string_literal: true require "paquito/errors" module Paquito # To make a Struct class cacheable, include Paquito::Struct: # # MyStruct = Struct.new(:foo, :bar) # MyStruct.include(Paquito::Struct) # # Alternatively, declare the struct with Paquito::Struct#new: # # MyStruct = Paquito::Struct.new(:foo, :bar) # # The struct defines #as_pack and .from_pack methods: # # my_struct = MyStruct.new("foo", "bar") # my_struct.as_pack # => [26450, "foo", "bar"] # # MyStruct.from_pack([26450, "foo", "bar"]) # => #<struct FooStruct foo="foo", bar="bar"> # # The Paquito::Struct module can be used in non-Struct classes, so long # as the class: # # - defines a #values instance method # - defines a .members class method # - has an #initialize method that accepts the values as its arguments # # If the last condition is _not_ met, you can override .from_pack on the # class and initialize the instance however you like, optionally using the # private extract_packed_values method to extract values from the payload. # module Struct class << self def included(base) base.class_eval do @__kw_init__ = inspect.include?("keyword_init: true") end base.extend(ClassMethods) end end def as_pack [self.class.pack_digest, *values] end class << self def new(*members, keyword_init: false, &block) struct = ::Struct.new(*members, keyword_init: keyword_init, &block) struct.include(Paquito::Struct) struct end def digest(attr_names) ::Digest::MD5.digest(attr_names.map(&:to_s).join(",")).unpack1("s") end end module ClassMethods def from_pack(packed) values = extract_packed_values(packed, as_hash: @__kw_init__) if @__kw_init__ new(**values) else new(*values) end end def pack_digest @pack_digest ||= ::Paquito::Struct.digest(members) end private def extract_packed_values(packed, as_hash:) digest, *values = packed if pack_digest != digest raise(VersionMismatchError, "#{self} digests do not match") end as_hash ? members.zip(values).to_h : values end end end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/lib/paquito/errors.rb
lib/paquito/errors.rb
# frozen_string_literal: true module Paquito Error = Class.new(StandardError) class PackError < Error attr_reader :receiver def initialize(msg, receiver = nil) super(msg) @receiver = receiver end end UnpackError = Class.new(Error) ClassMissingError = Class.new(Error) UnsupportedType = Class.new(Error) UnsupportedCodec = Class.new(Error) VersionMismatchError = Class.new(Error) end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/lib/paquito/cache_entry_coder.rb
lib/paquito/cache_entry_coder.rb
# frozen_string_literal: true gem "activesupport", ">= 7.0" module Paquito module CacheEntryCoder def self.dump(entry) entry.pack end def self.load(payload) ::ActiveSupport::Cache::Entry.unpack(payload) end end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/lib/paquito/comment_prefix_version.rb
lib/paquito/comment_prefix_version.rb
# frozen_string_literal: true module Paquito class CommentPrefixVersion PREFIX = "#\u2620" SUFFIX = "\u2622\n" VERSION_POSITION = PREFIX.bytesize HEADER_SLICE = (0..(PREFIX.bytesize + SUFFIX.bytesize)) PAYLOAD_SLICE = (PREFIX.bytesize + 1 + SUFFIX.bytesize)..-1 DEFAULT_VERSION = 0 def initialize(current_version, coders) unless (0..9).cover?(current_version) && coders.keys.all? { |version| (0..9).cover?(version) } raise ArgumentError, "CommentPrefixVersion versions must be between 0 and 9" end @current_version = current_version @coders = coders.transform_values { |c| Paquito.cast(c) }.freeze @current_coder = coders.fetch(current_version) end def dump(object) prefix = +"#{PREFIX}#{@current_version}#{SUFFIX}" payload = @current_coder.dump(object) if payload.encoding == Encoding::BINARY prefix.b << payload else prefix << payload end end def load(payload) payload_version, serial = extract_version(payload) coder = @coders.fetch(payload_version) do raise UnsupportedCodec, "Unsupported packer version #{payload_version}" end coder.load(serial) end private def extract_version(serial) header = serial.byteslice(HEADER_SLICE)&.force_encoding(Encoding::UTF_8) unless header.start_with?(PREFIX) && header.end_with?(SUFFIX) return [DEFAULT_VERSION, serial] end version = header.getbyte(VERSION_POSITION) - 48 # ASCII byte to number [version, serial.byteslice(PAYLOAD_SLICE) || ""] end end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/lib/paquito/conditional_compressor.rb
lib/paquito/conditional_compressor.rb
# frozen_string_literal: true module Paquito class ConditionalCompressor UNCOMPRESSED = 0 COMPRESSED = 1 def initialize(compressor, compress_threshold) @compressor = Paquito.cast(compressor) @compress_threshold = compress_threshold end def dump(uncompressed) uncompressed_size = uncompressed.bytesize version = UNCOMPRESSED value = uncompressed if @compress_threshold && uncompressed_size > @compress_threshold compressed = @compressor.dump(uncompressed) if compressed.bytesize < uncompressed_size version = COMPRESSED value = compressed end end version.chr(Encoding::BINARY) << value end def load(payload) payload_version = payload.getbyte(0) data = payload.byteslice(1..-1) case payload_version when UNCOMPRESSED data when COMPRESSED @compressor.load(data) else raise UnpackError, "invalid ConditionalCompressor version" end end end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/lib/paquito/serialized_column.rb
lib/paquito/serialized_column.rb
# frozen_string_literal: true module Paquito class SerializedColumn def initialize(coder, type = nil, attribute_name: nil) @coder = coder @type = type @attribute_name = attribute_name || "Attribute" check_arity_of_constructor @default_value = type&.new end def object_class @type || Object end def load(payload) return @type&.new if payload.nil? object = @coder.load(payload) check_type(object) object || @type&.new end def dump(object) return if object.nil? || object == @default_value check_type(object) @coder.dump(object) end private def check_arity_of_constructor load(nil) rescue ArgumentError raise ArgumentError, "Cannot serialize #{object_class}. Classes passed to `serialize` must have a 0 argument constructor." end def default_value?(object) object == @type&.new end def check_type(object) unless @type.nil? || object.is_a?(@type) || object.nil? raise ActiveRecord::SerializationTypeMismatch, "#{@attribute_name} was supposed to be a #{object_class}, " \ "but was a #{object.class}. -- #{object.inspect}" end end end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/lib/paquito/single_byte_prefix_version_with_string_bypass.rb
lib/paquito/single_byte_prefix_version_with_string_bypass.rb
# frozen_string_literal: true module Paquito class SingleBytePrefixVersionWithStringBypass < SingleBytePrefixVersion UTF8_VERSION = 255 BINARY_VERSION = 254 ASCII_VERSION = 253 def initialize(current_version, coders, string_coder = nil) super(current_version, coders) @string_coder = string_coder end def dump(object) if object.class == String # We don't want to match subclasses case object.encoding when Encoding::UTF_8 UTF8_VERSION.chr(Encoding::BINARY) << (@string_coder ? @string_coder.dump(object) : object.b) when Encoding::BINARY BINARY_VERSION.chr(Encoding::BINARY) << (@string_coder ? @string_coder.dump(object) : object) when Encoding::US_ASCII ASCII_VERSION.chr(Encoding::BINARY) << (@string_coder ? @string_coder.dump(object) : object) else super end else super end end def load(payload) payload_version = payload.getbyte(0) unless payload_version raise UnsupportedCodec, "Missing version byte." end case payload_version when UTF8_VERSION string = payload.byteslice(1..-1).force_encoding(Encoding::UTF_8) @string_coder ? @string_coder.load(string) : string when BINARY_VERSION string = payload.byteslice(1..-1).force_encoding(Encoding::BINARY) @string_coder ? @string_coder.load(string) : string when ASCII_VERSION string = payload.byteslice(1..-1).force_encoding(Encoding::US_ASCII) @string_coder ? @string_coder.load(string) : string else coder = @coders.fetch(payload_version) do raise UnsupportedCodec, "Unsupported packer version #{payload_version}" end coder.load(payload.byteslice(1..-1)) end end private def validate_version(version) unless (0..252).cover?(version) raise ArgumentError, "Invalid version #{version.inspect}, versions must be an integer between 0 and 252" end version end end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/lib/paquito/allow_nil.rb
lib/paquito/allow_nil.rb
# frozen_string_literal: true module Paquito class AllowNil def initialize(coder) @coder = Paquito.cast(coder) end def dump(object) return nil if object.nil? @coder.dump(object) end def load(payload) return nil if payload.nil? @coder.load(payload) end end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/lib/paquito/deflater.rb
lib/paquito/deflater.rb
# frozen_string_literal: true module Paquito class Deflater def initialize(deflater) @deflater = deflater end def dump(serial) @deflater.deflate(serial) end def load(payload) @deflater.inflate(payload) end end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/lib/paquito/safe_yaml.rb
lib/paquito/safe_yaml.rb
# frozen_string_literal: true module Paquito class SafeYAML ALL_SYMBOLS = [].freeze # Restricting symbols isn't really useful since symbols are no longer immortal BASE_PERMITTED_CLASSNAMES = [ "TrueClass", "FalseClass", "NilClass", "Numeric", "String", "Array", "Hash", "Integer", "Float", ].freeze def initialize(permitted_classes: [], deprecated_classes: [], aliases: false) permitted_classes += BASE_PERMITTED_CLASSNAMES @dumpable_classes = permitted_classes @loadable_classes = permitted_classes + deprecated_classes @aliases = aliases @dump_options = { permitted_classes: permitted_classes, permitted_symbols: ALL_SYMBOLS, aliases: true, line_width: -1, # Disable YAML line-wrapping because it causes extremely obscure issues. }.freeze end def load(serial) Psych.safe_load( serial, permitted_classes: @loadable_classes, permitted_symbols: ALL_SYMBOLS, aliases: @aliases, ) rescue Psych::DisallowedClass => psych_error raise UnsupportedType, psych_error.message rescue Psych::Exception => psych_error raise UnpackError, psych_error.message end def dump(obj) visitor = RestrictedYAMLTree.create(@dump_options) visitor << obj visitor.tree.yaml(nil, @dump_options) rescue Psych::Exception => psych_error raise PackError, psych_error.message end class RestrictedYAMLTree < Psych::Visitors::YAMLTree class DispatchCache def initialize(visitor, cache) @visitor = visitor @cache = cache end def [](klass) @cache[klass] if @visitor.permitted_class?(klass) end end def initialize(*) super @permitted_classes = Set.new(@options[:permitted_classes]) @dispatch_cache = DispatchCache.new(self, @dispatch_cache) @permitted_cache = Hash.new do |h, klass| unless @permitted_classes.include?(klass.name) raise UnsupportedType, "Tried to dump unspecified class: #{klass.name.inspect}" end h[klass] = true end.compare_by_identity end ruby2_keywords :initialize if respond_to?(:ruby2_keywords, true) def dump_coder(target) return unless permitted_class?(target.class) super end def permitted_class?(klass) @permitted_cache[klass] end end end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/lib/paquito/types.rb
lib/paquito/types.rb
# frozen_string_literal: true require "paquito/errors" begin require "active_support" require "active_support/core_ext/time/calculations" rescue LoadError # We don't actually depend on ActiveSupport, we just want to use # Time.at_without_coercion if it's available. Otherwise, we'll just use # Time.at and ignore this error. end module Paquito module Types autoload :ActiveRecordPacker, "paquito/types/active_record_packer" # Do not change those formats, this would break current codecs. TIME_FORMAT = "q< L<" TIME_WITH_ZONE_FORMAT = "q< L< a*" DATE_TIME_FORMAT = "s< C C C C q< L< c C" DATE_FORMAT = "s< C C" MAX_UINT32 = (2**32) - 1 MAX_INT64 = (2**63) - 1 SERIALIZE_METHOD = :as_pack SERIALIZE_PROC = SERIALIZE_METHOD.to_proc DESERIALIZE_METHOD = :from_pack class CustomTypesRegistry class << self def packer(value) packers.fetch(klass = value.class) do if packable?(value) && unpackable?(klass) @packers[klass] = SERIALIZE_PROC end end end def unpacker(klass) unpackers.fetch(klass) do if unpackable?(klass) @unpackers[klass] = klass.method(DESERIALIZE_METHOD).to_proc end end end def register(klass, packer: nil, unpacker:) if packer raise ArgumentError, "packer for #{klass} already defined" if packers.key?(klass) packers[klass] = packer end raise ArgumentError, "unpacker for #{klass} already defined" if unpackers.key?(klass) unpackers[klass] = unpacker self end private def packable?(value) value.class.method_defined?(SERIALIZE_METHOD) || raise(PackError.new("#{value.class} is not serializable", value)) end def unpackable?(klass) klass.respond_to?(DESERIALIZE_METHOD) || raise(UnpackError, "#{klass} is not deserializable") end def packers @packers ||= {} end def unpackers @unpackers ||= {} end end end # Do not change any #code, this would break current codecs. # New types can be added as long as they have unique #code. class << self def time_pack_deprecated(value) rational = value.to_r if rational.numerator > MAX_INT64 || rational.denominator > MAX_UINT32 raise PackError, "Time instance out of bounds (#{rational.inspect}), see: https://github.com/Shopify/paquito/issues/26" end [rational.numerator, rational.denominator].pack(TIME_FORMAT) end def time_unpack_deprecated(payload) numerator, denominator = payload.unpack(TIME_FORMAT) at = begin Rational(numerator, denominator) rescue ZeroDivisionError raise UnpackError, "Corrupted Time object, see: https://github.com/Shopify/paquito/issues/26" end Time.at(at).utc end def datetime_pack_deprecated(value) sec = value.sec + value.sec_fraction offset = value.offset if sec.numerator > MAX_INT64 || sec.denominator > MAX_UINT32 raise PackError, "DateTime#sec_fraction out of bounds (#{sec.inspect}), see: https://github.com/Shopify/paquito/issues/26" end if offset.numerator > MAX_INT64 || offset.denominator > MAX_UINT32 raise PackError, "DateTime#offset out of bounds (#{offset.inspect}), see: https://github.com/Shopify/paquito/issues/26" end [ value.year, value.month, value.day, value.hour, value.minute, sec.numerator, sec.denominator, offset.numerator, offset.denominator, ].pack(DATE_TIME_FORMAT) end def datetime_unpack_deprecated(payload) ( year, month, day, hour, minute, sec_numerator, sec_denominator, offset_numerator, offset_denominator, ) = payload.unpack(DATE_TIME_FORMAT) begin ::DateTime.new( year, month, day, hour, minute, Rational(sec_numerator, sec_denominator), Rational(offset_numerator, offset_denominator), ) rescue ZeroDivisionError raise UnpackError, "Corrupted DateTime object, see: https://github.com/Shopify/paquito/issues/26" end end def date_pack(value) [value.year, value.month, value.day].pack(DATE_FORMAT) end def date_unpack(payload) year, month, day = payload.unpack(DATE_FORMAT) ::Date.new(year, month, day) end def hash_with_indifferent_access_pack(value, packer) unless value.instance_of?(ActiveSupport::HashWithIndifferentAccess) raise PackError.new("cannot pack HashWithIndifferentClass subclass", value) end packer.write(value.to_h) end def hash_with_indifferent_access_unpack(unpacker) ActiveSupport::HashWithIndifferentAccess.new(unpacker.read) end def time_with_zone_deprecated_pack(value) [ value.utc.to_i, (value.time.sec_fraction * 1_000_000_000).to_i, value.time_zone.name, ].pack(TIME_WITH_ZONE_FORMAT) end def time_with_zone_deprecated_unpack(payload) sec, nsec, time_zone_name = payload.unpack(TIME_WITH_ZONE_FORMAT) time = Time.at(sec, nsec, :nsec, in: 0).utc time_zone = ::Time.find_zone(time_zone_name) ActiveSupport::TimeWithZone.new(time, time_zone) end def time_pack(value, packer) packer.write(value.tv_sec) packer.write(value.tv_nsec) packer.write(value.utc_offset) end if ::Time.respond_to?(:at_without_coercion) # Ref: https://github.com/rails/rails/pull/50268 def time_unpack(unpacker) ::Time.at_without_coercion(unpacker.read, unpacker.read, :nanosecond, in: unpacker.read) end else def time_unpack(unpacker) ::Time.at(unpacker.read, unpacker.read, :nanosecond, in: unpacker.read) end end def datetime_pack(value, packer) packer.write(value.year) packer.write(value.month) packer.write(value.day) packer.write(value.hour) packer.write(value.minute) sec = value.sec + value.sec_fraction packer.write(sec.numerator) packer.write(sec.denominator) offset = value.offset packer.write(offset.numerator) packer.write(offset.denominator) end def datetime_unpack(unpacker) ::DateTime.new( unpacker.read, # year unpacker.read, # month unpacker.read, # day unpacker.read, # hour unpacker.read, # minute Rational(unpacker.read, unpacker.read), # sec fraction Rational(unpacker.read, unpacker.read), # offset fraction ) end def time_with_zone_pack(value, packer) time = value.utc packer.write(time.tv_sec) packer.write(time.tv_nsec) packer.write(value.time_zone.name) end if ::Time.respond_to?(:at_without_coercion) # Ref: https://github.com/rails/rails/pull/50268 def time_with_zone_unpack(unpacker) utc = ::Time.at_without_coercion(unpacker.read, unpacker.read, :nanosecond, in: "UTC") time_zone = ::Time.find_zone(unpacker.read) ActiveSupport::TimeWithZone.new(utc, time_zone) end else def time_with_zone_unpack(unpacker) utc = ::Time.at(unpacker.read, unpacker.read, :nanosecond, in: "UTC") time_zone = ::Time.find_zone(unpacker.read) ActiveSupport::TimeWithZone.new(utc, time_zone) end end end TYPES = [ { code: 0, class: "Symbol", version: 0, packer: Symbol.method_defined?(:name) ? :name.to_proc : :to_s.to_proc, unpacker: :to_sym.to_proc, optimized_symbols_parsing: true, }.freeze, { code: 1, class: "Time", version: 0, packer: method(:time_pack_deprecated), unpacker: method(:time_unpack_deprecated), }.freeze, { code: 2, class: "DateTime", version: 0, packer: method(:datetime_pack_deprecated), unpacker: method(:datetime_unpack_deprecated), }.freeze, { code: 3, class: "Date", version: 0, packer: method(:date_pack), unpacker: method(:date_unpack), }.freeze, { code: 4, class: "BigDecimal", version: 0, packer: :_dump, unpacker: ::BigDecimal.method(:_load), }.freeze, # { code: 5, class: "Range" }, do not recycle that code { code: 6, class: "ActiveRecord::Base", version: 0, packer: ->(value) { ActiveRecordPacker.dump(value) }, unpacker: ->(value) { ActiveRecordPacker.load(value) }, }.freeze, { code: 7, class: "ActiveSupport::HashWithIndifferentAccess", version: 0, packer: method(:hash_with_indifferent_access_pack), unpacker: method(:hash_with_indifferent_access_unpack), recursive: true, }.freeze, { code: 8, class: "ActiveSupport::TimeWithZone", version: 0, packer: method(:time_with_zone_deprecated_pack), unpacker: method(:time_with_zone_deprecated_unpack), }.freeze, { code: 9, class: "Set", version: 0, packer: ->(value, packer) { packer.write(value.to_a) }, unpacker: ->(unpacker) { unpacker.read.to_set }, recursive: true, }.freeze, # { code: 10, class: "Integer" }, reserved for oversized Integer { code: 11, class: "Time", version: 1, recursive: true, packer: method(:time_pack), unpacker: method(:time_unpack), }.freeze, { code: 12, class: "DateTime", version: 1, recursive: true, packer: method(:datetime_pack), unpacker: method(:datetime_unpack), }.freeze, { code: 13, class: "ActiveSupport::TimeWithZone", version: 1, recursive: true, packer: method(:time_with_zone_pack), unpacker: method(:time_with_zone_unpack), }.freeze, # { code: 127, class: "Object" }, reserved for serializable Object type ] begin require "msgpack/bigint" TYPES << { code: 10, class: "Integer", version: 0, packer: MessagePack::Bigint.method(:to_msgpack_ext), unpacker: MessagePack::Bigint.method(:from_msgpack_ext), oversized_integer_extension: true, } rescue LoadError # expected on older msgpack end TYPES.freeze class << self def register(factory, types, format_version: Paquito.format_version) types.each do |type| # Up to Rails 7 ActiveSupport::TimeWithZone#name returns "Time" name = if defined?(ActiveSupport::TimeWithZone) && type == ActiveSupport::TimeWithZone "ActiveSupport::TimeWithZone" else type.name end matching_types = TYPES.select { |t| t[:class] == name } # If multiple types are registered for the same class, the last one will be used for # packing. So we sort all matching types so that the active one is registered last. past_types, future_types = matching_types.partition { |t| t.fetch(:version) <= format_version } if past_types.empty? raise KeyError, "No type found for #{name.inspect} with format_version=#{format_version}" end past_types.sort_by! { |t| t.fetch(:version) } (future_types + past_types).each do |type_attributes| factory.register_type( type_attributes.fetch(:code), type, type_attributes, ) end end end def register_serializable_type(factory) factory.register_type( 127, Object, packer: ->(value) do packer = CustomTypesRegistry.packer(value) class_name = value.class.to_s factory.dump([packer.call(value), class_name]) end, unpacker: ->(value) do payload, class_name = factory.load(value) begin klass = Object.const_get(class_name) rescue NameError raise ClassMissingError, "missing #{class_name} class" end unpacker = CustomTypesRegistry.unpacker(klass) unpacker.call(payload) end, ) end def define_custom_type(klass, packer: nil, unpacker:) CustomTypesRegistry.register(klass, packer: packer, unpacker: unpacker) end end end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/lib/paquito/single_byte_prefix_version.rb
lib/paquito/single_byte_prefix_version.rb
# frozen_string_literal: true module Paquito class SingleBytePrefixVersion def initialize(current_version, coders) @current_version = validate_version(current_version) @coders = coders.transform_keys { |v| validate_version(v) }.transform_values { |c| Paquito.cast(c) } @current_coder = coders.fetch(current_version) end def dump(object) @current_version.chr(Encoding::BINARY) << @current_coder.dump(object) end def load(payload) payload_version = payload.getbyte(0) unless payload_version raise UnsupportedCodec, "Missing version byte." end coder = @coders.fetch(payload_version) do raise UnsupportedCodec, "Unsupported packer version #{payload_version}" end coder.load(payload.byteslice(1..-1)) end private def validate_version(version) unless (0..255).cover?(version) raise ArgumentError, "Invalid version #{version.inspect}, versions must be an integer between 0 and 255" end version end end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false
Shopify/paquito
https://github.com/Shopify/paquito/blob/e462641cf1c8b3554f8749b86c387729fce2cfc4/lib/paquito/flat_cache_entry_coder.rb
lib/paquito/flat_cache_entry_coder.rb
# frozen_string_literal: true gem "activesupport", ">= 7.0" module Paquito class FlatCacheEntryCoder METADATA_CODEC = CodecFactory.build EXPIRES_AT_FORMAT = "E" # Float double-precision, little-endian byte order (8 bytes) VERSION_SIZE_FORMAT = "l<" # 32-bit signed, little-endian byte order (int32_t) (4 bytes) PREFIX_FORMAT = -(EXPIRES_AT_FORMAT + VERSION_SIZE_FORMAT) VERSION_SIZE_OFFSET = [0.0].pack(EXPIRES_AT_FORMAT).bytesize # should be 8 VERSION_OFFSET = [0.0, 0].pack(PREFIX_FORMAT).bytesize # Should be 12 VERSION_SIZE_UNPACK = -"@#{VERSION_SIZE_OFFSET}#{VERSION_SIZE_FORMAT}" def initialize(value_coder) @value_coder = value_coder end def dump(entry) version = entry.version payload = [ entry.expires_at || 0.0, version ? version.bytesize : -1, ].pack(PREFIX_FORMAT) payload << version if version payload << @value_coder.dump(entry.value) end def load(payload) expires_at = payload.unpack1(EXPIRES_AT_FORMAT) expires_at = nil if expires_at == 0.0 version_size = payload.unpack1(VERSION_SIZE_UNPACK) if version_size < 0 version_size = 0 else version = payload.byteslice(VERSION_OFFSET, version_size) end ::ActiveSupport::Cache::Entry.new( @value_coder.load(payload.byteslice((VERSION_OFFSET + version_size)..-1).freeze), expires_at: expires_at, version: version, ) end end end
ruby
MIT
e462641cf1c8b3554f8749b86c387729fce2cfc4
2026-01-04T17:57:28.878221Z
false