Rails Metal MongoDB GridFS access

I’m kind of new to Metal (and all things Rack) but this works. Just for reference.

# Allow the metal piece to run in isolation
require(File.dirname(__FILE__) + "/../../config/environment") unless defined?(Rails)
class ImageShow
 
  def self.call(env) 
    request = Rack::Request.new(env)
    if request.path_info =~ /^\/show_image\/(.+)$/
      if GridFS::GridStore.exist?(Media.database, $1)
        GridFS::GridStore.open(Media.database, $1, 'r') do |file|
          [200, {'Content-Type' => file.content_type}, [file.read]]
        end
      else
        [404, {'Content-Type' => 'text/plain'}, ['File not found.']]
      end
    else
      [404, {"Content-Type" => "text/html"}, ["Not Found"]]
    end
 end
 
end

That will need to be saved as image_show.rb. Slow .. but not as slow as doing it through a Rails controller.

Tags: ,

Leave a Reply