Rails page caching with subdomain

2019-05-25 09:36发布

问题:

Has anyone successfully implemented rails page caching with subdomains?

Right now the same file is being served up between subdomains as rails does not recognize the fact that the subdomain has changed.

I'd like my page caches to look something like this:

/public/cache/subdomain1/index.html
/public/cache/subdomain1/page2.html
/public/cache/subdomain2/index.html
/public/cache/subdomain2/page2.html

I'm using nginx for serving up these pages so will need to change it's config file to find these files once they're cached, that won't be a problem. The sticking point for me at the moment is on the rails end.

回答1:

You need to update the cache location based on which subdomain is in use.

You can add a before_filter to do this.

An example would be:

class ApplicationController < ActionController::Base
  before_filter :update_cache_location

  def update_cache_location
    if current_subdomain.present?
      ActionController::Base.page_cache_directory = "#{Rails.public_path}/cache/#{current_subdomain.directory_name}"
    end
  end
end


回答2:

I used this guy's post (with a few modifications)

class ApplicationController < ActionController::Base

  # Cache pages with the subdomain
  def cache_page(content = nil, options = nil, gzip = Zlib::BEST_COMPRESSION)
    path = [nil, request.subdomains, nil].join("/") # nil would add slash to 2 ends
    path << case options
    when Hash
      url_for(options.merge(:only_path => true, :skip_relative_url_root => true, :format => params[:format]))
    when String
      options
    else
      if request.path.empty? || request.path == '/'
        '/index'
      else
        request.path
      end
    end
    super(content, path, gzip)
  end

Then just use the usual caches_page class method.

The downfall of this is that, I need to hack the expire_page as well (which was not mentioned in the post). Also Rails won't use existing page cache if it exists, since it won't find it in the default path.