Skip to content

Instantly share code, notes, and snippets.

@vjt
Created February 11, 2010 12:43
Show Gist options
  • Save vjt/301471 to your computer and use it in GitHub Desktop.
Save vjt/301471 to your computer and use it in GitHub Desktop.
# http://gist.github.com/301471
#
# Not Found - (C) 2010 [email protected] - MIT License
#
# Quick hack to have a string that always says "not found",
# even when multiple methods are chained to it.
#
#
# E.g.:
#
# >> x = NotFound.new
# => "not found"
# >> x.oai_dc.authors.antani
# => "oai_dc authors antani not found"
# >> x.something(:that).will(:have, :attributes)
# => "something that will have attributes not found"
#
#
# Want to filter some methods? Here we go:
#
# >> x = NotFound.new(:_no => [:join])
# => "not found"
# >> x.prot.antani.join("\n").pizello
# => "document prot antani pizello not found"
#
#
# And one more thing: NotFound is blank!
#
# >> x.blank?
# => true
# >> x.nil?
# => true
#
# Efficiency? Quite efficient:
#
# >> bench(10000) { NotFound.new('document', :_no => [:join, :prot]).prot.antani.join("\n").pizello }
# 10000 iterations: 1.205242 (0.000121 per iteration)
#
# (bench() is here: http://gist.github.com/301485)
#
# Have fun :-)
#
class NotFound < String
def initialize(*attr)
@filters = attr.pop[:_no] \
if attr.last.kind_of?(Hash) &&
attr.last.has_key?(:_no)
@attr = attr.flatten
replace((@attr + ['not found']).join(' '))
end
undef_method :[], :type, :id
def blank?; true end
alias :nil? :blank?
def method_missing(meth, *args)
forward =
if @filters && @filters.include?(meth)
@attr
else
[@attr, meth, args]
end
self.class.new(forward, :_no => @filters)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment