Created
April 24, 2018 03:43
-
-
Save david-pm/83996de33a8d2ae921791c7dc7d62323 to your computer and use it in GitHub Desktop.
Null Object Pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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