Nil is Unfriendly

@PeytonF18 usually when I get into scenarios like this where I might encounter nil on an association, I handle it with a null object.

    class MyDecorator
      def president_name
        leader.username        
      end
    end

    class MyModel < ActiveRecord::Base
      def leader
        first_group.leader_or_no_leader
      end

      def first_group
         groups.order(level: :desc).first_or_no_group
      end  
    end

    class NoLeaderExists
      def username
        "" # could also say "Has No Leader", etc.
      end
   end

   class Group
     def self.first_or_no_group
       first || NoGroup.new
     end

     def leader_or_no_leader
       leader || NoLeaderExists.new
     end
  end

  class NoGroup
    def leader_or_no_leader
      NoLeaderExists.new
    end
  end

``

Despite the new syntax supporting a try-like behavior, using try to rescue from nil is a serious code smell. If you’re using try, it’s time to investigate other approaches for the problem.

This example is a little convoluted because you have two possible places where there could be a nil something (the check for a leader, the check for a group). It might be worth restructuring your templates so that you’re digging less deeply in an individual template (these examples are violating Law of Demeter).