And I learned about
this thing called the
Null Object Pattern.
Friday, September 28, 12
Slide 4
Slide 4 text
Right now we do things
like this:
if @guest && @guest.attending?
do_attending_stuff
end
Friday, September 28, 12
Slide 5
Slide 5 text
The Null Object Pattern seeks
to remove the excess logic.
@guest = Guest.find_by_id(params[:id])
|| NullGuest.new
...
class NullGuest
def attending?
false
end
end
Friday, September 28, 12
Slide 6
Slide 6 text
But this can get a bit tedious:
class NullGuest
def act!(action)
end
def additional_guests
nil
end
def attending?
false
end
def blank_name?
true
end
def display_name_or_email
nil
end
def email_address
nil
end
def email_address_id
nil
end
def member?
false
end
def not_attending?
false
end
...
Friday, September 28, 12
Slide 7
Slide 7 text
So I wrote a gem to
make it easier:
GordonDiggs/nobody
Friday, September 28, 12
Slide 8
Slide 8 text
How it’s used
class NulllGuest
include Nobody
returns_false_for :attending?, :not_attending?
returns_true_for :blank_name?
returns_nil_for :display_name, :personal_note
def state
'initialized'
end
end
Friday, September 28, 12
Slide 9
Slide 9 text
How it works
• Define methods on the given class that
return a specific value using Ruby’s
define_method
• Could in theory allow any return value
Friday, September 28, 12
Slide 10
Slide 10 text
Final thoughts
• The wiki page on Null Object Pattern
sucks. Don’t read it.
• Null classes can get tricky because of
coupling
• Metaprogramming is hard.
Friday, September 28, 12
Slide 11
Slide 11 text
Thank you
github.com/GordonDiggs/nobody
gem install nobody
Friday, September 28, 12