Class: NameOfPerson::PersonName

Inherits:
String
  • Object
show all
Defined in:
lib/name_of_person/person_name.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(first, last = nil) ⇒ PersonName

Returns a new instance of PersonName.

Raises:

  • (ArgumentError)


12
13
14
15
16
# File 'lib/name_of_person/person_name.rb', line 12

def initialize(first, last = nil)
  raise ArgumentError, "First name is required" unless first.present?
  @first, @last = first, last
  super full
end

Instance Attribute Details

#firstObject (readonly)

Returns the value of attribute first.



5
6
7
# File 'lib/name_of_person/person_name.rb', line 5

def first
  @first
end

#lastObject (readonly)

Returns the value of attribute last.



5
6
7
# File 'lib/name_of_person/person_name.rb', line 5

def last
  @last
end

Class Method Details

.full(full_name) ⇒ Object



7
8
9
10
# File 'lib/name_of_person/person_name.rb', line 7

def self.full(full_name)
  first, last = full_name.to_s.squish.split(/\s/, 2)
  new(first, last) if first.present?
end

Instance Method Details

#abbreviatedObject

Returns first initial + last, such as “J. Fried”.



29
30
31
# File 'lib/name_of_person/person_name.rb', line 29

def abbreviated
  @abbreviated ||= last.present? ? "#{first.first}. #{last}" : first
end

#encode_with(coder) ⇒ Object

Override to_yaml to serialize as a plain string.



54
55
56
# File 'lib/name_of_person/person_name.rb', line 54

def encode_with(coder)
  coder.represent_scalar nil, to_s
end

#familiarObject

Returns first + last initial, such as “Jason F.”.



24
25
26
# File 'lib/name_of_person/person_name.rb', line 24

def familiar
  @familiar ||= last.present? ? "#{first} #{last.first}." : first
end

#fullObject

Returns first + last, such as “Jason Fried”.



19
20
21
# File 'lib/name_of_person/person_name.rb', line 19

def full
  @full ||= last.present? ? "#{first} #{last}" : first
end

#initialsObject

Returns just the initials.



44
45
46
# File 'lib/name_of_person/person_name.rb', line 44

def initials
  @initials ||= remove(/(\(|\[).*(\)|\])/).scan(/([[:word:]])[[:word:]]+/i).join
end

#mentionableObject

Returns a mentionable version of the familiar name



49
50
51
# File 'lib/name_of_person/person_name.rb', line 49

def mentionable
  @mentionable ||= familiar.chop.delete(' ').downcase
end

#possessiveObject

Returns full name with with trailing ‘s or ’ if name ends in s.



39
40
41
# File 'lib/name_of_person/person_name.rb', line 39

def possessive
  @possessive ||= "#{self}'#{"s" unless end_with?("s")}"
end

#sortedObject

Returns last + first for sorting.



34
35
36
# File 'lib/name_of_person/person_name.rb', line 34

def sorted
  @sorted ||= last.present? ? "#{last}, #{first}" : first
end