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

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


= Examples =
= 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 =  
= Advantages =  

Revision as of 02:38, 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