jsonapi-rb / jsonapi-serializable

Conveniently build and efficiently render JSON API resources.
http://jsonapi-rb.org
MIT License
45 stars 35 forks source link

Add links conditionally #126

Closed zubin closed 6 months ago

zubin commented 6 months ago

My use case is to only include possible actions on a resource.

I want to omit ones which aren't relevant, depending on the resource state.

Something like this:

link :boom do
  if @object.can_go_boom?
    href "the-boom-url"
  end
end

Currently this results in links: {boom: nil} but I'd prefer any links which are nil to be removed (like Hash#compact).

Does this make sense? I'd be happy to make a PR if the idea is sound.

zubin commented 6 months ago

Closing because I found a way to do it:

extend JSONAPI::Serializable::Resource::ConditionalFields

link :boom, if: -> { @object.can_go_boom? } do
  href "the-boom-url"
end

Couldn't see it in the docs, came across it here: https://github.com/jsonapi-rb/jsonapi-serializable/issues/49