HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyrailsMinor

Avoid printing attributes of the nil object in Rails

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thenilavoidattributesrailsprintingobject

Problem

Currently, when I'm wanting to print a value for my class I do the following...



This seems really redundant to me. I've also have done...



where I've created a function for each attribute to kind of hide the first case. It seems a little much though. Is there a more preferred way to do it such as...

Solution

You are right, you code is too verbose. This is a pretty common pattern and you have some alternatives. For example, active_support has the abstraction Object#try:



Another alternative is the Object#maybe proxy: https://github.com/bhb/maybe

Code Snippets

<%= @person.team.try(:name) %>
<%= @person.team.maybe.name %>

Context

StackExchange Code Review Q#109533, answer score: 7

Revisions (0)

No revisions yet.