Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Asign a value with an arbitrary deep of keys to a lazy hash. The example shows a use case with i18n keys.
# 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
# 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