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

Patch for optional callback arguments? #18

Closed
jviney opened this issue Mar 4, 2014 · 5 comments
Closed

Patch for optional callback arguments? #18

jviney opened this issue Mar 4, 2014 · 5 comments

Comments

@jviney
Copy link

jviney commented Mar 4, 2014

Great gem - exactly what I was looking for.

I had to modify it slightly though to allow callbacks to take optional arguments, rather than passing them through to every callback. Would you accept a patch with that behaviour?

@apotonick
Copy link
Owner

I'm a very open person - can you explain what you mean with an example?

@jviney
Copy link
Author

jviney commented Mar 8, 2014

# Patch the hooks gem so the callbacks can take a variable number of arguments.
Hooks::Hook.class_eval do
  private
    def execute_callback(scope, callback, *args)
      args = args_with_correct_arity(scope, callback, args)

      if callback.kind_of?(Symbol)
        scope.send(callback, *args)
      else
        scope.instance_exec(*args, &callback)
      end
    end

    def args_with_correct_arity(scope, callback, args)
      if callback.kind_of?(Symbol)
        callback = scope.method(callback)
      end

      arity = callback.arity
      arity == -1 ? args : args.slice(0, arity)
    end
end

I have some hook methods that require an argument to be passed, and others that don't. I could just make them accept the argument, but they're used outside of hooks also so it doesn't really fit.

@jviney
Copy link
Author

jviney commented Mar 8, 2014

Actually don't worry about this, I've just restructured some code so this isn't a issue.

Cheers.

@jviney jviney closed this as completed Mar 8, 2014
@apotonick
Copy link
Owner

Ok. I thought about it and decided to leave it as it is.

Usually, people who write hook callbacks can do this if they're not interested in arguments.

def after_initialize(*)

In your case, you seem to reuse a method for both API and as a hook callback (which is good). I just don't understand why you would send parameters to the hook, then?

@jviney
Copy link
Author

jviney commented Mar 8, 2014

Yeah I know what you mean, I was migrating old code to use your gem some of which was block callbacks expecting the first parameter to be the scope object, rather than setting it to self as your gem does. After updating the old code it's not an issue any more.

Thanks :)

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

No branches or pull requests

2 participants