How to read attribute only if it is present?

ruby, ruby-on-rails

Solution

I agree with Ishank but you can call `super` to use Rails' getter and then use ActiveSupport's `presence` method which will return the value if it is `present?` or otherwise return `nil` (which will trigger the statement after the `||`).

def name
  super.presence || "[You have no name yet]"
end

To be clear, stack level too deep is happening because you are checking `self.name.blank?` - when you use `self.name` here, that is calling the `name` method on self (which is the method you are currently in) - so that results in an infinite loop.

Problem

I am trying to display a model attribute only if it is present. If it is not, then a placeholder should be displayed. This is what I've got: ``` class Person < ActiveRecord::Base def name if self.name.blank? "[You have no name yet]" else read_attribute(:name) end end end ``` However, I am getting a `stack level too deep` error. How can this be done? Thanks for any help.

Original source