Created
September 22, 2008 17:24
-
-
Save maccman/12059 to your computer and use it in GitHub Desktop.
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
# 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