1

I am trying to use asset_path in my controller to generate the path for a pdf that is placed in my assets/data/ directory. Is this obsolete in Rails 4?

Here is my controller code that throws the error:

  def beg_1
    File.open(asset_path("ee-beg-1.pdf"), 'r') do |f|
      send_data f.read.force_encoding('BINARY'), :filename => "ee-beg-1.pdf", :type => "application/pdf"
    end
  end  
Thalatta
  • 4,510
  • 10
  • 48
  • 79
  • maybe it needs to be wrapped in a string like this? `"#{asset_path('ee-beg-1.pdf')}"` – Thalatta Dec 19 '14 at 23:35
  • @NielsB. you are right, asset_path returns a string, which is what File.open() takes for the `filename` param: http://ruby-doc.org/core-2.1.4/File.html#method-c-open – Thalatta Dec 19 '14 at 23:38
  • 2
    Change to `File.open('app/assets/data/ee-beg-1.pdf')` – Niels B. Dec 19 '14 at 23:38
  • Ça marche! Do you happen to know how instead of downloading the PDF how it can be viewed in the browser? Sorry this is a different question, so I understand if you have no desire to answer that here. – Thalatta Dec 19 '14 at 23:40
  • 1
    On a side note, I would strongly advise against serving downloadable content for your site/app in the assets directory. Assets directory has a special purpose in Rails applications, it is not just a file store. I would recommend serving downloads from a sub-directory inside lib. – tagCincy Dec 20 '14 at 05:23

1 Answers1

5

asset_path is a view helper. It is not obsolete in Rails 4.

See #asset_path at http://api.rubyonrails.org.

This similar Question and Answer should provide a solution for you:

Access Asset Path from Rails Controller

Community
  • 1
  • 1
sealocal
  • 10,897
  • 3
  • 37
  • 50