Class: LetterThief::EmailSearch

Inherits:
Object
  • Object
show all
Defined in:
app/models/letter_thief/email_search.rb

Constant Summary collapse

PAGE_SIZE =
20

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params) ⇒ EmailSearch

Returns a new instance of EmailSearch.



7
8
9
10
11
12
13
# File 'app/models/letter_thief/email_search.rb', line 7

def initialize(params)
  @query = params[:query].to_s.strip
  @start_time = params[:start_time]
  @end_time = params[:end_time]
  @page = params[:page].to_i
  @page = 1 if @page < 1
end

Instance Attribute Details

#end_timeObject (readonly)

Returns the value of attribute end_time.



5
6
7
# File 'app/models/letter_thief/email_search.rb', line 5

def end_time
  @end_time
end

#has_next_pageObject (readonly)

Returns the value of attribute has_next_page.



5
6
7
# File 'app/models/letter_thief/email_search.rb', line 5

def has_next_page
  @has_next_page
end

#pageObject (readonly)

Returns the value of attribute page.



5
6
7
# File 'app/models/letter_thief/email_search.rb', line 5

def page
  @page
end

#queryObject (readonly)

Returns the value of attribute query.



5
6
7
# File 'app/models/letter_thief/email_search.rb', line 5

def query
  @query
end

#resultsObject (readonly)

Returns the value of attribute results.



5
6
7
# File 'app/models/letter_thief/email_search.rb', line 5

def results
  @results
end

#start_timeObject (readonly)

Returns the value of attribute start_time.



5
6
7
# File 'app/models/letter_thief/email_search.rb', line 5

def start_time
  @start_time
end

#total_countObject (readonly)

Returns the value of attribute total_count.



5
6
7
# File 'app/models/letter_thief/email_search.rb', line 5

def total_count
  @total_count
end

Instance Method Details

#performObject



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
# File 'app/models/letter_thief/email_search.rb', line 15

def perform
  scope = EmailMessage.order(intercepted_at: :desc)

  if query.present?
    adapter = ActiveRecord::Base.connection.adapter_name.downcase
    scope = if adapter.include?("postgresql")
      scope.where(<<~SQL.squish, q: "%#{query}%")
        subject ILIKE :q
        OR array_to_string("from", ',') ILIKE :q
        OR array_to_string("to", ',') ILIKE :q
      SQL
    elsif adapter.include?("mysql")
      scope.where("`subject` LIKE :q OR `from` LIKE :q OR `to` LIKE :q", q: "%#{query}%")
    else
      scope.where('subject LIKE :q OR "from" LIKE :q OR "to" LIKE :q', q: "%#{query}%")
    end
  end

  scope = scope.where("intercepted_at >= ?", parse_datetime(start_time)) if start_time.present?
  scope = scope.where("intercepted_at <= ?", parse_datetime(end_time)) if end_time.present?

  @total_count = scope.count
  @results = scope.limit(PAGE_SIZE).offset((page - 1) * PAGE_SIZE)
  @has_next_page = total_count > page * PAGE_SIZE
  self
end