Sha256: 3046b2320647f1acde4dfd408a20f708ccbec5e5e39e30fe43c02af15e4f1c83

Contents?: true

Size: 1.07 KB

Versions: 1

Compression:

Stored size: 1.07 KB

Contents

require 'active_record'

# Multitenant: making cross tenant data leaks a thing of the past...since 2011
module Multitenant
  class << self
    attr_accessor :current_tenant

    # execute a block scoped to the current tenant
    # unsets the current tenant after execution
    def with_tenant(tenant, &block)
      Multitenant.current_tenant = tenant
      yield
    ensure
      Multitenant.current_tenant = nil
    end
  end

  module ActiveRecordExtensions
    # configure the current model to automatically query and populate objects based on the current tenant
    # see Multitenant#current_tenant
    def belongs_to_multitenant(association = :tenant)
      reflection = reflect_on_association association
      before_validation Proc.new {|m|
        m.send("#{association}=".to_sym, Multitenant.current_tenant) if Multitenant.current_tenant
      }, :on => :create
      default_scope lambda {
        where({reflection.foreign_key => Multitenant.current_tenant.id}) if Multitenant.current_tenant
      }
    end
  end
end
ActiveRecord::Base.extend Multitenant::ActiveRecordExtensions

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
multitenant-0.4.1 lib/multitenant.rb