CSC/ECE 517 Fall 2012/ch1 1w22 an: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
Line 155: Line 155:
  Numeric Value for xxvi is: 26
  Numeric Value for xxvi is: 26
  Roman string is invalid
  Roman string is invalid
===method_missing to log method calls===
Another application that makes use of method_missing could be a simple logger used for debugging purposes. Many times, it may be required to log the trace of called methods and provide information such as: called method-name, arguments, return type. It can be tedious to repeat this part of code in every method. So, a simple solution to this problem can be obtained using method_missing as:
  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
'''EXPLANATION:''' This program makes use of method_missing in a way that it wraps around called method to output the logging information on entry and on exit, it logs the return type. Further, method_missing intercepts the method call and forward it to internal object with ‘send’ method of ruby. Hence, this use of method_missing acts as wrapper.
===Generic Handler===
class NoBar
def method_missing(methodname, *args)
define_method(:bar) if "bar" == methodname.to_s
define_method(:nobar) if "nobar" == methodname.to_s
end
end
This is an example of using method_missing as a generic handler to handle when a calling method is not exist. You can use missing_method to dynamically create a method at a runtime.

Revision as of 04:04, 9 September 2012

Introduction

When we define a method in a class and decide to call that method, how do we do it?

We simply create an object of the class and pass the method name to the object as a message. The object then looks up into its method lookup path and tries to match the called method (passed as a message to the object) with the defined methods in the class. When there is a match, the method is executed along with the parameters passed and the result is returned.

What is a Method Lookup Path?

When the object receives a method name that is to be executed, these are the steps carried out for finding out that method called:

  • It looks in the current self object’s own instance methods.
  • Then it looks in the list of instance methods that all objects of that class share.
  • Then in each of the included modules of that class, in reverse order of inclusion.
  • Then it looks in that class’s superclass.
  • Then in the superclass’s included modules, all the way up until it reaches the class Object.
  • If it still can’t find a method, the very last place it looks is in the Kernel module, included in the class Object.
  • Finally, it calls method_missing (if defined in the class), else throws up the NOMethodError exception.

This entire tracing that the object does is the method lookup path.

What is method_missing?

Now suppose that the object does not find a matching method in its method lookup path i.e there is no such method defined in the class. Then what?

In normal circumstances the NoMethodError Exception is raised .

Here is where the method_missing comes into picture. The name “method_missing” should be self explanatory that it is invoked when a method is not found. It is a method of last resort. This method accepts the name of the non-existing method, the array of arguments passed and also any associated block to the method.

The format for defining method_missing

=> def method_missing(m,*args,&block)

Examples

A Simple Illustration

class A			// creating a class A
def say			// defining a method say
puts " say Hi "
end
end

Now, creating the object of the class

 a=A.new	         // object of the class
 => #<A:0x2a082e0>      //object id

Calling the defined method

a.say                  // defined method
=> say Hi		       // returned result

Calling the undefinedd method

