Recent News

Interceptor Methods

Let's say we have a class in a plugin or module somewhere, and we want to override one of its methods to handle more cases, without losing the original functionality. For example, maybe we've got a login module that checks for the user record in a database. We want to make it check an LDAP first, then check the database if the user is not found in the LDAP. Using an "interceptor" pattern can help here. We'll alias the original method, storing a copy of it under a new name. Then we redefine the method to handle the new feature and conditionally call the old method. Here's an example:
    class Unicorn
      attr_accessor :climate

      def frolic
        puts 'Frolic in a meadow, enchant other forest creatures with majesty'
      end
    end
    # this class definition is locked away somewheres

    # now let's reopen the class and add the interceptor
    class Unicorn
      # copy the original method so we can still call it
      alias_method :old_frolic, :frolic 
      
      # let's intercept calls to frolic method
      def frolic
        if @climate == 'tundra' # new functionality
          puts 'Frolic on a glittering glacier, under the Aurora Borealis'
        else # conditionally default to old method definition
          old_frolic
        end
      end
    end


Comments are closed

cementhorses.com

Categories

Cement Horses Pics

Archives