Module: Elastictastic::OptimisticLocking::ClassMethods

Defined in:
lib/elastictastic/optimistic_locking.rb

Instance Method Summary collapse

Instance Method Details

#create_or_update(*ids, &block) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/elastictastic/optimistic_locking.rb', line 9

def create_or_update(*ids, &block)
  scope = current_scope
  ids.each do |id|
    begin
      new.tap do |instance|
        instance.id = id
        yield instance
      end.create do |e|
        case e
        when nil # chill
        when Elastictastic::ServerError::DocumentAlreadyExistsEngineException,
          Elastictastic::ServerError::DocumentAlreadyExistsException # 0.19+
          scope.update(id, &block)
        else
          raise e
        end
      end
    rescue Elastictastic::CancelSave
      # Do Nothing
    end
  end
end

#update(*ids, &block) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/elastictastic/optimistic_locking.rb', line 32

def update(*ids, &block)
  [].tap do |found|
    case ids.length
    when 0 then return []
    when 1
      id = ids.first
      instance = scoped({}).find_one(id, :preference => '_primary_first')
      return [] unless instance
      found << id
      instances = [instance]
    else
      instances = scoped({}).
        find_many(ids, :preference => '_primary_first')
      found.concat(instances.map { |instance| instance.id })
    end
    instances.each do |instance|
      instance.try_update(current_scope, &block)
    end
  end
end

#update_each(&block) ⇒ Object



59
60
61
# File 'lib/elastictastic/optimistic_locking.rb', line 59

def update_each(&block)
  all.each { |instance| instance.try_update(current_scope, &block) }
end

#update_or_create(*ids, &block) ⇒ Object



53
54
55
56
57
# File 'lib/elastictastic/optimistic_locking.rb', line 53

def update_or_create(*ids, &block)
  updated_ids = update(*ids, &block)
  create_ids = ids - updated_ids
  create_or_update(*create_ids, &block) if create_ids.any?
end