-
-
Save pgr0ss/aa95f039f48716d5e147 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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