【问题标题】:How to setup dynamic variables before request?如何在请求之前设置动态变量?
【发布时间】:2011-05-16 19:31:24
【问题描述】:

我有一个这样的博客工厂配置:

- blogcrea.com/a-blog/ -> blog = a-blog
- blogcrea.com/another-blog/ -> blog = another-blog
- blogcrea.com/blog-with-custom-domain/ -> blog = blog-with-custom-domain

但我也想像这样使用完整的域名:

- www.myawsomeblog.com -> blog = blog-with-custom-domain

我托管了很多博客,也有很多域名,所以我不能按个案处理。

我正在考虑使用 before_dispatch (http://m.onkey.org/dispatcher-callbacks) 来设置动态博客名称并在 routes.rb 中动态使用路径变量。我在考虑一个全局变量,但这似乎是个坏主意(Why aren't global (dollar-sign $) variables used?)。

你认为这是个好主意吗?在请求期间存储博客名称的最佳方式是什么?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 routes cross-domain


    【解决方案1】:

    你不需要在请求之前处理它。您有两种类型的网址:blogcrea.com/[blogname]/[other params][customdomain]/[other params]

    处理此问题的最佳方法是使用两组路由,具体取决于域:

    constrains(CheckIfBlogCrea) do
        match '/:blog(/:controller(/:action(/:id)))' # Build your routes with the :blog param
    end
    
    match '/(:controller(/:action(/:id)))' # Catch the custom domain routes
    

    公共域匹配器:

    module CheckIfBlogCrea
    
        def self.matches?(request)
            request.host == 'blogcrea.com' 
        end
    
    end
    

    现在您知道路线将始终匹配。当然,您仍然必须知道要显示哪个博客。这可以通过before_filterApplicationController 中轻松完成

    class ApplicationController < ActionController::Base
    
        before_filter :load_blog
    
    
        protected
    
        def load_blog
            # Custom domain?
            if params[:blog].nil?
                @blog = Blog.find_by_domain(request.host)
            else
                @blog = Blog.find_by_slug(params[:blog])
            end
            # I recommend to handle the case of no blog found here
        end
    
    end
    

    现在,在您的操作中,您将拥有@blog 对象,该对象告诉您它是哪个博客,渲染时它也可以在视图中使用。

    【讨论】:

      【解决方案2】:

      你应该使用全局变量。但在使用它时要小心。用常用的地方初始化它,这样你就可以在需要时更改它。喜欢

      - blogcrea.com/a-blog/ -> blog = $a-blog
      - blogcrea.com/another-blog/ -> blog = $another-blog
      - blogcrea.com/blog-with-custom-domain/ -> blog = $blog-with-custom-domain
      

      【讨论】:

      • 不要使用全局变量,它会破坏 Rails 的无状态状态,并在您同时运行多个应用实例时导致复杂化(就像在生产环境中一样)。
      猜你喜欢
      • 1970-01-01
      • 2019-07-18
      • 2017-11-25
      • 1970-01-01
      • 2018-08-11
      • 1970-01-01
      • 1970-01-01
      • 2019-03-06
      • 2011-10-28
      相关资源
      最近更新 更多