Created
May 20, 2015 14:25
-
-
Save airportyh/47484cb736c285fe76f5 to your computer and use it in GitHub Desktop.
Example of using the Null Object Pattern for Lists
This file contains 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
class EmptyList | |
def first | |
nil | |
end | |
def rest | |
self | |
end | |
def append(item) | |
NonEmptyList.new(item, self) | |
end | |
def render | |
"<p>No results were found.</p>" | |
end | |
def each | |
end | |
end | |
class NonEmptyList | |
def initialize(item, rest) | |
@item = item | |
@rest = rest | |
end | |
def first | |
@item | |
end | |
def rest | |
@rest | |
end | |
def append(item) | |
NonEmptyList.new(item, self) | |
end | |
def each(&block) | |
block.call(first) | |
rest.each(&block) | |
end | |
def render | |
items = [] # cheating here: convert to | |
# array to use its join method | |
each do |item| | |
items.push( | |
" <li>\n" + | |
%Q( <a href="#{item.url}">#{item.title}</a>\n) + | |
" </li>") | |
end | |
%Q(<ul>\n#{items.join("\n")}\n</ul>) | |
end | |
end | |
Result = Struct.new(:title, :url) | |
results = EmptyList.new | |
.append(Result.new("Null Object Pattern", "http://en.wikipedia.org/wiki/Null_Object_pattern")) | |
.append(Result.new("Introduce Null Object", "http://refactoring.com/catalog/introduceNullObject.html")) | |
.append(Result.new("Q & A: is nothing something?", "https://van.physics.illinois.edu/qa/listing.php?id=1235")) | |
puts "<h1>Search Results</h1>" | |
puts results.render | |
puts | |
puts "<h1>Search Results</h1>" | |
puts EmptyList.new.render |
This file contains 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
<h1>Search Results</h1> | |
<ul> | |
<li> | |
<a href="https://van.physics.illinois.edu/qa/listing.php?id=1235">Q & A: is nothing something?</a> | |
</li> | |
<li> | |
<a href="http://refactoring.com/catalog/introduceNullObject.html">Introduce Null Object</a> | |
</li> | |
<li> | |
<a href="http://en.wikipedia.org/wiki/Null_Object_pattern">Null Object Pattern</a> | |
</li> | |
</ul> | |
<h1>Search Results</h1> | |
<p>No results were found.</p> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment