# Concern for sorting models module Sortable extend ActiveSupport::Concern included do before_action :sort end private def sort return if params['searching'].nil? @search_hash = Array.new objects = Array.new params.each do |k, v| unless v.class.eql? String objects << k @search_hash << v end end puts objects.inspect return if objects.nil? || objects.empty? # If the object is inside a namespace if objects[0].include? '::' to_capitalize = objects[0].split('::') # We split the string with '::' and camelize the two words # Then we have to join again with '::' the capitalized words results = (to_capitalize.map { |o| o.camelize.singularize }).join('::').constantize.unscoped else results = objects[0].camelize.constantize.unscoped end @search_hash.each_with_index do |object_params, index| table_name = objects[index].pluralize table_name = params[:table_name] if params[:table_name] object_params.each do |k, v| next unless v.present? if v.eql? 'null' if index != 0 results = results.joins(table_name.to_sym).where("#{table_name}.#{k} is null") else results = results.where("#{table_name}.#{k} is null") end elsif !v.nil? if index != 0 if k.eql?('created_at') || k.eql?('updated_at') results = results.where("created_at::date = to_date(?, 'YYYY/MM/DD')", v) else results = results.joins(table_name.to_sym).where("#{table_name}.#{k}::varchar ILIKE '%#{v}%'") end else results = results.where("#{table_name}.#{k}::varchar ILIKE ?", "%#{v}%") end end end end objects_per_page = (params.select { |k, v| k.match /per_page$/ }).values.first objects_per_page ||= 20 @result = results.distinct.paginate(page: params[:page], per_page: objects_per_page).order(sort_options) end private def sort_options "#{sort_column} #{sort_direction}" end def sort_column params[:sort] ? params[:sort] : 'updated_at' end def sort_direction %w[asc desc].include?(params[:direction]) ? params[:direction] : 'asc' end end