0

I got a sw.js file generated by offline-plugin in 'app/public/packs/'.
I have to respond to a GET to /sw.js with app/public/packs/sw.js.
No redirect_to, I have to serve it from there to have the service worker controlling the root scope.

How do I write a controller to respond to localhost/sw.js with the content from localhost/packs/sw.js?

lellefood
  • 1,885
  • 3
  • 18
  • 40

1 Answers1

2

You can use the send_file from the controller action like here :

def your_action 
  send_file("#{Rails.root}/app/public/packs/sw.js",
            :filename => "sw.js",
            :type => "application/javascript")
end

I'm not 100% sure on the mime type, it's either text/javascript or application/javascript

Máté
  • 2,294
  • 3
  • 18
  • 25
  • This is a good answer but now I realized that my problem wasn't the controller but the routes. In my `routes.rb` i've added `get '/sw' => 'sw#show'` but: `GET localhost/sw.js` gives No route matches [GET] "/sw.js" But `GET localhost/sw` return the correct file. What should I change? – lellefood Feb 07 '18 at 10:08
  • @lellefood You can add something like the [respond_to and format](https://stackoverflow.com/questions/30600864/rails-respond-to-blocks-and-format) block – Máté Feb 07 '18 at 10:17