Background
Sometime ago I found a bug in my RAML logic where it wasn’t accounting for the fact that a raw response could have no bodies. This was breaking my CrystalForge webserver as it relied on a body being present. Here is the quick code fix put together to get this going again:
|
Solution
This got everything up and working again, but there had to be a better
way to write this. I decided to remove the nil I was initializing the
RawResponse
with and instead send a Null representation of the body instead.
Using OpenStruct you can mimic whole objects that are normally “outside” of your
control, which helped out nicely with this refactor. Here is the code
afterwards:
|
This has removed the complexity of both RawResponse
and RawExample
by a good
bit. RawExample#responses
no longer needs to worry about bodies being in a
good valid state, it can just map over them and know that each one is valid.
RawResponse#body
no longer needs to have the responsibility of making sure body is
nil
anymore and can return back to expecting #example having the right answer.
The next time you find yourself wanting to pass nil
and have it mean
something, instead consider using the NullObject Pattern,
and if you have Ruby in your toolbelt remember that OpenStruct
may be the best
fit for the bill.