Skip to content

Instantly share code, notes, and snippets.

@bkudria
Created July 7, 2010 23:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bkudria/467459 to your computer and use it in GitHub Desktop.
Save bkudria/467459 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