Class: AsyncRequestReply::MethodsChain
- Inherits:
-
Object
- Object
- AsyncRequestReply::MethodsChain
- Defined in:
- lib/async_request_reply/methods_chain.rb
Overview
A module providing functionality for chaining method calls on a constant. This class provides a method to execute a series of method calls in sequence on a given constant.
Example:
AsyncRequestReply::MethodsChain.run_methods_chain(1, [[:+, 1], [:*, 2]])
# => 4
The methods in ‘attrs_methods` will be called in the order they are provided. If a method requires arguments, the arguments will be passed, otherwise the method will be called without arguments.
Class Method Summary collapse
-
.run_methods_chain(constant, attrs_methods = []) ⇒ Object
Executes a chain of method calls on a given constant.
Class Method Details
.run_methods_chain(constant, attrs_methods = []) ⇒ Object
Executes a chain of method calls on a given constant.
This method allows chaining of method calls on a constant, where each method can optionally receive parameters.
The constant is first constantized (if it is a string, it will be converted to a constant), and then methods from the ‘attrs_methods` array are invoked on it in order.
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/async_request_reply/methods_chain.rb', line 38 def run_methods_chain(constant, attrs_methods = []) # The constant is either a string that needs to be constantized or an already defined constant. attrs_methods.inject(constant.is_a?(String) ? constant.constantize : constant) do |constantized, method| if method[1] args = [method[1]].flatten.select{|arg| !arg.is_a?(Hash)} kwargs = ([method[1]].flatten.find{|arg| arg.is_a?(Hash)} || {}).symbolize_keys # If the argument is a Proc, pass it as a block to the method call. next constantized.send(method[0], &args[0]) if args.size == 1 && args[0].is_a?(Proc) constantized.send(method[0], *args, **kwargs) else # If no argument is provided, call the method without parameters. constantized.send(method[0]) end end end |