Created
July 7, 2010 23:54
-
-
Save bkudria/467459 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
LazyStruct.new({:a=>1, :b => 2}).a # => 2 | |
# That's wrong. Why? |
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
require 'lazy' | |
class LazyStruct < OpenStruct | |
def self.to_self(value, key) | |
klass = key.classify.constantize rescue self | |
case value.class | |
when Array | |
value.map{|e| klass.new(e)} | |
when Hash | |
klass.new(value) | |
else | |
value | |
end | |
end | |
def initialize(obj) | |
@table = {} | |
obj = (obj.respond_to? :each) ? obj : {'data' => obj} | |
for k,v in obj | |
@table[k.to_sym] = Lazy::Promise.new {self.class.to_self(v, k)} | |
new_ostruct_member(k) | |
end | |
end | |
def new_ostruct_member(name) | |
name = name.to_sym | |
unless self.respond_to?(name) | |
class << self; self; end.class_eval do | |
define_method(name) { @table[name].__result__ } | |
define_method("#{name}=") { |x| modifiable[name] = x } | |
end | |
end | |
name | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment