Skip to content

Instantly share code, notes, and snippets.

@airportyh
Created May 20, 2015 14:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save airportyh/47484cb736c285fe76f5 to your computer and use it in GitHub Desktop.
Save airportyh/47484cb736c285fe76f5 to your computer and use it in GitHub Desktop.
Example of using the Null Object Pattern for Lists
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
<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