Подтвердить что ты не робот

Маршрутизация на статическую страницу html в/public

Как я могу маршрутизировать /foo для отображения /public/foo.html в Rails?

4b9b3361

Ответ 1

Вы можете сделать это:

Добавьте это в свой файл routes.rb.

match '/foo', :to => redirect('/foo.html')

Обновление

В Rails 4 он должен использовать "get", а не "match":

get '/foo', :to => redirect('/foo.html')

спасибо Грант Бирчмайер

Ответ 2

Это можно сделать без запуска перенаправления. Следуйте дальнейшим шагам, чтобы иметь возможность маршрутизировать статические файлы в config/routes.rb, как показано в этом примере:

# This route will serve public/index.html at the /login URL 
# path, and have a URL helper named `login_path`:
get "/login", to: static("index.html")

# This route will serve public/register.html at the /register
# URL path, and have URL helper named `new_user_registration_path`:
get "/register", to: static("register.html"), as: :new_user_registration
  • Создайте config/initializers/static_router.rb со всем содержимым файла, показанного в конце этого ответа. Убедитесь, что вы переключаете комментарии для строк, относящихся к вашей версии Rails в приложении.
  • Перезагрузите приложение (сначала bin/spring stop, чтобы убедиться, что приложение полностью перезагружено).
  • Начните использование метода static(path) в config/routes.rb.

# File: config/initializers/static_router.rb
module ActionDispatch
  module Routing
    class StaticResponder < Endpoint

      attr_accessor :path, :file_handler

      def initialize(path)
        self.path = path
        # Only if you're on Rails 5+:
        self.file_handler = ActionDispatch::FileHandler.new(
          Rails.configuration.paths["public"].first
        )
        # Only if you're on Rails 4.2:
        # self.file_handler = ActionDispatch::FileHandler.new(
        #   Rails.configuration.paths["public"].first,
        #   Rails.configuration.static_cache_control
        # )
      end

      def call(env)
        env["PATH_INFO"] = @file_handler.match?(path)
        @file_handler.call(env)
      end

      def inspect
        "static('#{path}')"
      end

    end

    class Mapper
      def static(path)
        StaticResponder.new(path)
      end
    end
  end
end

Источник: https://github.com/eliotsykes/rails-static-router