Skip to content

Instantly share code, notes, and snippets.

@sgrif
Created December 22, 2014 22:57
Show Gist options
  • Save sgrif/0e5d72e50af20e8ea788 to your computer and use it in GitHub Desktop.
Save sgrif/0e5d72e50af20e8ea788 to your computer and use it in GitHub Desktop.
diff --git a/activerecord/lib/active_record/core.rb b/activerecord/lib/active_record/core.rb
index d957bd1..60d3002 100644
--- a/activerecord/lib/active_record/core.rb
+++ b/activerecord/lib/active_record/core.rb
@@ -130,7 +130,7 @@ module ActiveRecord
return super if ids.first.kind_of?(Symbol)
return super if block_given? ||
primary_key.nil? ||
- default_scopes.any? ||
+ !default_scopes.all?(&:cacheable?) ||
current_scope ||
columns_hash.include?(inheritance_column) ||
ids.first.kind_of?(Array)
@@ -161,7 +161,7 @@ module ActiveRecord
def find_by(*args)
return super if current_scope || !(Hash === args.first) || reflect_on_all_aggregations.any?
- return super if default_scopes.any?
+ return super unless default_scopes.all?(&:cacheable?)
hash = args.first
diff --git a/activerecord/lib/active_record/scoping/default.rb b/activerecord/lib/active_record/scoping/default.rb
index 18190cb..27a540f 100644
--- a/activerecord/lib/active_record/scoping/default.rb
+++ b/activerecord/lib/active_record/scoping/default.rb
@@ -82,6 +82,9 @@ module ActiveRecord
# end
def default_scope(scope = nil)
scope = Proc.new if block_given?
+ def scope.cacheable?
+ false
+ end
if scope.is_a?(Relation) || !scope.respond_to?(:call)
raise ArgumentError,
@@ -94,6 +97,15 @@ module ActiveRecord
self.default_scopes += [scope]
end
+ def cached_default_scope(scope = nil)
+ scope = Proc.new if block_given?
+ def scope.cacheable?
+ true
+ end
+
+ self.default_scopes += [scope]
+ end
+
def build_default_scope(base_rel = relation) # :nodoc:
if !Base.is_a?(method(:default_scope).owner)
# The user has defined their own default scope method, so call that
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment