Created
May 19, 2010 20:21
-
-
Save mileszs/406791 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| class Memcached | |
| def fetch(key) | |
| if value = get(key) | |
| value | |
| elsif block_given? | |
| begin | |
| add(key, value = yield) | |
| rescue Memcached::NotStored => e | |
| value = get(key) | |
| end | |
| value | |
| end | |
| end | |
| end |
Author
I don't know that it's necessarily completely useless. If, for some reason, the add to Memcache is slow, and a key of the same name gets added between the check for a value and the completion of our add, we'll get the NotStored error. If that happens, we want to return the value of the key that was stored while we were trying to store something else. Haha.
Maybe it's overly defensive? I don't know. I left it out initially, but I can see its purpose.
def fetch(key)
get(key) || add(key, yield) rescue get(key) if block_given?
end
Is that legal? Ruby ♥ moment if it is. Where's the spec?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Looking at it again...the rescue clause is useless since #get should return nil since nothing was stored. Here's another stab:
def fetch(key) value = get(key) if value.nil? && block_given? value = yield add(key, value) end value rescue Memcached::NotStored nil # or do we want value, the result of the yield? change the above to ensure? endAnd now to curse FriendFeed. :-)