Suppose we wish to serve a bunch of images from a directory by over a REST endpoint and retrieve them by index. For example: http://localhost:4567/image?index=0 would return the first image in the directory. This is easy to accomplish in Ruby by using Sinatra:

require 'sinatra'
get '/image' do

  # Read all the JPEG files from a given directory
  @images = Dir.glob("/Users/nspool/Pictures/*.jpg")

  # Take the path at the supplied index
  index = params['index'].to_i
  path = @images[index]

  # Return the image
  send_file open(path, type: 'image/jpeg', disposition: 'inline')
end 

If we just want to serve a different image for each index and not worry about running out of images by choosing an image index that is too high, we can return the image at index modulo the number of available images.

Here is a more complete example that does just that:

require 'sinatra'
get '/' do
	'Usage: /image?index=123'
end
get '/image' do
	@images = Dir.glob("/Users/nspool/Pictures/*.jpg")
	index = params['index'].to_i % @images.count
	path  = @images[index]
	redirect 404 unless File.readable?(path)
	content_type 'image/jpeg'
	send_file open(path, type: 'image/jpeg', disposition: 'inline')
end

Run with ruby server.rb then use URLs of the form http://localhost:4567/image?index=123.