Skip to content

Instantly share code, notes, and snippets.

@acook
Forked from bkudria/irb.rb
Created February 7, 2013 00:29
Show Gist options
  • Save acook/4727270 to your computer and use it in GitHub Desktop.
Save acook/4727270 to your computer and use it in GitHub Desktop.
LazyStruct.new({:a=>1, :b => 2}).a # => 2
# That's wrong. Why?
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