Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor away from method_missing for custom_query_container. #874

Merged
merged 1 commit into from
Sep 21, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 8 additions & 26 deletions lib/valkyrie/persistence/custom_query_container.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,35 +39,17 @@ class CustomQueryContainer
attr_reader :query_service, :query_handlers
def initialize(query_service:)
@query_service = query_service
@query_handlers = []
@query_handlers = {}
end

def register_query_handler(query_handler)
@query_handlers << query_handler
end

def method_missing(meth_name, *args, &block)
handler_class =
find_query_handler(meth_name) ||
raise(NoMethodError, "Custom query #{meth_name} is not registered. The registered queries are: #{queries}")

query_handler = handler_class.new(query_service: query_service)
return super unless query_handler
query_handler.__send__(meth_name, *args, &block)
end

def find_query_handler(method)
query_handlers.find { |x| x.queries.include?(method) }
end

def respond_to_missing?(meth_name, _args)
find_query_handler(meth_name).present?
end

private

def queries
query_handlers.map(&:queries).flatten
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, &block|
query_handlers[query.to_sym].__send__(query, *args, &block)
end
end
end
end
end