ProMotion
ProMotion copied to clipboard
Idea: expand the PM::Support.try method
We use try a lot internally, but we're also starting to do a lot of arity detection to determine what parameters should be sent to the user's subclass like so:
action = :will_display_header
if respond_to?(action)
case self.method(action).arity
when 0 then self.send(action)
when 2 then self.send(action, view, section)
else self.send(action, view)
end
end
what if we expanded the try method to do something like this?
def try(method, *args)
if respond_to?(method)
case self.method(action).arity
case self.method(action).arity
when 0 then self.send(action)
when 2 then self.send(action, args[0], args[1])
else self.send(action, args[0])
end
end
end
so that we could call something like try(:some_method, var1, var2, var3) and if the user has only implemented def some_method(); end; it wouldn't send those other arguments, but if they implemented def some_method(var1); end; or def some_method(var1, var2); end; it would still work.
Thoughts?
Haven't tested but it looks like we might be able to do something like this to support as many arguments as we want.
def try(method, *args)
if respond_to?(method)
arity = self.method(method).arity
if arity == 0
self.send(method)
else
self.send(method, *args.first(arity))
end
end
end
The above works flawlessly in my tests :P
I like it! Have you done any benchmark tests?
I haven't, thought I just realized that we also have the trigger_action for both table and collection views that implement this sort of thing too.
I really like it. Keep in mind that any optional arguments will screw this up badly. Really wish Ruby had arity and optional_arity.
I'm doing something kind of similar to your arity trick here: https://github.com/clearsightstudio/ProMotion/blob/master/lib/ProMotion/repl/live_reloader.rb#L18