Class: RecordCollection

Inherits:
Object
  • Object
show all
Defined in:
lib/record-collection.rb

Instance Method Summary collapse

Constructor Details

#initialize(base_scope) ⇒ RecordCollection

Returns a new instance of RecordCollection.



4
5
6
7
# File 'lib/record-collection.rb', line 4

def initialize(base_scope)
  self.base_scope = coerce_to_relation(base_scope)
  self.scopes = Set.new
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object



43
44
45
# File 'lib/record-collection.rb', line 43

def method_missing(name, *args, &block)
  final_scope.__send__(name, *args, &block)
end

Instance Method Details

#coerce_to_relation(base_scope) ⇒ Object



9
10
11
12
13
14
15
16
17
# File 'lib/record-collection.rb', line 9

def coerce_to_relation(base_scope)
  # rails 3
  if base_scope.respond_to?(:scoped)
    base_scope.scoped
  else
    # rails 4
    base_scope.all
  end
end

#is_limited_by?(scope) ⇒ Boolean Also known as: limited_by?, is_ordered_by?

Returns:

  • (Boolean)


29
30
31
32
# File 'lib/record-collection.rb', line 29

def is_limited_by?(scope)
  # because ActiveRecord::Relations do not implement hashing correctly, we must do case by case equality
  base_scope == scope || scopes.any? { |s| s == scope }
end

#limit_by(scope = nil) ⇒ Object Also known as: and, order_by

Raises:

  • (ArgumentError)


19
20
21
22
23
24
# File 'lib/record-collection.rb', line 19

def limit_by(scope=nil)
  raise ArgumentError, "A relation or block is required" if scope.nil? && !block_given?
  scope ||= yield(base_scope)
  scopes.add(scope)
  self
end

#respond_to?(name) ⇒ Boolean

Returns:

  • (Boolean)


39
40
41
# File 'lib/record-collection.rb', line 39

def respond_to?(name)
  super || final_scope.respond_to?(name)
end