Skip to content

Instantly share code, notes, and snippets.

@sukima
Created July 26, 2010 20:36
Show Gist options
  • Save sukima/491187 to your computer and use it in GitHub Desktop.
Save sukima/491187 to your computer and use it in GitHub Desktop.
Parse a persons name into parts. Ruby on Rails
class Instructor < ActiveRecord::Base
# code graciously copied and pasted from
# http://mysmallidea.com/articles/2009/5/31/parse-full-names-with-ruby/index.html
def self.parse_name(name)
return false unless name.is_a?(String)
# First, split the name into an array
parts = name.split
# If any part is "and", then put together the two parts around it
# For example, "Mr. and Mrs." or "Mickey and Minnie"
parts.each_with_index do |part, i|
if ["and", "&"].include?(part) and i > 0
p3 = parts.delete_at(i+1)
p2 = parts.at(i)
p1 = parts.delete_at(i-1)
parts[i-1] = [p1, p2, p3].join(" ")
end
end
# Build a hash of the remaining parts
hash = {
:suffix => (s = parts.pop unless parts.last !~ /(\w+\.|[IVXLM]+|[A-Z]+)$/),
:last_name => (l = parts.pop),
:prefix => (p = parts.shift unless parts[0] !~ /^\w+\./),
:first_name => (f = parts.shift),
:middle_name => (m = parts.join(" "))
}
#Reverse name if "," was used in Last, First notation.
if hash[:first_name] =~ /,$/
hash[:first_name] = hash[:last_name]
hash[:last_name] = $` # everything before the match
end
return hash
end
end
class ValidatedUser < ActiveRecord::Base
validates_each :name do |record, attr, value|
hash = User.parse_name(value)
record.errors.add attr, 'must have a first and last name' if
( hash[:first_name].nil? || hash[:last_name].nil? )
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment