Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value of another attribute if needed attribute is nil

I've got a User model which has fullname and email attributes.

I need to overwrite method fullname somehow so it will return value of email when fullname is nil or empty.

like image 425
Max Al Farakh Avatar asked Jul 10 '11 10:07

Max Al Farakh


2 Answers

I haven't tried it with ActiveRecord, but does this work?

class User < ActiveRecord::Base
  # stuff and stuff ...

  def fullname
    super || email
  end
end

It depends how ActiveRecord mixes in those methods.

like image 56
d11wtq Avatar answered Nov 17 '22 13:11

d11wtq


To do what you want, you can quite easily override the default reader for fullname and do something like this:

class User < ActiveRecord::Base
  def fullname
    # Because a blank string (ie, '') evaluates to true, we need
    # to check if the value is blank, rather than relying on a
    # nil/false value. If you only want to check for pure nil,
    # the following line wil also work:
    #
    # self[:fullname] || email
    self[:fullname].blank? ? email : self[:fullname]
  end
end
like image 33
dnch Avatar answered Nov 17 '22 13:11

dnch