Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #
- # The Scope class allows you to easily stack more than one scope on top
- # of a ActiveRecord::Base class.
- class Scope
- def initialize(klass, scope=nil)
- @klass = klass
- @scopes = []
- @joins = []
- add(scope) if scope
- end
- def joins(s); add(:joins => s); end
- def conditions(s); add(:conditions => s); end
- def include(s); add(:include => s); end
- def find(*opts)
- exec(0) { @klass.find *prepare_find_options(*opts) }
- end
- def count(*opts)
- exec(0) { @klass.count *prepare_find_options(*opts) }
- end
- private
- def add(scope)
- scope = scope.dup
- if joins = scope[:joins]
- @joins << scope.delete(:joins)
- end
- @scopes << { :find => scope }
- self
- end
- def exec(i)
- if i == @scopes.length
- yield
- else
- @klass.with_scope(@scopes[i]) do
- exec(i+1) { yield }
- end
- end
- end
- def prepare_find_options(*opts)
- hash = opts.last.is_a?(Hash) ? opts.pop.dup : {}
- joins = ([ hash.delete(:joins) ] + @joins).compact
- hash.update(:joins => joins.join(" ")) unless joins.empty?
- opts.push hash
- opts
- end
- end
Add Comment
Please, Sign In to add comment