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

Idea: expand the PM::Support.try method #735

Open
markrickert opened this issue Aug 22, 2015 · 6 comments
Open

Idea: expand the PM::Support.try method #735

markrickert opened this issue Aug 22, 2015 · 6 comments

Comments

@markrickert
Copy link
Contributor

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
Copy link
Contributor Author

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
Copy link
Contributor Author

The above works flawlessly in my tests :P

@GantMan
Copy link
Contributor

GantMan commented Aug 22, 2015

I like it! Have you done any benchmark tests?

@markrickert
Copy link
Contributor Author

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.

@jamonholmgren
Copy link
Owner

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
Copy link
Owner

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants