okuramasafumi / alba

Alba is a JSON serializer for Ruby, JRuby and TruffleRuby.
https://okuramasafumi.github.io/alba/
MIT License
934 stars 43 forks source link

Support for heterogenous lists? #335

Closed felixwatts closed 1 year ago

felixwatts commented 1 year ago

Is your feature request related to a problem? Please describe.

I need to implement an API that returns a single JSON list containing items of multiple types.

If heterogenous lists are already supported I can't find any documentation on how to use that feature.

Describe the solution you'd like

foos = FooResource.new([foo1, foo2])
bars = BarResource.new([bar1, bar2])
foos_and_bars = foos + bars
json = Alba.serialize(foos_and_bars)

Describe alternatives you've considered

  1. Use one Resource type for multiple actual types using some logic in the resource class
  2. Manually construct a JSON list from two Alba generated lists of single typed items
  3. Try to negotiate a change to the API definition
  4. Don't use Alba

Additional context

okuramasafumi commented 1 year ago

Alba currently does not support this kind of feature. You can use to_h to generate a Hash and manually combine them.

I've come up with the new API below:

class FooResource
# Resource for Foo
end

class BarResource
# Resource for Bar
end

Alba.serialize([foo, bar], each_resource: true) # => Use FooResource and BarResource

The new each_resource option makes Alba.serialize infers resource class for each object. This would be a slow API but might be good fit for your use case. What do you think?

felixwatts commented 1 year ago

Yea that seems to make sense. I've personally got a workaround working using a single resource type for both actual types, but this would definitely be cleaner.

okuramasafumi commented 1 year ago

@felixwatts I'm interested in how you workaround this problem, could you share the code?

okuramasafumi commented 1 year ago

I'm closing this issue since there's some workaround. I feel I can implement it when finding a high demand of this feature, so feel free to add some comments if you want this feature.