Class: ActiveRecord::OnDemand::FastEnumeration

Inherits:
Object
  • Object
show all
Defined in:
lib/ar-ondemand/fast_enumeration.rb

Instance Method Summary collapse

Constructor Details

#initialize(model, result_set) ⇒ FastEnumeration

Returns a new instance of FastEnumeration.



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
# File 'lib/ar-ondemand/fast_enumeration.rb', line 4

def initialize(model, result_set)
  @result_set = result_set
  @column_models = model.columns.inject({}) { |h, c| h[c.name] = c; h }
  result_set.columns.each_with_index do |name, index|
    column_model = @column_models[name]

    # For AR 5.x type casting
    ar_type = (column_model.type.is_a?(::Symbol) ?
                   ActiveRecord::Type.registry.lookup(column_model.type) :
                   column_model.type) if column_model && defined?(ActiveRecord::Type.registry.lookup)
    self.define_singleton_method(name) do
      raise 'Not accessible outside of enumeration' if @row.nil?
      if column_model.respond_to?(:type_cast)
        # TODO Remove this when dropping support for Rails 3
        column_model.type_cast @row[index]
      elsif column_model.respond_to?(:type_cast_from_database)
        # Rails 4.2 renamed type_cast into type_cast_from_database
        # This is not documented in their upgrade docs or release notes.
        # See https://github.com/rails/rails/commit/d24e640
        column_model.type_cast_from_database @row[index]
      elsif ar_type
        # Rails 5+
        ar_type.is_a?(::Symbol) ? @row[index] : ar_type.cast(@row[index])
      else
        @row[index]
      end
    end
  end
end

Instance Method Details

#eachObject



34
35
36
37
38
39
40
41
42
# File 'lib/ar-ondemand/fast_enumeration.rb', line 34

def each
  @result_set.rows.each do |r|
    @row = r
    yield(self)
    nil
  end
ensure
  @row = nil
end

#inject(inj) ⇒ Object



44
45
46
47
48
49
50
51
52
# File 'lib/ar-ondemand/fast_enumeration.rb', line 44

def inject(inj)
  @result_set.rows.each do |r|
    @row = r
    inj = yield(inj, self)
  end
  inj
ensure
  @row = nil
end

#sizeObject



54
55
56
# File 'lib/ar-ondemand/fast_enumeration.rb', line 54

def size
  @result_set.rows.size
end