Sha256: 4c0ea614b4046ee5a8236692a72cd4b8cb401ff6339c41eda9dcbecfc572a800

Contents?: true

Size: 1.58 KB

Versions: 6

Compression:

Stored size: 1.58 KB

Contents

# 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

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
care-0.1.6 lib/care/auto_finder/findable.rb
care-0.1.5 lib/care/auto_finder/findable.rb
care-0.1.4 lib/care/auto_finder/findable.rb
care-0.1.3 lib/care/auto_finder/findable.rb
care-0.1.1 lib/care/auto_finder/findable.rb
care-0.1.0 lib/care/auto_finder/findable.rb