Refactor Cti::CallerId

- execute rebuild in a single transaction
- reduce queries
- DRY up code
- satisfy RuboCop
This commit is contained in:
Julian Kornberger 2016-12-02 12:09:17 +01:00
parent 2ed9ed5897
commit 13be41c844

View file

@ -16,22 +16,17 @@ module Cti
=end =end
def self.maybe_add(data) def self.maybe_add(data)
records = Cti::CallerId.where( record = find_or_initialize_by(
caller_id: data[:caller_id], caller_id: data[:caller_id],
level: data[:level], level: data[:level],
object: data[:object], object: data[:object],
o_id: data[:o_id], o_id: data[:o_id],
user_id: data[:user_id], user_id: data[:user_id],
)
return if records[0]
Cti::CallerId.create(
caller_id: data[:caller_id],
comment: data[:comment],
level: data[:level],
object: data[:object],
o_id: data[:o_id],
user_id: data[:user_id],
) )
if record.new_record?
record.comment = data[:comment]
record.save!
end
end end
=begin =begin
@ -45,28 +40,11 @@ returns
=end =end
def self.lookup(caller_id) def self.lookup(caller_id)
result = Cti::CallerId.where( where(caller_id: caller_id)
caller_id: caller_id, .group(:user_id, :id) \
level: 'known', # first known, then maybe, last others
).group(:user_id, :id).order(id: 'DESC').limit(20) .order("level != 'known', level != 'maybe', id DESC")
if !result[0] .limit(20)
result = Cti::CallerId.where(
caller_id: caller_id,
level: 'maybe',
).group(:user_id, :id).order(id: 'DESC').limit(20)
end
if !result[0]
result = Cti::CallerId.where(
caller_id: caller_id,
).order('id DESC').limit(20)
end
# in case do lookups in external sources
if !result[0]
# ...
end
result
end end
=begin =begin
@ -143,15 +121,16 @@ returns
=end =end
def self.rebuild def self.rebuild
Cti::CallerId.delete_all transaction do
map = config delete_all
map.each { |item| config.each { |item|
level = item[:level] level = item[:level]
model = item[:model] model = item[:model]
item[:model].find_each(batch_size: 500) do |record| item[:model].find_each(batch_size: 500) do |record|
build_item(record, model, level) build_item(record, model, level)
end end
} }
end
end end
=begin =begin