ProMotion icon indicating copy to clipboard operation
ProMotion copied to clipboard

Idea: expand the PM::Support.try method

Open markrickert opened this issue 10 years ago • 6 comments

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?

markrickert avatar Aug 22 '15 17:08 markrickert

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

markrickert avatar Aug 22 '15 17:08 markrickert

The above works flawlessly in my tests :P

markrickert avatar Aug 22 '15 17:08 markrickert

I like it! Have you done any benchmark tests?

GantMan avatar Aug 22 '15 17:08 GantMan

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.

markrickert avatar Aug 22 '15 17:08 markrickert

I really like it. Keep in mind that any optional arguments will screw this up badly. Really wish Ruby had arity and optional_arity.

jamonholmgren avatar Aug 25 '15 18:08 jamonholmgren

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

jamonholmgren avatar Aug 25 '15 18:08 jamonholmgren