Created
December 17, 2010 20:09
-
-
Save rogercampos/745617 to your computer and use it in GitHub Desktop.
Asign a value with an arbitrary deep of keys to a lazy hash. The example shows a use case with i18n keys.
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
# lazy_hash.rb | |
module LazyHash | |
class << self | |
def lazy_add(hash, key, value, pre = nil) | |
skeys = key.split(".") | |
f = skeys.shift | |
if skeys.empty? | |
pre.nil? ? hash.send("[]=", f, value) : pre.send("[]=", f, value) | |
else | |
pre = pre.nil? ? hash.send("[]", f) : pre.send("[]", f) | |
lazy_add(hash, skeys.join("."), value, pre) | |
end | |
end | |
def build_hash | |
lazy = lambda { |h,k| h[k] = Hash.new(&lazy) } | |
Hash.new(&lazy) | |
end | |
end | |
end | |
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
# test.rb | |
require 'lazy_hash' | |
foo = LazyHash.build_hash | |
LazyHash.lazy_add(foo, "es.projects.index.phrase", "Some sentence") | |
LazyHash.lazy_add(foo, "es.projects.title", "Title") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment