fast_jsonapi icon indicating copy to clipboard operation
fast_jsonapi copied to clipboard

Suggestion of usage required attributes from parent serializer

Open sofakingworld opened this issue 5 years ago • 1 comments

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

sofakingworld avatar May 14 '19 11:05 sofakingworld

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

artzte avatar May 14 '19 13:05 artzte