Ringo
Ringo

Reputation: 5483

Secondary route

I am trying to figure out the best way to define a secondary route to an asset in Rails.

For example, I have a javascript file located here:

/assets/scripts/my-script.js

But I'd like to create a new route to the same file, something like:

/api/v1/my-script.js

I tried this:

  namespace :api do
    namespace :v1 do
      resources :images, only: [:show, :create]
      match 'my-script.js', :path => '/assets/scripts/my-script.js', :via => 'get'
    end
  end

But it literally forwarded to /assets/scripts/my-script.js. I'd like to retain the new browser URL rather than get forwarded to the original path.

Upvotes: 1

Views: 64

Answers (1)

Nick Veys
Nick Veys

Reputation: 23939

I'm not sure routes can be used in such a way. If you want, you could probably make a controller that served those assets up.

This is untested, but should get the idea across.

namespace :api do
  namespace :v1 do
    resources :images, only: [:show, :create]
    get 'my-script.js', to: 'scripts#my'
  end
end

and

class Api::V1::ScriptsController < ApplicationController
  def my
    send_file ActionController::Base.helpers.javascript_path("my-script.js")
  end
end

Kinda clunky of course, could be generalized to serve any script.

Upvotes: 1

Related Questions