Netflix / fast_jsonapi

No Longer Maintained - A lightning fast JSON:API serializer for Ruby Objects.
Apache License 2.0
5.07k stars 425 forks source link

Suggestion of usage required attributes from parent serializer #418

Open sofakingworld opened 5 years ago

sofakingworld commented 5 years ago

Hi Netflix! :)

I would like to suggest an alternative for Helpers and inheritance (I'm sure, most use Helpers for inheritance)

Problem:

I have big serializer with many custom attributes, and there is needed short version

Current realization:

module Helpers::User
  extend ActiveSupport::Concern

  class_methods do
    def full_name(user)
      [user.first_name, user.middle_name, user.last_name].join(' ')
    end
    .... #other methods
  end
end
class UserSerializer
  include FastJsonapi::ObjectSerializer
  include Helpers::User
  attribute :id
  attribute :full_name, &:full_name
  # other attributes with same pattern:
  # attribute :att_name, &:proc_helper_fucntion
end

So UserShortSerializer reuses same modules and looks like this: (we need only id and full_name)

class UserShortSerializer
  include FastJsonapi::ObjectSerializer
  include Helpers::User
  attribute :id
  attribute :full_name, &:full_name
end

I suggest adding a new DSL method parent_attributes, and then UserShortSerializer will look so:

class UserShortSerializer < UserSerializer
  parent_attributes :id, :full_name
end

UserShortSerializer.new(User.first).serializable_hash #=> {data: {id: 1, full_name: 'Robert Jr. Downey'}}

If you like the idea - support, I will be happy to implement

artzte commented 5 years ago

My app has similar concerns... I used the "fields" option at invocation of the serializer.

https://github.com/artzte/tinysis-api/blob/develop/app/controllers/concerns/user_controller_methods.rb#L121