a.sayhi                  // undefined method
NoMethodError: undefined method `sayhi' for #<A:0x2a082e0>   // the NoMethodError is raised

method_missing implementation

class A
def say
puts " say hi "
end
def method_missing(m,*args,&block)		// defining method_missing
puts " This method does not exist"		// body of method_missing
end
end

Calling a method that is not defined

a=A.new
a.sayhi
=> This method does not exist		// this result returned when method_missing is executed

>> Explanation: When the object 'a' traces its method lookup path for a matching method as 'sayhi', after a failure it resorts to method_missing and the body of method_missing is executed.

Note: There is something interesting that programmers do. Sometimes when a class has many methods that do generally the same kinds of things, and the programmer is not sure in advance which methods will the user call since there are so many of them, and they are all so similar, implementing all of them by hand seems futile. In these situations method_missing makes a new method that was previously not defined and adds it to the class ; or it just does what needs to be done, this is in the hands of the programmer.


Now, let us look into a few more examples to get the concept right.

passing parameters to an undefined method

class A
def add(a,b)
a+b
end
def method_missing(name,*args,&block)    // the method_missing is defined and the *args parameter accepts all the parameters passed during 								                                 
                                            the method call   
puts “You have typed the method name wrong and these were the parameters passed ; #{args[0]}, #{args[1]}”								
end                         			
end

the passed parameters are stored in the array 'args' and can be accessed like a normal array


Calling the defined method

a.add(1,2)			// calling the defined method add and passing the parameters (1,2)
=> 3                           // result

Calling the undefined method

a.adds(4,2) 			// calling the undefined method adds and passing the parameter (4,2)
=> You have typed the method name wrong and these were the parameters passed; 4, 2

Explanation: There is a genuine mistake that the user instead of add has typed in adds and this method is not defined. Here when the adds method with parameters is called, the object 'a' tries to look up the method in the method lookup path. When upon failure it invokes method_missing then the args passed in the 'adds' method are stored in the array “args”. It then executes the body of method_missing making use of the parameters.

converting numbers from roman representation to integer representation

class Roman
@@Roman_to_Numeric = {'i' => 1, 'v' => 5, 'x' => 10, 'l' => 50, 'c' => 100, 'd' => 500, 'm' => 1000}// Here we are creating a hash with the   roman symbols and their	corresponding values.
def method_missing(method_var,*args,&block)
numeric_value = 0
roman_string = method_var.to_s.downcase
for i in 0...roman_string.length-1
if (@@Roman_to_Numeric[roman_string[i]]-@@Roman_to_Numeric[roman_string[i+1]] == 0 || @@Roman_to_Numeric[roman_string[i]]-     @@Roman_to_Numeric[roman_string[i+1]] == -9 || @@Roman_to_Numeric[roman_string[i]]-@@Roman_to_Numeric[roman_string[i+1]] == -4 || @@Roman_to_Numeric[roman_string[i]]-@@Roman_to_Numeric[roman_string[i+1]] >= 4) && (/.v.x/ =~ roman_string) == nil
else
puts "Roman string is invalid"
return
end
end
while roman_string != ""
if roman_string[roman_string.length - 1] == 'x' && roman_string[roman_string.length - 2] == 'i'
numeric_value += 9
roman_string.chop!
roman_string.chop!
elsif
roman_string[roman_string.length - 1] == 'v' && roman_string[roman_string.length - 2] == 'i'
numeric_value += 4
roman_string.chop!
roman_string.chop!
else
numeric_value += @@Roman_to_Numeric[roman_string[(roman_string.length)-1]]
roman_string.chop!
end
end
puts "Numeric Value for #{method_var} is: #{numeric_value}"
end
end

calling the undefined methods

r= Roman.new
r.vii
r.iClx
r.xxix
r.xxxi
r.xxiv
r.xxvi
r.vx

The Output:

O/P:

Numeric Value for vii is: 7
Roman string is invalid
Numeric Value for xxix is: 29
Numeric Value for xxxi is: 31
Numeric Value for xxiv is: 24
Numeric Value for xxvi is: 26
Roman string is invalid

method_missing to log method calls

Another application that makes use of method_missing could be a simple logger used for debugging purposes. Many times, it may be required to log the trace of called methods and provide information such as: called method-name, arguments, return type. It can be tedious to repeat this part of code in every method. So, a simple solution to this problem can be obtained using method_missing as:

 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

EXPLANATION: This program makes use of method_missing in a way that it wraps around called method to output the logging information on entry and on exit, it logs the return type. Further, method_missing intercepts the method call and forward it to internal object with ‘send’ method of ruby. Hence, this use of method_missing acts as wrapper.

Generic Handler

class NoBar
def method_missing(methodname, *args)
define_method(:bar) if "bar" == methodname.to_s
define_method(:nobar) if "nobar" == methodname.to_s
end
end

This is an example of using method_missing as a generic handler to handle when a calling method is not exist. You can use missing_method to dynamically create a method at a runtime.