Ruby Aliasing
Aliasing is a powerful Ruby feature that allows more than one method to be referred to by multiple names. This can be used to give a programmer more expressive options or to create copies of a method, allowing you to change the behavior of a class. For an example if you wanted to override to_s to always place quotes around the value (nopt very useful but it will suffice for now) we could write a module like this:1 2 3 4 5 6 7 8 9 10 11 12 | module QuoteToS def self.included(base) base.class_eval do alias_method :to_s_without_quotes, :to_s unless method_defined?(:to_s_without_quotes) alias_method :to_s, :to_s_with_quotes end end def to_s_with_quotes "'#{to_s_without_quotes}'" end end |
- Create an alias for the method to be modified. This alias provides a name for the unmodified version of the method.
- Define a new version of the method. This new version should call the unmodified version through the alias, but it can add whatever functionality is needed before and after it does that.
Related posts brought to you by Yet Another Related Posts Plugin.



No Comments Comments Feed
Add a Comment