Class: ActiveRecordStreamer

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

Instance Method Summary collapse

Constructor Details

#initialize(args = {}) ⇒ ActiveRecordStreamer

Returns a new instance of ActiveRecordStreamer.



4
5
6
7
8
9
# File 'lib/active-record-streamer.rb', line 4

def initialize(args = {})
  @args = args
  @klass = args[:query].klass
  @sql = @args[:query].to_sql
  @includes = @args[:query].includes_values
end

Instance Method Details

#each(&blk) ⇒ Object



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
# File 'lib/active-record-streamer.rb', line 15

def each(&blk)
  if @klass.respond_to?(:connection_without_octopus)
    @baza_db = Baza::Cloner.from_active_record_connection(@klass.connection_without_octopus)
  else
    @baza_db = Baza::Cloner.from_active_record_connection(@klass.connection)
  end

  begin
    cache = []

    @baza_db.query_ubuf(@sql) do |data|
      model = @klass.new

      if rails4?
        model.assign_attributes(data)
        model.instance_variable_set(:@new_record, false)
      else
        model.instance_variable_set(:@new_record, false)
        model.instance_variable_set(:@attributes, data.stringify_keys!)
      end

      cache << model

      if cache.length >= 1000
        yield_cache(cache, &blk)
        cache = []
      end
    end

    yield_cache(cache, &blk) if cache.any?
  ensure
    @baza_db.destroy
  end
end

#rails4?Boolean

Returns:

  • (Boolean)


11
12
13
# File 'lib/active-record-streamer.rb', line 11

def rails4?
  @@rails4 ||= ActiveRecord::VERSION::STRING.start_with?('4')
end