Skip to content

Instantly share code, notes, and snippets.

@pgr0ss
Created October 3, 2013 04:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pgr0ss/aa95f039f48716d5e147 to your computer and use it in GitHub Desktop.
Save pgr0ss/aa95f039f48716d5e147 to your computer and use it in GitHub Desktop.
module ScopedFindHook
class ScopeError < StandardError; end
WHITELIST = %w[
Audit
]
def self.included(klass)
klass.class_eval do
after_find :_after_find_scoped_find_hook
end
end
def _after_find_scoped_find_hook
_ensure_merchant_is_correct
end
def _ensure_merchant_is_correct
return if WHITELIST.include?(self.class.name)
return unless RequestContext.merchant.present?
if RequestContext.active? && _not_an_intermediate_activerecord_object? && (self.merchant_id != RequestContext.merchant.id)
message = "#{self.class.name} cannot return objects scoped by the incorrect merchant. Got #{self.merchant_id}, expected #{RequestContext.merchant.pk}."
message << "\n"
message << caller.join("\n")
raise ScopeError.new(message)
end
end
def _not_an_intermediate_activerecord_object?
!self.class.column_names.include?("merchant_id") || has_attribute?(:merchant_id)
end
end
ActiveRecord::Base.send(:include, ScopedFindHook)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment