Method: Sohm::Model#refresh_indices

Defined in:
lib/sohm.rb

#refresh_indicesObject

Refresh model indices



1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
# File 'lib/sohm.rb', line 1115

def refresh_indices
  memo_key = key["_indices"]
  # Add new indices first
  commands = fetch_indices.each_pair.map do |field, vals|
    vals.map do |val|
      index_key = model.key["_indices"][field][val]
      [["SADD", memo_key, index_key], ["SADD", index_key, id]]
    end
  end.flatten(2)

  model.synchronize do
    commands.each do |command|
      redis.queue(*command)
    end
    redis.commit
  end

  # Remove old indices
  index_set = ::Set.new(redis.call("SMEMBERS", memo_key))
  # Here we are fetching the latest model to avoid concurrency issue
  valid_list = model[id].send(:fetch_indices).each_pair.map do |field, vals|
    vals.map do |val|
      model.key["_indices"][field][val]
    end
  end.flatten(1)
  valid_set = ::Set.new(valid_list)
  diff_set = index_set - valid_set
  if diff_set.size > 0
    diff_list = diff_set.to_a
    commands = diff_list.map do |key|
      ["SREM", key, id]
    end + [["SREM", memo_key] + diff_list]

    model.synchronize do
      commands.each do |command|
        redis.queue(*command)
      end
      redis.commit
    end
  end
  true
end