Re: How to make a per-request variable globally available?

Chris Kampmeier
2007-02-08T18:39:58Z

Aaron wrote:
> You can use Thread.current to pass data to your models.  Something
> like this:
>
> def initialize_site
>   @site = Site.find_by_domain(request.domain)
>   Thread.current[:site] = @site
> end

Thank you, that''s exactly what I needed.

After I did that I extended ActiveRecord.Base::find to put my conditions
in at the highest level:

class Site < ActiveRecord::Base
  def Site.current
    Thread.current[:site]
  end
end

class Widget < ActiveRecord::Base
  class << self
    # keep a pointer to the old find
    alias :find_without_site :find

    # extend find to always return widgets for the current site
    def find(*args)
      self.with_scope(:find => {:conditions => {:site_id =>
Site.current.id}}) do
        self.find_without_site(*args)
      end
    end
  end
end


And it''s amazing. All unnecessary references to the site are gone from
my controllers, and even the other models. Thanks again!