2011-05-16 115 views
0

我有一个博客工厂这样的配置:如何在请求之前设置动态变量?

- 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?)。

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

回答

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 

现在你知道路线将永远匹配。当然,你仍然需要知道要展示哪个博客。这很容易在ApplicationController做一个before_filter

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对象,告诉你哪个博客是,渲染时,它也提供了意见。

-1

你应该使用全局变量。但在使用它时要小心。用普通的地方初始化它,这样你就可以随时改变它。像

- 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 
+0

不要使用全局变量,它会打破轨道的无状态并导致一次运行多个应用程序的实例(如生产时)的复杂情况。 – 2011-05-16 15:48:27

相关问题