require 'mongo' class GridfsController < ActionController::Metal def serve gridfs_path = env["PATH_INFO"].gsub("/gridfs/", "") gridfs_file = Mongo::GridFileSystem.new(Mongoid.database).open(gridfs_path, 'r') rescue nil if gridfs_file self.response_body = gridfs_file.read self.content_type = gridfs_file.content_type else serve_rescue(gridfs_path.split('/').pop) end end def serve_images gridfs_path = env["PATH_INFO"] serve_rescue(gridfs_path.split('/').pop) end def serve_rescue(file_name) referer = request.env['HTTP_REFERER'] if referer.include?('admin') page = Page.find(referer.split('/').pop) else vars = request.env['HTTP_REFERER'].split('/') names = get_names(vars, []) page = Page.find_by_name(names.pop) names.reverse_each do |name| page = page.children.find_by_name(name) end end image = page.design.images.detect{|i| i.file_filename == file_name} gridfs_path = image.file.url.gsub("/gridfs/", "") begin gridfs_file = Mongo::GridFileSystem.new(Mongoid.database).open(gridfs_path, 'r') self.response_body = gridfs_file.read self.content_type = gridfs_file.content_type rescue self.status = :file_not_found self.content_type = 'text/plain' self.response_body = '' end end def get_names(vars, names) page = Page.all(:conditions => {:name => vars.last}) names << vars.pop if page.count > 1 get_names(vars, names) else names end end end