Sha256: e665ce3bdd8bdb3896dcddfd8a2233cefafe540ef1e3151e9a5fa11fe20c9d3a

Contents?: true

Size: 1.78 KB

Versions: 2

Compression:

Stored size: 1.78 KB

Contents

module SeekParty
  class SeekPartyEngine
    attr_accessor :seek_party_attribute,
                  :seek_party_query,
                  :inspected_class

    def initialize(inspected_class,
                   params: {},
                   white_list: nil,
                   black_list: nil,
                   scopes: {})
      @seek_party_attribute = SeekPartyAttribute.new(inspected_class,
                                                     white_list,
                                                     black_list)
      @seek_party_query = SeekPartyQueryBuilder.new(params)
      @inspected_class = inspected_class
      @scopes = scopes
    end

    def search
      spa_attribute = seek_party_attribute.discover_attributes
      final_query = seek_party_query.build_query(spa_attribute)
      run_search(final_query)
    end

    private

    def run_search(final_query)
      # If scopes were passed, iterate trough\ them.
      setup_scopes if @scopes

      # Execute final query (alongside any scopes that have been passed)
      @inspected_class.where(final_query)
    end

    def setup_scopes
      # Iterate trough the scopes that may have been
      # passed. PS: This is more of a luxury than anything
      # else, as the returned object from run_search is an
      # ActiveRecord_Relation object that would accept
      # method chaining
      @scopes.each do |scope|
        if scope.respond_to?(:keys)
          scope.keys.each do |key|
            scope_call(key, scope[key])
          end
        else
          scope_call(scope, nil)
        end
      end
    end

    def scope_call(key, value)
      if value.present?
        @inspected_class = @inspected_class.method(key).call(*value)
      else
        @inspected_class = @inspected_class.method(key).call
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
seek_party-0.0.9 lib/seek_party/seek_party_engine.rb
seek_party-0.0.8 lib/seek_party/seek_party_engine.rb