2
votes

right now I use devise and have two fields. fname and lname.

I would like the ability to put a full_name field to the user model. Then the user model would take the full_name field and extract the fname and lname by splitting with a space. if there is more than one space that would all go to the fname and the last item would be the last name, and then saved to the user model with the extracted fields for fname and lname.

Is this possible without hacking up devise?

Thanks

2

2 Answers

4
votes

The problem with both current answers is that they don't handle three(+) word names such as Billy Bob Thornton.

'Billy Bob Thornton'.split(/(.+) (.+)$/)  => ["", "Billy Bob", "Thornton"] 
'Billy Bob Thornton'.split(' ', 2)        => ["Billy", "Bob Thornton"] 

The original posting requests all but the last name to go to first name. So I'd suggest:

def full_name
  [first_name, last_name].join(' ')
end

def full_name=(name)
  elements = name.split(' ')
  self.last_name = elements.delete(elements.last)
  self.first_name = elements.join(" ")
end
3
votes

You don't need to hack up devise persay, just do it in your Users model (or whatever modal you are usuing as your devise_for

class User
  def fullname
    self.fname << " " << self.lname
  end
  def fullname=(fname)
    names = fname.split(/(.+) (.+)$/)
    self.fname = names[0]  
    self.lname = names[1] 
  end
end

untested and off the top my head, but it should be a start....

i wouldn't suggest storing the fullname, just use it like a helper function, but that is up to you.