Creating a rails route to an external URL

前端 未结 4 1391
一向
一向 2020-11-30 05:41

A lot of my users keep going to http://(rails app URL)/blog, but I don\'t actually have a blog. I finally setup a Posterous blog and now want to direct my users

4条回答
  •  遥遥无期
    2020-11-30 06:08

    Emulate frontend routes as regular Rails controller routes

    Background : at the beginning there was Rails monolith rendering html view. Then came a frontend React app, and the need to convert the backend to a JSON api, and generate URLs (mostly in emails) pointing to a frontend app that behaves almost exactly like a Rails controller.

    I was looking for a way to mimick the rails resource way to construct URL but to point instead to a frontend URL and generate appropriate path_helpers, that could be used easily with my app, RSpec, cucumber/Capybara, and everything else. I found this hack around routes to emulate frontend routes, which also requires an extra param to be passed to completely desambiguate frontend VS backend routes (useful in capybara testing)

    frontend_scope = {
      as: :frontend,
      host: Rails.configuration.frontend_host, # like https://www.example.com
      port: Rails.configuration.frontend_port, # 443
      constraints: (lambda { |request| request.params[:app] == :frontend })
    }
    scope(frontend_scope) do
      root to: 'static_pages_controller#home'
      resources :articles, only: [:show, :index]
    end
    

    Then in my Ruby code I can use

    frontend_article_url(@article, app: :frontend)
    frontend_articles_url(app: :frontend)
    ... (and everything that can be generated in a classic rails app)
    

    The inconvenient is that there will be a app parameter in your redirection, that you would have to ignore on your frontend app + all other web apps like Google Analytics, Search engine, etc*.

    * the problem being, if you have both a /articles on your frontend and a /articles on your backend, your app will not be able to make the difference with both routes that resolve to the same URL without the help from an extra param

提交回复
热议问题