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

Implemented very simple caching to avoid unnecessary database queries #195

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
11 changes: 8 additions & 3 deletions lib/ancestry/instance_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -152,15 +152,15 @@ def parent= parent
end

def parent_id= parent_id
self.parent = if parent_id.blank? then nil else unscoped_find(parent_id) end
self.parent = if parent_id.blank? then nil else cached_unscoped_find(parent_id) end
end

def parent_id
if ancestor_ids.empty? then nil else ancestor_ids.last end
end

def parent
if parent_id.blank? then nil else unscoped_find(parent_id) end
if parent_id.blank? then nil else cached_unscoped_find(parent_id) end
end

def parent_id?
Expand All @@ -174,7 +174,7 @@ def root_id
end

def root
if root_id == id then self else unscoped_find(root_id) end
if root_id == id then self else cached_unscoped_find(root_id) end
end

def is_root?
Expand Down Expand Up @@ -303,6 +303,11 @@ def unscoped_find id
self.ancestry_base_class.unscoped { self.ancestry_base_class.find(id) }
end

def cached_unscoped_find id
@cached_unscoped_find ||= Hash.new
@cached_unscoped_find[id] ||= unscoped_find id
end

def get_arel_table
self.ancestry_base_class.arel_table
end
Expand Down
24 changes: 23 additions & 1 deletion test/concerns/has_ancestry_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,28 @@ def test_descendants_move_with_node
end
end

def single_instance_caches_parent_calls
AncestryTestDatabase.with_model :depth => 3, :width => 3 do |model, roots|
root = roots.first
child = root.children.first
other = root.children.last

assert_same child.parent, child.parent
refute_same child.parent, other.parent
end
end

def single_instance_caches_root_calls
AncestryTestDatabase.with_model :depth => 3, :width => 3 do |model, roots|
root = roots.first
child = root.children.first
other = root.children.last

assert_same child.root, child.root
refute_same child.root, other.root
end
end

def test_setup_test_nodes
AncestryTestDatabase.with_model :depth => 3, :width => 3 do |model, roots|
assert_equal Array, roots.class
Expand All @@ -78,4 +100,4 @@ def test_setup_test_nodes
end
end
end
end
end