Rails Restful 路由和子域 [英] Rails Restful Routing and Subdomains

查看:14
本文介绍了Rails Restful 路由和子域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有任何插件或方法允许我转换资源路由,允许我将控制器名称作为子域放置.

I wondered if there were any plugins or methods which allow me to convert resource routes which allow me to place the controller name as a subdomain.

示例:

map.resources :users
map.resource :account
map.resources :blog
...

example.com/users/mark
example.com/account
example.com/blog/subject
example.com/blog/subject/edit
...

#becomes

users.example.com/mark
account.example.com
blog.example.com/subject
blog.example.com/subject/edit
...

我意识到我可以使用命名路由来做到这一点,但想知道是否有某种方法可以保持我当前简洁的 routes.rb 文件.

I realise I can do this with named routes but wondered if there were some way to keep my currently succinct routes.rb file.

推荐答案

最好的方法是编写一个简单的机架中间件库来重写请求标头,以便您的 Rails 应用程序从用户的url 没有改变的观点.这样您就不必对 Rails 应用程序(或路由文件)进行任何更改

The best way to do it is to write a simple rack middleware library that rewrites the request headers so that your rails app gets the url you expect but from the user's point of view the url doesn't change. This way you don't have to make any changes to your rails app (or the routes file)

例如机架库将重写:users.example.com => example.com/users

For example the rack lib would rewrite: users.example.com => example.com/users

这个 gem 应该完全适合你:http://github.com/jtrupiano/rack-重写

This gem should do exactly that for you: http://github.com/jtrupiano/rack-rewrite

更新代码示例

注意:这是快速编写的,完全未经测试,但应该让您走上正确的道路.另外,我还没有检查过rack-rewrite gem,这可能会使这更简单

Note: this is quickly written, totally untested, but should set you on the right path. Also, I haven't checked out the rack-rewrite gem, which might make this even simpler

# your rack middleware lib.  stick this in you lib dir
class RewriteSubdomainToPath

  def initialize(app)
    @app = app
  end

  def call(env)
    original_host = env['SERVER_NAME']
    subdomain = get_subdomain(original_host)
    if subdomain
      new_host = get_domain(original_host)
      env['PATH_INFO'] = [subdomain, env['PATH_INFO']].join('/')
      env['HTTP_X_FORWARDED_HOST'] = [original_host, new_host].join(', ')
      logger.info("Reroute: mapped #{original_host} => #{new_host}") if defined?(Rails.logger)
    end

    @app.call(env)

  end

  def get_subdomain
    # code to find a subdomain.  simple regex is probably find, but you might need to handle 
    # different TLD lengths for example .co.uk
    # google this, there are lots of examples

  end

  def get_domain
    # get the domain without the subdomain. same comments as above
  end
end

# then in an initializer
Rails.application.config.middleware.use RewriteSubdomainToPath

这篇关于Rails Restful 路由和子域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