Skip to content

Instantly share code, notes, and snippets.

@mpraglowski
Created June 11, 2025 06:58
Show Gist options
  • Select an option

  • Save mpraglowski/ca852ba76503888be85ec53bacb491fe to your computer and use it in GitHub Desktop.

Select an option

Save mpraglowski/ca852ba76503888be85ec53bacb491fe to your computer and use it in GitHub Desktop.
require "bundler/inline"
gemfile do
source "https://rubygems.org"
gem "ruby_event_store",
github: "RailsEventStore/rails_event_store",
ref: "45e685ecab7fe3f59e0fee07ac0630bbef00c840"
end
SomeEventWithPersonalInfo =
Class.new(RubyEventStore::Event) do
def self.encryption_schema
{ personal_info: ->(data) { data.fetch(:user_id) } }
end
end
class KeysRepository < RubyEventStore::Mappers::InMemoryEncryptionKeyRepository
def fetch_keys(identifiers)
# just created keys for the given identifiers if not exists
# here shall be an API call to KMS storage
identifiers.each do |identifier|
create(identifier) unless key_of(identifier)
end
end
end
class CustomEncryptionMapper < RubyEventStore::Mappers::BatchMapper
def initialize
@keys_repository = KeysRepository.new
super(
RubyEventStore::Mappers::EncryptionMapper.new(
@keys_repository,
serializer: RubyEventStore::Serializers::YAML,
forgotten_data: RubyEventStore::Mappers::ForgottenData.new
)
)
end
def records_to_events(records)
# fetch keys identifiers from records metadata
# simplified as in read code you need to assume not all records are encrypted
identifiers =
records
.flat_map do |r|
r.metadata[:encryption].values.map { |v| v[:identifier] }
end
.compact
@keys_repository.fetch_keys(identifiers.uniq)
super
end
def events_to_records(events)
# fetch keys identifiers from events data
# simplified - in real life it will be probably more complicated :)
@keys_repository.fetch_keys(
events.map { |e| e.data[:user_id] }.compact.uniq
)
super
end
end
data = RubyEventStore::InMemoryRepository.new
res =
RubyEventStore::Client.new(
repository: data,
mapper: CustomEncryptionMapper.new
)
events =
%w[sample@example.com another@example.com onemore@example.com].map do |email|
SomeEventWithPersonalInfo.new(
data: {
personal_info: email,
user_id: rand(1000)
}
)
end
res.append(events)
puts "Stored data: #{data.send(:storage).values.map { |v| v.data }}"
puts "Read data: #{res.read.map(&:data)}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment