Nil safe getter


/ Published in: Ruby
Save to your folder(s)

Access deeply nested properties in a nil-safe manner. This is usually a code smell but if you insist...


Copy this code and paste it in your HTML
  1. class SafeGetter
  2. attr_accessor :receiver
  3.  
  4. def self.safe_nil
  5. @safe_nil ||= SafeGetter.new(nil)
  6. end
  7.  
  8. def initialize(r)
  9. @receiver = r
  10. end
  11.  
  12. def to_s
  13. @receiver.to_s
  14. end
  15.  
  16. def method_missing(methodname, *args)
  17. (@receiver.respond_to? methodname) ? SafeGetter.new(@receiver.send(methodname)) : SafeGetter.safe_nil
  18. end
  19. end
  20.  
  21. # SafeGetter.new(@user).course.book.title.name.to_s => ''

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.