2011-05-16 34 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

相關問題