What is a good way to provide an easy to use object-style interface to an HTTP API, while still allowing asynchronous HTTP requests to be made? For example, given the following code:
user = User.find(1) # /api/v1/users/1
f = user.foo # /api/v1/users/1/foo
b = user.bar # /api/v1/users/1/bar
Calls to the foo and bar methods could logically be called in parallel, but if possible I’d like to let the calling user have a clean way to declare their intent for parallel calls without getting into the details of the underlying HTTP lib.
I don’t think invisibly automating the parallelization is a good idea, so that the calling code is explicit about its expectations. But, I do think something like the following block syntax could be extremely useful for front-end developers to be able to use when they know that a set of requests do not depend on each other.
# possible implementation?
user = User.find(1)
User.parallel do
f = user.foo
b = user.bar
end
Is this possible? How can I accomplish this using Ruby 1.9.2?
Transparent parallelization is generally accomplished through something called a future. In ruby, both the lazy and promise gems have implementations of futures. Here’s an example with the promise gem:
A future will run the computation in a block in a background thread, and any attempt to operate on f or b will block unless the background thread has already run to completion.
As a library designer, so long as your library is threadsafe, this should be fine in many cases, though it probably doesn’t scale all that well in ruby.