Skip to content

Commit

Permalink
fix: allow using active_model_serializers in associations (compat)
Browse files Browse the repository at this point in the history
  • Loading branch information
ElMassimo committed Apr 19, 2023
1 parent 3a7c2e6 commit 501ed40
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
32 changes: 32 additions & 0 deletions lib/oj_serializers/compat.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,38 @@ def self.one(object, options = nil)
def self.many(array, options = nil)
array.map { |object| new(object, options) }
end

# OjSerializer: Used internally to write a single object association in :hash mode.
#
# Returns nothing.
def self.one_as_hash(object)
new(object)
end

# OjSerializer: Used internally to write an association in :hash mode.
#
# Returns nothing.
def self.many_as_hash(array)
array.map { |object| new(object) }
end

# OjSerializer: Used internally to write a single object association in :json mode.
#
# Returns nothing.
def self.write_one(writer, object, options)
writer.push_value(new(object, options))
end

# OjSerializer: Used internally to write an association in :json mode.
#
# Returns nothing.
def self.write_many(writer, array, options)
writer.push_array
array.each do |object|
write_one(writer, object, options)
end
writer.pop
end
end

require 'oj_serializers'
Expand Down
28 changes: 28 additions & 0 deletions spec/oj_serializers/compat_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# frozen_string_literal: true

require 'spec_helper'

require 'support/models/album'
require 'support/serializers/active_model_serializer'

class CompatSerializer < Oj::Serializer
has_one :item, serializer: ActiveModelSerializer
has_many :items, serializer: ActiveModelSerializer
end

RSpec.describe "AMS Compat", type: :serializer do
def expect_encoded_json(object)
expect(Oj.dump(object).tr("\n", ''))
end

it 'can use ams serializer in associations' do
album = Album.abraxas.tap { |a| a.id = 1 }
object = OpenStruct.new(item: album, items: [album, album])
attrs = {id: 1, name: "Abraxas"}

expect_encoded_json(CompatSerializer.one(object)).to eq({
item: attrs,
items: [attrs, attrs],
}.to_json)
end
end

0 comments on commit 501ed40

Please sign in to comment.