Module: ApiQueries::ClassMethods

Included in:
ApiQueries
Defined in:
lib/api_queries.rb

Overview

class method

Instance Method Summary collapse

Instance Method Details

#api_q(opts = {}) ⇒ Object



8
9
10
11
12
13
14
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
41
42
43
44
45
46
47
48
49
50
# File 'lib/api_queries.rb', line 8

def api_q(opts={})
  # last updated at q
  if opts[:q] == 'last_updated_at'
    return { last_updated_at: (begin
                                 order('updated_at DESC').limit(1).first.updated_at.strftime('%Y-%m-%dT%H:%M:%SZ')
                               rescue StandardError
                                 nil
                               end) }
  end

  # condition hash
  conditions = {}

  # AFTER: updated_at > given_date
  if opts[:after].present?
    conditions = ['updated_at > ?', fdate(opts[:after])]
  # BEFORE: updated_at < given_date
  elsif opts[:before].present?
    conditions = ['updated_at < ?', fdate(opts[:before])]
  # FROM & TO: between "from date" to "to date"
  elsif opts[:from].present? && opts[:to].present?
    conditions[:updated_at] = (fdate(opts[:from])..fdate(opts[:to]))
  # FROM: updated_at >= given_date
  elsif opts[:from].present?
    conditions = ['updated_at >= ?', fdate(opts[:from])]
  # TO: updated_at <= given_date
  elsif opts[:to].present?
    conditions = ['updated_at <= ?', fdate(opts[:to])]
  end

  # get by status
  conditions[:status] = 'active' if opts[:active_only].to_s == '1' && conditions.is_a?(Hash)
  # return hash
  records = where(conditions)
  # get by status
  records = records.where(status: 'active') if opts[:active_only].to_s == '1' && conditions.is_a?(Array)

  if opts[:q] == 'count'
    { count: records.count }
  else
    records.order(id: :asc).paginate(page: opts[:page], per_page: 50)
  end
end