Tldr: I am trying to use public_send to call methods but some of these methods require arguments as well. How to check which requires arguments and add those as arguments and include them in the call
I have an array of methods in a class like this
class_methods = [:first, :second, :third, :fourth] ...
I defined a can_execute
method to check if the class has the method, if so it will execute.
def can_execute (class, method_name)
if class.respond_to?(method_name.to_sym) && class.class_methods.include?(method_name.to_sym)
class.public_send(method_name)
end
end
When user supplies any of those class_method
as an argument, I can call them like this
can_execute(class, method_name)
Problem is some of those methods accepts hash as arguments, like
class.first(Value: true)
or
class.second(Id: 0, Value: "string")
But some dont
class.third
I am not sure how to include the params hash some of these class_methods
require?
I do have the option to check what arguments these methods require by calling, method_args
on them, like
class.method_args(:first)
-> [:Value]
class.method_args(:second)
=> [:Id, :Value]
class.method_args(:third)
=> []
can_execute(?)
method to use them inside it.can_execute
also actually executes methods? If you want to keep the behaviour, then yes, simply pass the needed arguments to it.can_execute?
andexecute
into two methods or removecan_
part from the method, cause it makes it ambiguous