Skip to content

Instantly share code, notes, and snippets.

@mostlyobvious
Created June 17, 2023 10:46
Show Gist options
  • Save mostlyobvious/f39026514185e8f72e4daaca2d99b85a to your computer and use it in GitHub Desktop.
Save mostlyobvious/f39026514185e8f72e4daaca2d99b85a to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require "bundler/inline"
require "json"
gemfile do
source "https://rubygems.org"
gem "rails_event_store", "2.9.1"
gem "railties", "~> 7.0.0"
end
IssueHasBeenPostedOnGithub =
Class.new(RailsEventStore::Event)
event =
IssueHasBeenPostedOnGithub.new(data: OpenStruct.new(message: "This is unpreserved OpenStruct."))
in_memory_repository_with_json_serialization_to_mimic_database_behaviour =
RubyEventStore::InMemoryRepository.new(serializer: JSON)
preserve_types_as_seen_in_json_client =
RubyEventStore::Mappers::Transformation::PreserveTypes
.new
.register(Symbol, serializer: ->(v) { v.to_s }, deserializer: ->(v) { v.to_sym })
.register(
Time,
serializer: ->(v) { v.iso8601(RubyEventStore::TIMESTAMP_PRECISION) },
deserializer: ->(v) { Time.iso8601(v) }
)
.register(
ActiveSupport::TimeWithZone,
serializer: ->(v) { v.iso8601(RubyEventStore::TIMESTAMP_PRECISION) },
deserializer: ->(v) { Time.iso8601(v).in_time_zone },
stored_type: ->(*) { "ActiveSupport::TimeWithZone" }
)
.register(Date, serializer: ->(v) { v.iso8601 }, deserializer: ->(v) { Date.iso8601(v) })
.register(DateTime, serializer: ->(v) { v.iso8601 }, deserializer: ->(v) { DateTime.iso8601(v) })
.register(BigDecimal, serializer: ->(v) { v.to_s }, deserializer: ->(v) { BigDecimal(v) })
mapper_with_open_struct_preservation =
RubyEventStore::Mappers::PipelineMapper.new(
RubyEventStore::Mappers::Pipeline.new(
preserve_types_as_seen_in_json_client.register(OpenStruct, serializer: ->(v) { v.to_h }, deserializer: ->(v) { OpenStruct.new(v) }),
RubyEventStore::Mappers::Transformation::SymbolizeMetadataKeys.new
)
)
client =
RailsEventStore::Client.new(
repository: in_memory_repository_with_json_serialization_to_mimic_database_behaviour,
mapper: mapper_with_open_struct_preservation
)
client.publish(event)
pp [event.data, client.read.last.data]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment