Class: Valkyrie::Persistence::CustomQueryContainer

Inherits:
Object
  • Object
show all
Defined in:
lib/valkyrie/persistence/custom_query_container.rb

Overview

Allows for implementors to register and use custom queries on a

per persister basis

Examples:

Custom Query Class


# Snippet from custom query class see: https://github.com/pulibrary/figgy/blob/d0b1305a1564c2aa4e7d6c1e99f0c2a88ed673f4/app/queries/find_by_string_property.rb
class FindByStringProperty
  def self.queries
    [:find_by_string_property]
  end

  ...

  def initialize(query_service:)
    @query_service = query_service
  end
  ...

  def find_by_string_property(property:, value:)
    internal_array = "{\"#{property}\": [\"#{value}\"]}"
    run_query(query, internal_array)
  end
  ...
end

Registration


# in config/initializers/valkyrie.rb
[FindByStringProperty].each do |query_handler|
  Valkyrie.config..query_service.custom_queries.register_query_handler(query_handler)
end

See Also:

  • for use of this class

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(query_service:) ⇒ CustomQueryContainer

Returns a new instance of CustomQueryContainer.



40
41
42
43
# File 'lib/valkyrie/persistence/custom_query_container.rb', line 40

def initialize(query_service:)
  @query_service = query_service
  @query_handlers = {}
end

Instance Attribute Details

#query_handlersObject (readonly)

Returns the value of attribute query_handlers.



39
40
41
# File 'lib/valkyrie/persistence/custom_query_container.rb', line 39

def query_handlers
  @query_handlers
end

#query_serviceObject (readonly)

Returns the value of attribute query_service.



39
40
41
# File 'lib/valkyrie/persistence/custom_query_container.rb', line 39

def query_service
  @query_service
end

Instance Method Details

#register_query_handler(query_handler) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/valkyrie/persistence/custom_query_container.rb', line 45

def register_query_handler(query_handler)
  query_handler.queries.each do |query|
    handler = query_handler.new(query_service: query_service)
    query_handlers[query.to_sym] = handler
    define_singleton_method query do |*args, **kwargs, &block|
      if kwargs.empty?
        # This case needs to be specially handled in Ruby 2.6, or else an
        # empty hash will be passed as the final argument.
        query_handlers[query.to_sym].__send__(query, *args, &block)
      else
        query_handlers[query.to_sym].__send__(query, *args, **kwargs, &block)
      end
    end
  end
end