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



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
51
52
53
54
55
56
57
58
59
60
# File 'lib/api_queries.rb', line 10

def api_q(opts={})
  # add default value
  opts[:column_date] = 'updated_at' unless opts[:column_date].present?

  # condition hash
  conditions = {}

  # check if specified column exists
  if column_names.include?(opts[:column_date])
    # last updated at q
    if opts[:q] == 'last_updated_at'
      return { last_updated_at: (begin
                                  order(opts[:column_date] => :desc).limit(1).first.updated_at.strftime('%Y-%m-%dT%H:%M:%SZ')
                                rescue StandardError
                                  nil
                                end) }
    end

    # AFTER: updated_at > given_date
    if opts[:after].present?
      conditions = ["#{opts[:column_date]} > ?", fdate(opts[:after])]
    # BEFORE: updated_at < given_date
    elsif opts[:before].present?
      conditions = ["#{opts[:column_date]} < ?", fdate(opts[:before])]
    # FROM & TO: between "from date" to "to date"
    elsif opts[:from].present? && opts[:to].present?
      conditions[opts[:column_date].to_sym] = (fdate(opts[:from])..fdate(opts[:to]))
    # FROM: updated_at >= given_date
    elsif opts[:from].present?
      conditions = ["#{opts[:column_date]} >= ?", fdate(opts[:from])]
    # TO: updated_at <= given_date
    elsif opts[:to].present?
      conditions = ["#{opts[:column_date]} <= ?", fdate(opts[:to])]
    end
  else
    raise Errors::UnknownColumn, 'Invalid value for column_date.' unless opts[:column_date] == 'updated_at'
  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