Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make the Active Record Locator use unscoped if it responds to it. #73

Merged
merged 1 commit into from
Aug 4, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions lib/global_id/locator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,9 @@ def use(app, locator = nil, &locator_block)

private
def locator_for(gid)
@locators.fetch(normalize_app(gid.app)) { default_locator }
@locators.fetch(normalize_app(gid.app)) do
gid.model_class.respond_to?(:unscoped) ? UNSCOPED_LOCATOR : DEFAULT_LOCATOR
end
end

def find_allowed?(model_class, only = nil)
Expand All @@ -125,7 +127,7 @@ def normalize_app(app)
private
@locators = {}

class ActiveRecordFinder
class DefaultLocator
def locate(gid)
gid.model_class.find gid.model_id
end
Expand All @@ -149,8 +151,19 @@ def find_records(model_class, ids, options)
end
end
end
DEFAULT_LOCATOR = DefaultLocator.new

class UnscopedLocator < DefaultLocator
def locate(gid)
gid.model_class.unscoped { super }
end

mattr_reader(:default_locator) { ActiveRecordFinder.new }
private
def find_records(model_class, ids, options)
model_class.unscoped { super }
end
end
UNSCOPED_LOCATOR = UnscopedLocator.new

class BlockLocator
def initialize(block)
Expand Down
17 changes: 17 additions & 0 deletions test/cases/global_locator_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -248,3 +248,20 @@ def with_app(app)
GlobalID.app = old_app
end
end

class ScopedRecordLocatingTest < ActiveSupport::TestCase
setup do
@gid = Person::Scoped.new('1').to_gid
end

test "by GID with scoped record" do
found = GlobalID::Locator.locate(@gid)
assert_kind_of @gid.model_class, found
assert_equal @gid.model_id, found.id
end

test "by many with scoped records" do
assert_equal [ Person::Scoped.new('1'), Person::Scoped.new('2') ],
GlobalID::Locator.locate_many([ Person::Scoped.new('1').to_gid, Person::Scoped.new('2').to_gid ])
end
end
16 changes: 16 additions & 0 deletions test/models/person.rb
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,20 @@ def ==(other)
end
end

class Person::Scoped < Person
def initialize(*)
super
@find_allowed = false
end

def self.unscoped
@find_allowed = true
yield
end

def self.find(*)
super if @find_allowed
end
end

class Person::Child < Person; end