是否可以使用.powrc文件根据访问的URL将会话变量传递给Rails?
我有一个Rails 2应用程序,服务于多个域。 也就是说, http://domainA.com和http://domainB.com都由相同的Rails应用程序提供服务。 当我手动启动它们时,我通过传递site
变量来指定我想要查看的site
: site=domainB ruby script/server
。
我想使用Pow,以便我可以通过http://domainA.myapp.dev和http://domainB.myapp.dev访问这两个站点(我也很高兴http://domainA.dev和http://domainB.dev如果那更容易)。
我可以手动执行此操作,将export site="domainB"
到我的.powrc
文件中,然后每次我想切换网站时手动编辑(然后执行touch tmp/restart.txt
)…我更喜欢但是更自动一点。 我在想类似于subdomain == domainA ? export site="domainA" : export site="domainB"
subdomain == domainA ? export site="domainA" : export site="domainB"
. .powrc
文件中的subdomain == domainA ? export site="domainA" : export site="domainB"
。
我已经编写了以下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
我想出了如何做到这一点,并写了一篇关于它的博客文章。 这是它如何完成的要点……
我配置了我的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本身内完成的,而Pow的唯一参与是,Rails应用程序所服务的每个站点都必须有一个符号链接。
符号链接还必须与在before_filter
中检查的request.domain
匹配。 因此,在此示例中将有两个符号链接 – domainA
和domainB
。