Skip to content

Commit

Permalink
Allow using methods with keyword arguments in search DSL (sunspot#1031)
Browse files Browse the repository at this point in the history
  • Loading branch information
s4na authored Aug 25, 2023
1 parent 678c5b2 commit 4a86fbb
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 10 deletions.
30 changes: 20 additions & 10 deletions sunspot/lib/sunspot/util.rb
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ def deep_merge_into(destination, left, right)
Coordinates = Struct.new(:lat, :lng)

class ContextBoundDelegate
class <<self
class << self
def instance_eval_with_context(receiver, &block)
calling_context = eval('self', block.binding)
if parent_calling_context = calling_context.instance_eval{@__calling_context__ if defined?(@__calling_context__)}
Expand Down Expand Up @@ -289,21 +289,31 @@ def sub(*args, &block)
__proxy_method__(:sub, *args, &block)
end

def method_missing(method, *args, &block)
__proxy_method__(method, *args, &block)
def method_missing(method, *args, **kwargs, &block)
__proxy_method__(method, *args, **kwargs, &block)
end

def __proxy_method__(method, *args, &block)
begin
def respond_to_missing?(method, _)
@__receiver__.respond_to?(method, true) || super
end

def __proxy_method__(method, *args, **kwargs, &block)
if kwargs.empty?
@__receiver__.__send__(method.to_sym, *args, &block)
rescue ::NoMethodError => e
begin
else
@__receiver__.__send__(method.to_sym, *args, **kwargs, &block)
end
rescue ::NoMethodError => e
begin
if kwargs.empty?
@__calling_context__.__send__(method.to_sym, *args, &block)
rescue ::NoMethodError
raise(e)
else
@__calling_context__.__send__(method.to_sym, *args, **kwargs, &block)
end
rescue ::NoMethodError
raise(e)
end
end
end
end
end
end
15 changes: 15 additions & 0 deletions sunspot/spec/api/binding_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,17 @@
end
end
end
expect(value).to eq('value')
end

it 'should give access to calling context\'s methods with keyword arguments' do
value = nil
session.search(Post) do
any_of do
value = kwargs_method(a: 10, b: 20)
end
end
expect(value).to eq({ a: 10, b: 20 })
end

private
Expand All @@ -47,4 +58,8 @@ def test_method
def id
16
end

def kwargs_method(a:, b:)
{ a: a, b: b }
end
end

0 comments on commit 4a86fbb

Please sign in to comment.