Module: Istox::ResultHandler
- Defined in:
- lib/istox/helpers/result_handler.rb
Class Method Summary collapse
- .order(query:, meta:) ⇒ Object
- .paginate(query:, meta:) ⇒ Object
-
.process(query:, meta:, exclude_order: false, exclude_paginate: false) ⇒ Object
main method to be called, suggested to always use this method and not individual method below.
Class Method Details
.order(query:, meta:) ⇒ Object
15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
# File 'lib/istox/helpers/result_handler.rb', line 15 def self.order(query:, meta:) return query if .blank? || .sorts.blank? .sorts.each do |sort| # to prevent sql injection # sort.field should contains only alphabet and nothing else raise StandardError, 'POSSIBLE_SQL_INJECTION' unless validate_column_name(sort.field) # sort.order can only be asc or desc raise StandardError, 'POSSIBLE_SQL_INJECTION' unless %w[asc desc].include?(sort.order.downcase) query = query.order("#{sort.field.downcase} #{sort.order.upcase}") end query end |
.paginate(query:, meta:) ⇒ Object
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/istox/helpers/result_handler.rb', line 30 def self.paginate(query:, meta:) current_page = .page offset = (current_page - 1) * .limit total = query.count data = query.limit(.limit).offset(offset) page_count = (total + .limit - 1) / .limit OpenStruct.new( data: data, pagination: { page: current_page, limit: .limit, previousPage: current_page - 1, currentPage: current_page, nextPage: current_page < page_count ? current_page + 1 : 0, pageCount: page_count, totalCount: total } ) end |
.process(query:, meta:, exclude_order: false, exclude_paginate: false) ⇒ Object
main method to be called, suggested to always use this method and not individual method below
4 5 6 7 8 9 10 11 12 13 |
# File 'lib/istox/helpers/result_handler.rb', line 4 def self.process(query:, meta:, exclude_order: false, exclude_paginate: false) query = order(query: query, meta: ) unless exclude_order # if never set limit, means no pagination is needed return OpenStruct.new(data: query.all, pagination: nil) if .limit.blank? || .limit.zero? return paginate(query: query, meta: ) unless exclude_paginate query end |