0

I have a configuration of a blog factory like this :

- 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

But I also want to use fully domain names like this :

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

I host a lot of blogs and there is a lot of domain names also, so I cannot do a per case treatment.

I am thinking using before_dispatch (http://m.onkey.org/dispatcher-callbacks) to set up a dynamic blog name and use dynamically a path variable in the routes.rb. I was thinking of a global var but it seems a bad idea (Why aren't global (dollar-sign $) variables used?).

Do you think it's a good idea ? What is the best way to store the blog name during the request ?

Community
  • 1
  • 1
Hartator
  • 5,029
  • 4
  • 43
  • 73

2 Answers2

1

You don't need to handle it before the request. You have two types of urls: blogcrea.com/[blogname]/[other params] and [customdomain]/[other params]

The best way to handle this is with two sets of routes depending on the domain:

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

Matcher for common domain:

module CheckIfBlogCrea

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

end

Now you know the routes will always match. Ofcourse you still have to know which blog to show. This can easily be done in the ApplicationController with a 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

Now in your actions you'll have the @blog object that tells you which blog it is, it's also available in the views when rendering.

Stefaan Colman
  • 3,715
  • 2
  • 22
  • 11
-1

you should use global variable.but take care during using it.initialize it with common place so you can change it whenever you require. like

- 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
Hitesh
  • 815
  • 1
  • 6
  • 11
  • Don't use globals, it breaks the statelessness of rails and causes complications when you have multiple instances of your app running at once (like you would on production). – Max Williams May 16 '11 at 15:48