Skip to content

Instantly share code, notes, and snippets.

@fsubal
Created July 28, 2026 01:57
Show Gist options
  • Select an option

  • Save fsubal/9b9ef02b09624c67af7e6a01883d7f48 to your computer and use it in GitHub Desktop.

Select an option

Save fsubal/9b9ef02b09624c67af7e6a01883d7f48 to your computer and use it in GitHub Desktop.
has_json_snapshot.rb
module HasJsonSnapshot
extend ActiveSupport::Concern
class_methods do
def has_one_json_snapshot(attribute_name, class_name: attribute_name.to_s.classify)
klass = class_name.constantize
raise "#{class_name} does not have #as_json method" unless klass.method_defined?(:as_json)
composed_of(
attribute_name,
constructor: ->(json) { klass.new(json) },
converter: ->(model) { model.as_json.except(:id, :created_at, :updated_at) }
)
end
def has_many_json_snapshots(attribute_name, class_name: attribute_name.to_s.classify)
klass = class_name.constantize
raise "#{class_name} does not have #as_json method" unless klass.method_defined?(:as_json)
composed_of(
attribute_name,
constructor: ->(json) { json.map { klass.new(_1) } },
converter: ->(models) { models.map { _1.as_json.except(:id, :created_at, :updated_at) } }
)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment