[Any Version] avarisc's Tack (aka quick-alias)

avarisc's Tack a.k.a. quick-alias


Just thought I'd drop in for a quick script release. Very, very simple this time: I get tired of having to alias stuff, so I set up a faster and easier way to do it. Usage and example are both in the script header.

No demo, no screenshots - because either would be entirely pointless for this specific case. It's a scripter's tool, and by itself will do absolutely nothing to the game.

Adds a Tack module with two methods: hook_after, and hook_before. Both methods require two symbols and a code block. The symbols are the class name, preceded by a ":" (a colon, without the quotes), and a function name, preceded by ":". A code block can be wrapped in between "do" and "end".

Usage example (changed - please review if updating):
  1. Tack.hook_before :GameTimer, :start do |instance, args|
  2.    args[0][0] += 5 #sorry about the double array here. nothing I can do about it that retains mutability.
  3. end
  4.  
  5. Tack.hook_after :GameTimer, :start do |instance, args|
  6.    instance.stop
  7. end
  8.  
Expand to see the code.


hook_after will execute your code block after the target function is run; hook_before will execute your code block before the target function is triggered.

The new version should work with any of the standard RPG Maker products.

THE SCRIPT 2.1 (aka absolute sorcery edition)
  1. # avarisc's Tack (a.k.a. quick-alias) | A simple mini-script that provides an
  2. # v2.1 - 3/23/15  - Public Domain     | easier and cleaner alternative to alias
  3. ################################################################################
  4. # Usage Examples:  [hook_before runs your block before, hook_after runs after]
  5. # Tack.hook_before :Game_Timer, :start do |instance, args|
  6. #   args[0][0] += 5
  7. # end
  8. # Tack.hook_after :Game_Timer, :start do |instance, args|
  9. #   instance.stop
  10. # end
  11. ################################################################################
  12.  
  13. module Tack
  14.   begin @@b, @@i = Hash.new, Array.new end
  15.   def self.hook_before(c, m, &b) tack(true, c, m, &b) end
  16.   def self.hook_after(c, m, &b) tack(false, c, m, &b) end
  17.   def self.tack(before, c_symbol, m_symbol, &block)
  18.     caller_id = caller[1].gsub(/[^0-9a-z]/i, '').hash
  19.     @@i.include?(caller_id) ? return : @@i << caller_id
  20.     _class = Object.const_get(c_symbol)
  21.     _class.send :define_method, :__tack_y__ do |*args|
  22.       instance_eval do block.call(self, args) end
  23.     end
  24.     k = ((before ? 'b_' : 'a_') + (m_s=m_symbol.to_s)).hash
  25.     @@b[k] = Array.new if !@@b.has_key? k
  26.     @@b[k] << _class.instance_method(:__tack_y__)
  27.     _class.send :remove_method, :__tack_y__
  28.     f = ('__tack_stub_' + m_s + '__').to_sym
  29.     if _class.method_defined?(f)
  30.       _class.send :alias_method, m_symbol, f
  31.     end
  32.     _class.send :alias_method, f, m_symbol
  33.     _class.send :define_method, m_symbol do |*args|
  34.       if @@b.has_key?(k=('b_' + m_s).hash)
  35.         @@b[k].each {|m|m.bind(self).call args}
  36.       end
  37.       self.send f, *args
  38.       if @@b.has_key?(k=('a_' + m_s).hash)
  39.         @@b[k].each {|m|m.bind(self).call args}
  40.       end
  41.     end
  42.   end
  43. end
Expand to see the code.


But how does it work?
It takes the code block you pass, creates a temporary class method in the target class to house the block. It then unbinds the method from the class and stores it in a specially tracked array in the Tack module. The temporary method is then deleted. If this is the first hook for the targeted method, then the Tack module aliases it to add the wrapper code. The wrapper code simply checks the specially tracked array for unbound functions that should run before or after a targeted function, and binds and executes them, along with calling the wrapped method.
TL;DR - you were better off not asking.
Nice.
Updated, the new version does not use alias, instead it uses a custom alias implementation. Advantages are unclear, but was interesting to make.
So you fixed, the problem of two identical alias-names (ala :old_update) on a very nice way too
Nice :)
Updated again, somehow I overlooked that this didn't work on functions with arguments. Note that the first update apparently dropped support for RPG Maker XP due to requiring Ruby functions that weren't present then.

Latest version supports functions with arguments - no need to do anything different at all, it should just work. Don't specify the arguments while hooking - this is all done magically behind the scenes. If you need to intercept the arguments, you should be able to access the *args array while inside the block.
Updated to 2.0. This was more or less a rewrite. What can I say, I enjoy throwing the rulebook out the window and finding a creative solution.

Features:
Fixed compatibility with XP - it no longer uses 1.9.2 specific Ruby features.
Only makes a single alias per function to handle wrapping.
F12 proof - doesn't raise errors or increase stack levels on reset
Stack effective - it runs each hook parallel rather than daisy chained. No more stack overflow errors!
No risk of name collisions (like there would be with aliasing) as this uses the calling script/line number to ID callbacks.
Support for reading and modifying arguments and interacting with the instance itself.
No longer resides in Object, rather it's neatly packed into its own module now.
License changed to public domain. Go crazy.

Effectively, this thing is now half-API and half-code-generator. Awesomesauce.

I do hope someone enjoys using it.
But does it support methods that use yield?
Had to test. It does not, it seems. Not sure how to add support for yield passthrough :\
You made me curious, so i progged my own solution 😀 :
  1. class Object
  2.     def get_new_sym(sym)
  3.         new_sym = temp_sym = sym.to_s + self.hash.to_s
  4.         while method_defined?(new_sym)
  5.             new_sym = temp_sym.to_s + rand.hash.to_s
  6.         end
  7.         return new_sym
  8.     end
  9.     def b_alias_method(old_sym, &block)
  10.         new_sym = get_new_sym(:old_sym)
  11.         alias_method new_sym, old_sym
  12.         define_method(old_sym) { |*args, &_block|
  13.             self.instance_exec(*args, &block)
  14.             send new_sym, *args
  15.         }
  16.     end
  17.     def a_alias_method(old_sym, &block)
  18.         new_sym = get_new_sym(:old_sym)
  19.         alias_method new_sym, old_sym
  20.         define_method(old_sym) { |*args, &_block|
  21.             result = send new_sym, *args
  22.             self.instance_exec(*args, &block)
  23.             result
  24.         }
  25.     end
  26.     def bb_alias_method(old_sym, &block)
  27.         new_sym = get_new_sym(:old_sym)
  28.         alias_method new_sym, old_sym
  29.         define_method(old_sym) { |*args, &_block|
  30.             self.instance_exec(_block, *args , &block)
  31.             send new_sym, *args
  32.         }
  33.     end
  34.     def ab_alias_method(old_sym, &block)
  35.         new_sym = get_new_sym(:old_sym)
  36.         alias_method new_sym, old_sym
  37.         define_method(old_sym) { |*args, &_block|
  38.             result = send new_sym, *args
  39.             self.instance_exec(_block, *args , &block)
  40.             result
  41.         }
  42.     end
  43. end
Expand to see the code.

Example:
  1. class Test < Array
  2.     b_alias_method(:size) { p "test" }
  3.     a_alias_method(:size) { p "test" }
  4.     bb_alias_method(:each) { |block, *args|
  5.         for i in 0...size()
  6.             block.call(self[i])
  7.         end
  8.     }
  9. end
  10. t = Test.new(5) { |i| i }
  11. p t.size()
  12. t.each { |e| p e }
Expand to see the code.

Original thread: https://www.hbgames.org/forums/viewtopic.php?t=78589