ruby - Downloading Rails Assets - File-paths In Development vs Production -


i have downloads_controller.rb single download action want trigger download of file lives in folder called downloads lives in folder called download_assets have added asset paths.

- download_assets [added asset paths]    - downloads       - file_1.pdf       - file_2.pdf       ... 

i can access files in folder using:

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

in order use send_file need file system path file rather url. can path the root of rails project using rails.root, , path file using asset_path(path). however, problem because i'm in development, there no file @ path. file stored in:

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

the action:

   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 

to work in development need use following:

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

however fail in production because assets precompiled , moved assets.

my current workaround is:

   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 

is there alternative supplying different path based on environment seems fragile?

in short:

yes.

in long:

in /config/initializers create file called config.yml* set so:

config.yml:

--- ## not tab character.  3 spaces.  (in case 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 

then create file in same directory (/config/initializers/) called config.rb

config.rb:

app_config = yaml.load_file("#{rails.root}/config/initializers/config.yml") 

hop on controller:

foo_controller.rb:

      class foocontroller < applicationcontroller            def download               # ...                path_to_uploads = rails.root.to_s + app_config["#{rails.env}"]['path_to_uploads']  ## handing rails.env object, return current environment , handle selecting correct environment you.         end     end 

there excellent railscast on using yaml find environment here.

hope helps!


*please note filenames arbitrary.


Comments

Popular posts from this blog

matlab - Deleting rows with specific rules -

php - MySQLi multi_query results for later use -