...
/Return Rich Result Objects, Not Booleans or Active Records
Return Rich Result Objects, Not Booleans or Active Records
Learn about enhanced testing, and improved error handling, and ensuring a more seamless development process in Rails.
We'll cover the following...
Enriching call results for clarity
A caller often needs to know what happened in the call they made. Not always, but often. Typical reasons are to report errors back to the user or to feed into the logic it needs to execute. As part of the seam between the outside world and our business logic, a boolean value—true
if the call succeeded, false
otherwise—is not very useful and can be hard to manage.
If, instead, we return a richer object that exposes details the caller needs, our code and tests be more readable, and our seam can now grow more easily if needs change.
A rich result doesn’t have to be fancy. We like creating them as inner classes of the service’s class as a pretty basic Ruby class, like so:
class WidgetsCreatordef create_widget(widget_params)if ...Result.new(created: true, widget: widget)elseResult.new(created: false, widget: widget)endendclass Resultattr_reader :widgetdef initialize(created:, widget: nil)@created = created@widget = widgetenddef created?@createdendendend