Skip to content

Instantly share code, notes, and snippets.

@pnegri
Created February 24, 2011 01:19
Show Gist options
  • Save pnegri/841566 to your computer and use it in GitHub Desktop.
Save pnegri/841566 to your computer and use it in GitHub Desktop.
Trying to do a DRY multi tenancy with mongoid
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter do
# Find Account_ID by seach for a domain - NOT Refactored yet
host_id = $memcache_instance.get('hosts/' + request.host)
unless host_id
host_db_row = BimbooHost.where( :host => request.host ).one
if host_db_row
$memcache_instance.set('hosts/' + request.host, host_db_row.bimboo_account_id, 60*60)
host_id = host_db_row.bimboo_account_id
end
end
@tenant = request.host
if host_id
current_account = BimbooAccount.where( :_id => host_id ).one
BimbooAccount.current = current_account if current_account
end
render :template => 'bimboo/no_site' unless current_account
return false unless current_account
true
end
end
require "#{Rails.root}/lib/mongoid_tenancy"
class BimbooAccount
include Mongoid::Document
field :name, :type => String
class << self
def current
Thread.current[:current_account]
end
def current=(account)
Thread.current[:current_account] = account
# Reseting scope stack each time we set the current
BimbooPage.reset_scope_stack
# Need to call default scope for each model, also, model code in controller
BimbooPage.default_scope :where => { :bimboo_account_id => account._id }
end
end
end
module Mongoid
module Finders
def reset_scope_stack
scope_stack_for = Thread.current[:mongoid_scope_stack] ||= {}
scope_stack_for[object_id] = []
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment