lib/milia/base.rb in milia-0.3.2 vs lib/milia/base.rb in milia-0.3.7

- old
+ new

@@ -13,10 +13,13 @@ # acts_as_tenant -- makes a tenanted model # Forces all references to be limited to current_tenant rows # ------------------------------------------------------------------------ def acts_as_tenant() attr_protected :tenant_id + belongs_to :tenant + validates_presence_of :tenant_id + default_scope lambda { where( "#{table_name}.tenant_id = ?", Thread.current[:tenant_id] ) } # ..........................callback enforcers............................ before_save do |obj| # force tenant_id to be correct for current_user obj.tenant_id = Thread.current[:tenant_id] @@ -41,10 +44,12 @@ # acts_as_universal -- makes a univeral (non-tenanted) model # Forces all reference to the universal tenant (nil) # ------------------------------------------------------------------------ def acts_as_universal() attr_protected :tenant_id + belongs_to :tenant + default_scope where( "#{table_name}.tenant_id IS NULL" ) # ..........................callback enforcers............................ before_save do |obj| # force tenant_id to be universal raise ::Control::InvalidTenantAccess unless obj.tenant_id.nil? @@ -103,9 +108,28 @@ old_tenant.users.clear # remove all users from this tenant true end # before_destroy do end + +# ------------------------------------------------------------------------ +# where_restrict_tenant -- gens tenant restrictive where clause for each klass +# NOTE: subordinate join tables will not get the default scope by Rails +# theoretically, the default scope on the master table alone should be sufficient +# in restricting answers to the current_tenant alone .. HOWEVER, it doesn't feel +# right. adding an additional .where( where_restrict_tenants(klass1, klass2,...)) +# for each of the subordinate models in the join seems like a nice safety issue. +# ------------------------------------------------------------------------ + def where_restrict_tenant(*args) + args.map{|klass| "#{klass.table_name}.tenant_id = #{Thread.current[:tenant_id]}"}.join(" AND ") + end + +# ------------------------------------------------------------------------ +# ------------------------------------------------------------------------ + +# ------------------------------------------------------------------------ +# ------------------------------------------------------------------------ + # ------------------------------------------------------------------------ # ------------------------------------------------------------------------ end # module ClassMethods # ############################################################################# \ No newline at end of file