【问题标题】:Downloading Rails Assets - File-paths In Development vs Production下载 Rails 资产 - 开发与生产中的文件路径
【发布时间】:2013-08-10 02:04:00
【问题描述】:

我有一个 downloads_controller.rb 和一个 download 操作,我想触发下载位于名为 downloads 的文件夹中的文件,该文件夹位于名为 download_assets 的文件夹中,我已将其添加到我的资产路径。

- download_assets [Added to asset paths]
   - downloads
      - file_1.pdf
      - file_2.pdf
      ...

我可以使用以下方法成功访问文件夹中的任何文件:

http://my-app.dev/assets/downloads/file.pdf

为了使用 send_file,我需要该文件的文件系统路径而不是 URL。我可以使用Rails.root 获取Rails 项目的根路径,使用asset_path(path) 获取文件路径。但是,问题是因为我正在开发中,所以这个路径没有文件。文件存放在:

path/to/rails/project/app/assets/download_assets/downloads/file.pdf

动作:

   def download
      @download = Download.find(params[:id])
      file_path = "downloads/#{@download.filename}.pdf"
      file_path = "#{Rails.root}#{ActionController::Base.helpers.asset_path(file_path)}"
      send_file(file_path, :type=>"application/pdf", x_sendfile: true)
   end

要让它在开发中工作,我需要使用以下内容:

"#{Rails.root}/app/assets/download_assets/#{file_path}"

但是这在生产环境中会失败,因为资产将被预编译并移动到 assets。

我目前的解决方法是:

   file_path = "downloads/#{@download.filename}.pdf"
   if Rails.env == "development" || Rails.env == "test"
        file_path = "#{Rails.root}/app/assets/download_assets/#{file_path}"
    else
        file_path = "#{Rails.root}{ActionController::Base.helpers.asset_path(file_path)}"
    end

是否可以根据环境提供不同的路径,因为这看起来很脆弱?

【问题讨论】:

    标签: ruby-on-rails ruby controller download sendfile


    【解决方案1】:

    是的。

    在 /config/initializers 创建一个名为 say "config.yml" 的文件,像这样设置它:

    config.yml:

    ---
    ## NOT a tab character.  3 spaces.  (In case that affects you)                                                                                                                            
    development:
       path_to_uploads: /path/to/downloads/for/development
    
    production:
       path_to_uploads: /path/to/downloads/for/production
    
    test:
       path_to_uploads: /path/to/downloads/for/test
    

    然后在同一目录(/config/initializers/)中创建一个名为config.rb的文件

    config.rb:

    APP_CONFIG = YAML.load_file("#{Rails.root}/config/initializers/config.yml")
    

    跳到你的控制器:

    foo_controller.rb:

          class FooController < ApplicationController
               def download
                  # ... 
                  path_to_uploads = Rails.root.to_s + APP_CONFIG["#{Rails.env}"]['path_to_uploads'] 
    ## By handing it the Rails.env object, it will return the current environment and handle selecting the correct environment for you.
            end
        end
    

    有一个很棒的 RailsCast 关于使用 YAML 查找环境here.

    希望对您有所帮助!


    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      相关资源
      最近更新 更多