I’m trying to extend OpenStruct for an application I’m building, where
I’d like to access nested hashes as models. OpenStruct (in core) sounds
perfect for this, but I ran into two problems:
- Recursion
My hashes have nested hashes, and I want to convert those to
objects, too. I was able to solve this problem pretty easily, see the
to_self method in the linked code [1].
However, this made me run into the second problem - speed. I was loading
rather large documents, and it was taking quite a bit of time to go
through them, instantiating classes for everything. I though I’d make
the code lazy-load, using the lazy.rb [0]
However, I overrode some more core methods for OpenStruct, to create
promises, and demand them, but now the code simply produces incorrect
results.
In IRB, I do:
LazyStruct.new({:a=>1, :b => 2}).a
But my result is 2, not 1. The code is here:
What could be going wrong? Any inishgt would be appreciatted. I’m using
Ruby 1.9.2-preview3
(Apologies for the Railsisms, this is part of a Rails project. The
classify method turns things into a string resembling a class, and
constantize turns that string into a constant - hopefully a class. This
code is bypassed in my simple example.)
0: http://github.com/mental/lazy
Thanks!
Benjamin K.
[email protected]