Skip to content

Instantly share code, notes, and snippets.

@maccman
Created September 22, 2008 17:24
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 maccman/12059 to your computer and use it in GitHub Desktop.
Save maccman/12059 to your computer and use it in GitHub Desktop.
# Alex MacCaw
# info@eribium.org
# Paranoid Hash
# This is so you don't need to validate options on initialize - as you may not require all the options for every method.
# You can validate them as the program runs - so you don't get unexpected nils.
# I still haven't decided whether this is a good idea or not ;)
# class Foo
# attr_reader :options
# def initialize(options = {})
# @options = options
# end
#
# def options!
# @paranoid_ops ||= options.dup.to_paranoid
# end
#
# def bar
# options![:bar]
# end
# end
#
# foo = Foo.new({:one => 1});
# foo.bar # raises error
#
# foo = Foo.new({:bar => 1});
# foo.bar #=> 1
class Hash
class ParanoidHashError < StandardError; end
def to_paranoid
instance_eval do
def [](key)
value = super(key)
return value unless value == nil
raise ParanoidHashError.new("You must specify '#{key}' as an option")
end
end
self
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment