Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP

Loading…

Patch for optional callback arguments? #18

Closed
jviney opened this Issue · 5 comments

2 participants

@jviney

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
Owner

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

@jviney
# 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

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

Cheers.

@jviney jviney closed this
@apotonick
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

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
Something went wrong with that request. Please try again.