Skip to content

Instantly share code, notes, and snippets.

@david-pm
Created April 24, 2018 03:43
Show Gist options
  • Save david-pm/83996de33a8d2ae921791c7dc7d62323 to your computer and use it in GitHub Desktop.
Save david-pm/83996de33a8d2ae921791c7dc7d62323 to your computer and use it in GitHub Desktop.
Null Object Pattern
# Active Nothing - Null Object Pattern
class Bot
FAUX_DATABASE = [{ id: 1, name: 'KITT' }, { id: 3, name: 'GERTY' }].freeze
attr_reader :name
def self.find(id)
row = FAUX_DATABASE.find{ |r| r[:id] == id }
return nil if row.nil?
new(row)
end
def initialize(row)
@name = row.dig(:name)
end
end
class MissingBot
def name
'missing robot'
end
end
# wrap both in another class
class GuaranteedRobot
def self.find(id)
Bot.find(id) || MissingBot.new
end
end
# if there is no Bot in the db, we will return an
# instance of our MissingBot which responds to `#name`
bots = [1,2,3].map { |id| GuaranteedRobot.find(id).name }
puts bots
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment