scinote-web/app/services/lists/base_service.rb

47 lines
1 KiB
Ruby
Raw Normal View History

# frozen_string_literal: true
module Lists
class BaseService
def initialize(raw_data, params, user: nil)
@raw_data = raw_data
@params = params
@user = user
2023-12-11 22:41:03 +08:00
@filters = params[:filters] || {}
2023-12-12 19:17:38 +08:00
@records = []
end
def call
2023-12-12 19:17:38 +08:00
fetch_records
filter_records
sort_records
paginate_records
@records
end
private
def fetch_records
raise NotImplementedError
end
def order_params
@order_params ||= @params.require(:order).permit(:column, :dir).to_h
end
2023-12-12 19:17:38 +08:00
def paginate_records
@records = @records.page(@params[:page]).per(@params[:per_page])
end
def sort_direction(order_params)
order_params[:dir] == 'asc' ? 'ASC' : 'DESC'
end
2023-12-12 19:17:38 +08:00
def sort_records
return unless @params[:order] && sortable_columns[order_params[:column].to_sym].present?
sort_by = "#{sortable_columns[order_params[:column].to_sym]} #{sort_direction(order_params)}"
@records = @records.order(sort_by).order(:id)
end
end
end