2012-06-08 54 views
0

我有一个服务于多个域的Rails 2应用程序。也就是说,http://domainA.comhttp://domainB.com都由相同的Rails应用程序提供服务。当我手动启动这些功能时,我通过传递site变量来指定要查看的网站:site=domainB ruby script/server是否可以使用.powrc文件根据所访问的URL将会话变量传递给Rails?

我想使用战俘,这样我可以通过http://domainA.myapp.devhttp://domainB.myapp.dev访问这两个网站(我也很乐意与http://domainA.devhttp://domainB.dev如果这是更容易)。

我可以通过添加export site="domainB".powrc文件中手动做到这一点,和编辑,通过手(然后做touch tmp/restart.txt)我想改用网站每一次...我喜欢的东西多一点自动,虽然。我正在考虑类似.powrc文件中的subdomain == domainA ? export site="domainA" : export site="domainB"

回答

0

我想通了,如何做到这一点,并且写了关于它here博客文章。这是它如何完成的要点...

我配置了我的before_filter以获取被访问的域名,并在整个Rails应用中使用该域名。如果该网站是通过标准的Rails应用程序访问的,它将不会有域名(它只是localhost)。在这种情况下,before_filter会查找在命令行中传递的site变量(如果没有通过,那么它将使用默认站点)。

def set_site 
    if RAILS_ENV == "development" 
    session[:site] = case request.domain 
     when "domainA.dev" then "domainA" 
     when "domainB.dev" then "domainB" 
     else ENV['site'] || "domainA" 
    end 
    else session[:site].blank? 
    if RAILS_ENV == "staging" 
     session[:site] = case request.subdomains.last # *.yourstagingdomain.com 
     when "domainA" then "domainA" 
     when "domainB" then "domainB" 
     end 
    elsif RAILS_ENV == "production" 
     session[:site] = case request.domain 
     when "domainA.com" then "domainA" 
     when "domainB.com" then "domainB" 
     else "domainA" 
     end 
    else 
     session[:site] = "domainA" # default 
    end 
    end 
    if @site.nil? 
    @site ||= Site.find_by_name(session[:site]) 
    end 
end 

整个事情实际上是Rails内部本身完成,而战俘拥有国内唯一的参与是必须有由Rails应用程序被服务的每个站点的一个符号链接。

符号链接还必须匹配在before_filter中检查的request.domain。因此,在这个例子中会有两个符号链接 - domainAdomainB

0

我已经写了下面的rake任务,以切换网站rake pow[SITENAME],直到我能找到一个更自动化的解决方案。此代码也可作为Gist提供。

desc "Switches site that Pow serves" 
task :pow, :site_name do |t, args| 
    pow_config = "#{Rails.root}/.powrc" 
    args.with_defaults(:site_name => "domainA") 

    # Overwrite .powrc file with new site name 
    file = File.open(pow_config, 'w') 
    file.write "if [ -f \"$rvm_path/scripts/rvm\" ] && [ -f \".rvmrc\" ]; then 
source \"$rvm_path/scripts/rvm\" 
source \".rvmrc\" 
fi 

export site=#{args.site_name}" 
    file.close 

    # Restart Pow 
    FileUtils.touch "#{Rails.root}/tmp/restart.txt" 

    # Announce site change 
    puts "Switched to #{args.site_name}" 
end 
相关问题