Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ability to skip nil values #155

Open
jpboliv opened this issue May 14, 2024 · 3 comments
Open

Ability to skip nil values #155

jpboliv opened this issue May 14, 2024 · 3 comments

Comments

@jpboliv
Copy link

jpboliv commented May 14, 2024

Similar to #133

Is there a way to exclude attributes if its value is nil?

We're are migrating our API serialization library to yours, particularly because of performance reasons. And we have multiple instances of big payloads where there are fields that could be nil.

For example, this is how we include errors on our serializers, which leads us to instances where if the resource has no errors it will include it in the payload unnecessarily.

class ApplicationSerializer < Panko::Serializer
      attributes :errors
      
      def errors
        return unless object&.errors&.any?

        object.errors.messages
      end
end

If it's not possible at the moment, is this a feature that you might consider adding support for in the future? For example a general config where you could skip all nil values.

@yosiat
Copy link
Owner

yosiat commented Jun 13, 2024

Hi,

The library don't support excluding keys based on their values.
What you can do, it use "SKIP" option, so it won't serialize "errors" if there aren't any. see test as example: https://github.com/yosiat/panko_serializer/blob/master/spec/panko/serializer_spec.rb#L181

class ApplicationSerializer < Panko::Serializer
      attributes :errors
      
      def errors
        return Panko::SKIP unless object&.errors&.any?

        object.errors.messages
      end
end

@jpboliv that answers your question?

@jpboliv
Copy link
Author

jpboliv commented Jun 25, 2024

Hi! sorry for the late reply @yosiat , but that Panko::SKIP option should be enough to help us!
I think it might be worth adding a reference on that feature to your documentation!
Cheers!

@SlavaNixon
Copy link

Hello. Maybe this option should be specified in the documentation?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants