CSC/ECE 517 Fall 2007/wiki1b 2 22: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
Line 8: Line 8:


=== 1. Object composition ===
=== 1. Object composition ===
class SimpleCallLogger
 
class SimpleCallLogger
   def initialize(o)
   def initialize(o)
     @obj = o
     @obj = o
Line 18: Line 19:
     return a
     return a
   end
   end
end
end


This object "intercepts" all method calls made to it, prints out a message and forwards on the method call to an internal object using the 'send' method, without knowing anything about the object passed to it. It can be used to debug some code without littering it with print statements.
This object "intercepts" all method calls made to it, prints out a message and forwards on the method call to an internal object using the 'send' method, without knowing anything about the object passed to it. It can be used to debug some code without littering it with print statements.

Revision as of 02:39, 26 September 2007

Introduction - method_missing

method_missing: This method is called whenever someone tries to call a method in your object that doesn't exist.

Examples

1. Object composition

class SimpleCallLogger
 def initialize(o)
   @obj = o
 end
 def method_missing(methodname, *args)
   puts "called: #{methodname}(#{args})"
   a = @obj.send(methodname, *args)
   puts "\t-> returned: #{a}"
   return a
 end
end

This object "intercepts" all method calls made to it, prints out a message and forwards on the method call to an internal object using the 'send' method, without knowing anything about the object passed to it. It can be used to debug some code without littering it with print statements.

Advantages

References

Further reading

External links