Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Autoload #1

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions lib/bin/store.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -25,11 +25,21 @@ def write(key, value, options={})
def read(key, options=nil) def read(key, options=nil)
super do super do
if doc = collection.find_one(:_id => key.to_s, :expires_at => {'$gt' => Time.now.utc}) if doc = collection.find_one(:_id => key.to_s, :expires_at => {'$gt' => Time.now.utc})
doc['raw'] ? doc['value'] : Marshal.load(doc['value'].to_s) autoload_missing_constants do
doc['raw'] ? doc['value'] : Marshal.load(doc['value'].to_s)
end
end end
end end
end end


def autoload_missing_constants
yield
rescue ArgumentError => error
lazy_load ||= Hash.new { |hash, hash_key| hash[hash_key] = true; false }
if error.to_s[/undefined class|referred/] && !lazy_load[error.to_s.split.last.sub(/::$/, '').constantize] then retry
else raise error end
end

def delete(key, options=nil) def delete(key, options=nil)
super do super do
collection.remove(:_id => key.to_s) collection.remove(:_id => key.to_s)
Expand Down Expand Up @@ -81,4 +91,4 @@ def counter_key_upsert(key, amount)
}, :upsert => true) }, :upsert => true)
end end
end end
end end
17 changes: 16 additions & 1 deletion spec/bin/store_spec.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -97,6 +97,21 @@
it "works with symbol" do it "works with symbol" do
store.read(:foo).should == 'bar' store.read(:foo).should == 'bar'
end end

it "works with not yet loaded classes" do
class Klass
def initialize(str)
@str = str
end
def say_hello
@str
end
end
obj = Klass.new("hello\n")
store.write('foo', obj)
dump = store.read('foo')
dump.say_hello.should == "hello\n"
end
end end


describe "#delete" do describe "#delete" do
Expand Down Expand Up @@ -207,4 +222,4 @@
end end
end end
end end
end end