如何配置Rails以访问不在其传统目录位置的媒体资源?

pep*_*epe 2 routing routes ruby-on-rails convention-over-configur

假设我的图像不在正常位置:

{appname}/public/images/unconventional.gif
Run Code Online (Sandbox Code Playgroud)

但是在这里:

{appname}/unconventional.gif
Run Code Online (Sandbox Code Playgroud)

我理解这完全违反了Rails惯例,是不道德的,在任何情况下你都不应该这样做,而且,为什么我甚至会提出这样一个愚蠢的事情呢?

好吧,既然我们已经开始使用它,假设我在Windows上,因此符号链接是不可能的,如何设置它?

mol*_*olf 6

Rails不提供这些图像,它让Web服务器可以做到这一点.您最好更改Web服务器的配置以处理此方案.Apache例如,如果您使用它,则设置相当容易mod_rewrite.

使导轨为这些图像将是丑陋,但它如果你提供你的路线可能routes.rb是匹配/public/images/unconventional.gif的,如果文件本身不存在.例如:

map.connect "public/images/unconventional.gif",
  :controller => "static_image_controller",
  :action => "serve"
Run Code Online (Sandbox Code Playgroud)

然后创建一个控制器StaticImageController:

class StaticImageController < ApplicationController
  def serve
    image = File.read(File.join(Rails.root, "unconventional.gif"))
    send_data image, :type => "image/gif", :disposition => "inline"
  end
end
Run Code Online (Sandbox Code Playgroud)

警告:如果您使用上述概念,请注意,如果您使用URL中的输入来决定要提供哪个文件(params[:file]例如),则需要彻底清理输入,因为您有冒险将整个文件系统暴露给外面的世界.