# frozen_string_literal: true module Care::AutoFinder module Findable extend ActiveSupport::Concern module ClassMethods attr_accessor :chain_filter # attr_accessor :relation def set_relation(relation) @relation = relation end def entity self.relation = yield end def filter_by(*filters) self.chain_filter = filters end def relation @relation ||= /(.*)Finder/.match(name)[1].singularize.constantize end # # @param [Hash] options параметры для работы файдера # @option options [ActiveRecord] :relation модель, для которой будет вестись поиск # @option options [Hash] :params опции для поиска # # @example # FooBarFinder # .call( # relation: FooBar, # params: { page: 10, limit: 2, name: 'Lorem' } # ) # def call(options = {}) new(options).call end end def initialize(options = {}) options = options.symbolize_keys @relation = options[:relation] || self.class.relation || options[:params][:relation] @params = options[:params] || options || {} end def call collection = relation || self.class.relation chain_filter.each do |filter| collection = send(filter, collection) end collection.distinct end protected attr_reader :relation, :params def chain_filter self.class.chain_filter || [:ids, :paginate, :search, :sort] end end end