blueprinter icon indicating copy to clipboard operation
blueprinter copied to clipboard

Feature proposal: Support tolerating rendering `nil`

Open iamvery opened this issue 4 years ago • 0 comments

Problem

I have found that I have some use case for rendering potentially-nil values. In particular, this is when I wish to specify a :root on the rendering:

WidgetBlueprint.render(widget_or_nil, root: :widget)

When the value of widget_or_nil is nil, the following error occurs:

NoMethodError: undefined method `id' for nil:NilClass

To solve this problem today, we have to resort to wrapping the result outside the use of the library. Something like:

{ widget: widget_or_nil && WidgetBlueprint.render(widget_or_nil) }

This isn't the worst, but it's a little repetitive.

Proposal

Given the stated Problem, I am proposing a new rendering option :allow_nil that solves this problem. I chose the name based on similar options seen in Ruby on Rails. It would work like this:

widget_or_nil = Widget.new(id: 123)
rendered = WidgetBlueprint.render_as_hash(widget_or_nil, root: :widget)
# => { widget: { id: 123 } }

widget_or_nil = nil
rendered = WidgetBlueprint.render_as_hash(widget_or_nil, root: :widget)
# => { widget: nil }

A Note on nil

I recognize that this my be a controversial proposal based on the prevalence of issues caused by nil in systems. That said, I believe the use case is legitimate, and it feels a little icky to me to have to ditch the library-support :root feature for such a case.

Either way, I'm entirely open to feedback and appreciate you having a look at this!

iamvery avatar Dec 09 '21 19:12 iamvery