12-11-2024, 09:04 AM
Using *args for the standard alias + monkey patch pattern increases compatibility. Let me show you some code.
Original:
Script Other:
The update call path then goes like this:
() -> Other -> Original ->
Say I want to attach my own piece of code. Consider this piece of code with args code:
I can place my script both above and below the other script. Both cases works fine.
() -> Other -> With args -> Original ->
() -> With args -> Other -> Original ->
Let's look at some code with no args:
Again you have two possible order arrangements however only one works
() -> Other -> No args -> Original ->
() -> No args -> Other -> Original ->
I don't whether there is a performance impact. If not, then it's a case of pure upside. Even with a small perf impact I would often find the price worth paying.
P.s. Ruby supports passing on blocks to method calls. You can access this via the & symbol.
I've found the usage scenarios to be very rare indeed. Only use has pretty much been when I've played around with the Enumerable mixin.
Also, you got to be careful with Procs as they cannot be serialized. If you store it in the object (@my_block = block) then you can no longer serialize that Foo object.
*hugs*
Original:
Code:
class Foo
def update
# ...
end
end
Script Other:
Code:
class Foo
# ...
alias_method :other_update, :update
def update(bar)
# Do stuff with bar
other_update
end
end
The update call path then goes like this:
() -> Other -> Original ->
Say I want to attach my own piece of code. Consider this piece of code with args code:
Code:
class Foo
alias_method :zeriab_example_update, :update
def update(*args)
# Do new stuff
zeriab_example_update(*args)
end
end
I can place my script both above and below the other script. Both cases works fine.
() -> Other -> With args -> Original ->
() -> With args -> Other -> Original ->
Let's look at some code with no args:
Code:
class Foo
alias_method :zeriab_example_update, :update
def update
# Do new stuff
zeriab_example_update
end
end
Again you have two possible order arrangements however only one works
() -> Other -> No args -> Original ->
() -> No args -> Other -> Original ->
I don't whether there is a performance impact. If not, then it's a case of pure upside. Even with a small perf impact I would often find the price worth paying.
P.s. Ruby supports passing on blocks to method calls. You can access this via the & symbol.
Code:
class Foo
alias_method :zeriab_example_update, :update
def update(*args, &block)
# Do new stuff
zeriab_example_update(*args, &block)
end
end
Also, you got to be careful with Procs as they cannot be serialized. If you store it in the object (@my_block = block) then you can no longer serialize that Foo object.
*hugs*