Module: Rails3Finders

Defined in:
lib/fake_arel/rails_3_finders.rb

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/fake_arel/rails_3_finders.rb', line 3

def self.included(base)
  base.class_eval do

    # the default named scopes
    named_scope :offset, lambda {|offset| {:offset => offset}}
    named_scope :limit, lambda {|limit| {:limit => limit}}
    named_scope :includes, lambda { |*includes| { :include => includes }}
    named_scope :order, lambda {|*order| {:order => order.flatten.join(',') }}
    named_scope :joins, lambda {|*join| {:joins => join } if join[0]}
    named_scope :from, lambda {|*from| {:from => from }}
    named_scope :having, lambda {|*having| {:having => having }}
    named_scope :group, lambda {|*group| {:group => group.flatten.join(',') }}
    named_scope :readonly, lambda {|readonly| {:readonly => readonly }}
    named_scope :lock, lambda {|lock| {:lock => lock }}

    def self.select(value = Proc.new)
      if block_given?
        all.select {|*block_args| value.call(*block_args) }
      else
        self.scoped(:select => Array.wrap(value).join(','))
      end
    end

    __where_fn = lambda do |*where|
      if where.is_a?(Array) and where.size == 1
        {:conditions => where.first}
      else
        {:conditions => where}
      end
    end

    named_scope :where, __where_fn

    __or_fn = lambda do |*scopes|
      where = []
      joins = []
      includes = []

      # for some reason, flatten is actually executing the scope
      scopes = scopes[0] if scopes.size == 1
      scopes.each do |s|
        s = s.proxy_options
        begin
          where << merge_conditions(s[:conditions])
        rescue NoMethodError
          # I am ActiveRecord::Base. Only my subclasses define merge_conditions:
          where << subclasses.first.merge_conditions(s[:conditions])
        end
        #where << merge_conditions(s[:conditions])
        joins << s[:joins] unless s[:joins].nil?
        includes << s[:include] unless s[:include].nil?
      end
      scoped = self
      scoped = scoped.includes(includes.uniq.flatten) unless includes.blank?
      scoped = scoped.joins(joins.uniq.flatten) unless joins.blank?
      scoped.where(where.join(" OR "))
    end
    named_scope :or, __or_fn

    def self.fakearel_find_each(options = {:batch_size => 1000}, &block)
      count = self.scoped({}).count
      offset = 0
      while offset < count
        self.scoped(:limit => options[:batch_size], :offset => offset).each { |entry| yield entry }
        offset += options[:batch_size]
      end
    end

    def self.fakearel_destroy
      self.destroy_all(:id => self.scoped({}).select(:id).map(&:id))
    end
  end
end