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

Update crutch.rb to allow crutch inter-dependency with efficiency #965

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
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
24 changes: 23 additions & 1 deletion lib/chewy/index/crutch.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,30 @@ def respond_to_missing?(name, include_private = false)
@index._crutches.key?(name) || super
end

# This method triggers crutch executions whenever crutches are accessed
# This method is called from method_missing above, with crutch name as argument
# This allows the crutch to be invoked in two ways, depending upon the block passed.
# If crutch is defined with a block accepting only 1 argument, it is called with only @collection
# ```ruby
# :crutch my_independent_crutch do |entities|
# <do stuff>
# end
# ```
# If crutch is defined with a block accepting 2 arguments, the second argument is all crutches so that we can invoke dependent crutches from here
# ```ruby
# :crutch my_dependent_crutch do |entities, crutches|
# independent_entities = crutches.my_independent_crutch
# <do stuff>
# end
# ```
# WARN: One thing to note here is that this method doesnt check for cycles. So its upto developer discretion to make sure they dont end up with a cycle here.
def [](name)
@crutches_instances[name] ||= @index._crutches[:"#{name}"].call(@collection)
execution_block = @index._crutches[:"#{name}"]
@crutches_instances[name] ||= if execution_block.arity == 2
execution_block.call(@collection, self)
else
execution_block.call(@collection)
end
end
end

Expand Down