Skip to content

Instantly share code, notes, and snippets.

@jordelver
Last active December 16, 2015 10:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jordelver/5422197 to your computer and use it in GitHub Desktop.
Save jordelver/5422197 to your computer and use it in GitHub Desktop.

Usage

Normal

person = Person.new('Jo', 'Bloggs')
    
HumanName.new(person).full_name
> "Joe Bloggs"

Specify name attributes

person = Person.new(title: 'Mr', first: 'Jo', last: 'Bloggs')
    
HumanName.new(person, :title, :first, :last).full_name
> "Mr Joe Bloggs"

Interpolation

person = Person.new('Jo', 'Bloggs')
    
string = "My name is #{HumanName.new(person)}"
> "My name is Joe Bloggs"

Splat the arguments in from an array

names = [ :first, :last ]
name = HumanName.new(person, *names)
class Person
attr_reader :first_name, :last_name
def initialize(first_name, last_name)
@first_name, @last_name = first_name, last_name
end
def full_name
HumanName.new(self, :title, :first_name, :last_name)
end
end
class HumanName
attr_reader :nameable, :name_attributes
def initialize(nameable, *name_attributes)
@nameable = nameable
@name_attributes = name_attributes
end
def full_name
names.join(" ")
end
def names
name_attributes.map do |attribute|
unless nameable.respond_to?(attribute)
raise ArgumentError.new("#{nameable.class} does not respond to `#{attribute}`")
end
nameable.send(attribute)
end
end
def name_attributes
@name_attributes.empty? ? defaults : @name_attributes
end
def to_s
full_name
end
private
def defaults
[ :first_name, :last_name ]
end
end
require "minitest/autorun"
require "minitest/pride"
require "mocha"
require_relative "../../app/models/human_name"
describe HumanName do
it "must output the first and last name by default" do
person = stub(first_name: 'Jo', last_name: 'Bloggs')
name = HumanName.new(person)
name.full_name.must_equal "Jo Bloggs"
end
it "must interpolate easily" do
person = stub(first_name: 'Jo', last_name: 'Bloggs')
string = "#{HumanName.new(person)}"
string.must_equal "Jo Bloggs"
end
it "must allow specifying which attributes to use" do
person = stub(first: 'Jo', last: 'Bloggs')
name = HumanName.new(person, :first, :last)
name.full_name.must_equal "Jo Bloggs"
end
it "must raise an ArgumentError if incorrect attributes are supplied" do
person = Object.new
name = HumanName.new(person, :i_dont_exist)
proc { name.full_name }.must_raise ArgumentError
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment