Class: Neoid::Batch

Inherits:
Object
  • Object
show all
Defined in:
lib/neoid/batch.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}, &block) ⇒ Batch

Returns a new instance of Batch.



23
24
25
26
27
28
29
30
31
32
33
# File 'lib/neoid/batch.rb', line 23

def initialize(options={}, &block)
  if options.respond_to?(:call) && !block
    block = options
    options = {}
  end

  options.reverse_merge!(self.class.default_options)

  @options = options
  @block = block
end

Class Method Details

.current_batchObject



11
12
13
# File 'lib/neoid/batch.rb', line 11

def self.current_batch
  Thread.current[:neoid_current_batch]
end

.current_batch=(batch) ⇒ Object



15
16
17
# File 'lib/neoid/batch.rb', line 15

def self.current_batch=(batch)
  Thread.current[:neoid_current_batch] = batch
end

.default_optionsObject



7
8
9
# File 'lib/neoid/batch.rb', line 7

def self.default_options
  @default_options ||= { batch_size: 200, individual_promises: true }
end

.reset_current_batchObject



19
20
21
# File 'lib/neoid/batch.rb', line 19

def self.reset_current_batch
  Thread.current[:neoid_current_batch] = nil
end

Instance Method Details

#<<(command) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/neoid/batch.rb', line 35

def <<(command)
  commands << command

  if commands.length >= @options[:batch_size]
    flush_batch
  end

  if @options[:individual_promises]
    promise = SingleResultPromiseProxy.new(command)
    thens << promise
    promise
  end
end

#commandsObject



49
50
51
# File 'lib/neoid/batch.rb', line 49

def commands
  @commands ||= []
end

#countObject



57
58
59
# File 'lib/neoid/batch.rb', line 57

def count
  @commands ? @commands.count : 0
end

#default_options=(value) ⇒ Object



3
4
5
# File 'lib/neoid/batch.rb', line 3

def default_options=(value)
  @default_options = value
end

#resultsObject



61
62
63
# File 'lib/neoid/batch.rb', line 61

def results
  @results ||= []
end

#runObject



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/neoid/batch.rb', line 65

def run
  self.class.current_batch = self

  begin
    @block.call(self)
  ensure      
    self.class.reset_current_batch
  end

  Neoid.logger.info "Neoid batch (#{commands.length} commands)"

  flush_batch

  BatchPromiseProxy.new(results)
end

#thensObject



53
54
55
# File 'lib/neoid/batch.rb', line 53

def thens
  @thens ||= []
end