Created
March 22, 2010 22:52
-
-
Save mboeh/340640 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 SettingReader | |
def initialize hash | |
# You may want to consider doing a deep copy of the hash and then #freeze-ing it | |
@hash = hash.nil? ? {} : hash | |
raise ArgumentError, "must pass a hash or nil" unless @hash.kind_of? Hash | |
end | |
def get key, default = nil | |
h = @hash | |
for subkey in key.split(".") | |
h = h[subkey] | |
return default if h.nil? | |
end | |
# You may want to #freeze or #dup this here if you didn't in #initialize | |
return h | |
end | |
alias [] get | |
end | |
sr = SettingReader.new nil | |
sr["a.b.c"] == nil or raise | |
sr["a"] == nil or raise | |
sr = SettingReader.new({"a" => { "b" => { "c" => 1 } }, "d" => 2}) | |
sr["a"].kind_of?(Hash) or raise | |
sr["d"] == 2 or raise | |
sr["a.b.c"] == 1 or raise |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment