1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
|
<html><title>Programming Ruby: The Pragmatic Programmer's Guide</title><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"><STYLE TYPE="text/css"><!--
BODY { margin-left: 1in;
width: 6in;
font-family: helvetica, arial, sans-serif;
}
H1 { color: #000080;
font-family: helvetica, arial, sans-serif;
font-size: 22pt;
margin-left: 0in
}
H2 { color: #000080; font: bold x-large helvetica, sans-serif;
margin-left: 0in }
H3 { color: #000080; font: bold large helvetica, sans-serif; }
H4 { color: #000080; font: italic large helvetica, sans-serif; }
.ruby { background: #fff0f0 }
.header { color: white }
.subheader { color: #ffdddd }
.sidebar { width: 6in }
span.sans { font-family: helvetica, arial, sans-serif }
-->
</STYLE><table bgcolor="#a03030" cellpadding="3" border="0" cellspacing="0"><tr><td colspan="3"><table bgcolor="#902020" cellpadding="20"><tr><td><h1 class="header">Programming Ruby</h1><h3 class="subheader">The Pragmatic Programmer's Guide</h3></td></tr></table></td></tr><tr><td width="33%" align="left"><a class="subheader" href="taint.html">Previous <</a></td><td width="33%" align="center" valign="middle"><a class="subheader" href="index.html">Contents ^</a><br></td><td width="33%" align="right"><a class="subheader" href="builtins.html">Next ></a><br></td></tr></table></head><body bgcolor="white">
<!--
Copyright (c) 2001 by Addison Wesley Longman. This
material may be distributed only subject to the terms and
conditions set forth in the Open Publication License, v1.0 or
later (the latest version is presently available at
http://www.opencontent.org/openpub/).
-->
<h1>Reflection, ObjectSpace, and Distributed Ruby</h1><hr><br>
<P></P>
One of the many advantages of dynamic languages such as Ruby is the
ability to <em>introspect</em>---to examine aspects of the program from
within the program itself. Java, for one, calls this
feature <em>reflection</em>.
<P></P>
The word ``reflection''
conjures up an image of looking at oneself in the mirror---perhaps
investigating the relentless spread of that bald spot on the top of
one's head. That's a pretty apt analogy: we use reflection to examine
parts of our programs that aren't normally visible from where we stand.
<P></P>
In this deeply introspective mood, while we are contemplating our
navels and burning incense (being careful not to swap the two tasks),
what can we learn about our program? We might discover:
<P></P>
<ul>
<li> what objects it contains,
</li><li> the current class hierarchy,
</li><li> the contents and behaviors of objects, and
</li><li> information on methods.
</li></ul>
<P></P>
Armed with this information, we can look at particular objects
and decide which of their methods to call at runtime---even if the class of
the object didn't exist when we first wrote the code. We can also
start doing clever things, perhaps modifying the program as it's
running.
<P></P>
Sound scary? It needn't be. In fact, these reflection capabilities let
us do some very useful things. Later in this chapter we'll look at
distributed Ruby and marshaling, two reflection-based technologies
that let us send objects around the world and through time.
<h2>Looking at Objects</h2>
<P></P>
Have you ever craved the ability to traverse <em>all</em> the living objects
in your program? We have! Ruby lets you perform
this trick with <a href="ref_m_objectspace.html#each_object"><code>ObjectSpace::each_object</code></a>. We can use it to
do all sorts of neat tricks.
<P></P>
For example, to iterate over all objects of type <code>Numeric</code>, you'd
write the following.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
a = 102.7
b = 95.1
ObjectSpace.each_object(Numeric) {|x| p x }
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
95.1
102.7
2.718281828
3.141592654
</pre></td></tr></table>
<P></P>
Hey, where did those last two numbers come from? We didn't define
them in our program. If you look on page 433, you'll
see that the <code>Math</code> module defines constants for e and PI; since we are
examining <em>all</em> living objects in the system, these turn up as
well.
<P></P>
However, there is a catch. Let's try the same example with different
numbers.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
a = 102
b = 95
ObjectSpace.each_object(Numeric) {|x| p x }
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
2.718281828
3.141592654
</pre></td></tr></table>
<P></P>
Neither of the <code>Fixnum</code> objects we created showed up. That's because
<code>ObjectSpace</code> doesn't know about objects with immediate values:
<code>Fixnum</code>, <code>true</code>, <code>false</code>, and <code>nil</code>.
<h3>Looking Inside Objects</h3>
<P></P>
Once you've found an interesting object, you may be tempted to find
out just what it can do. Unlike static languages, where a variable's
type determines its class, and hence the methods it supports, Ruby
supports liberated objects. You really cannot tell exactly what an
object can do until you look under its hood.<em>[Or under its bonnet, for
objects created to the east of the Atlantic.]</em>
<P></P>
For instance, we can get a list of all the methods to which an object will
respond.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>r = 1..10 # Create a Range object</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>list = r.methods</code></td>
</tr>
<tr>
<td valign="top"><code>list.length</code></td>
<td valign="top"></td>
<td valign="top"><code>60</code></td>
</tr>
<tr>
<td valign="top"><code>list[0..3]</code></td>
<td valign="top"></td>
<td valign="top"><code>["size", "length", "exclude_end?", "inspect"]</code></td>
</tr>
</table>
<P></P>
<P></P>
Or, we can check to see if an object supports a particular method.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td valign="top"><code>r.respond_to?("frozen?")</code></td>
<td valign="top"></td>
<td valign="top"><code>true</code></td>
</tr>
<tr>
<td valign="top"><code>r.respond_to?("hasKey")</code></td>
<td valign="top"></td>
<td valign="top"><code>false</code></td>
</tr>
<tr>
<td valign="top"><code>"me".respond_to?("==")</code></td>
<td valign="top"></td>
<td valign="top"><code>true</code></td>
</tr>
</table>
<P></P>
<P></P>
We can determine our object's class and its unique object id, and test
its relationship to other classes.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>num = 1</code></td>
</tr>
<tr>
<td valign="top"><code>num.id</code></td>
<td valign="top"></td>
<td valign="top"><code>3</code></td>
</tr>
<tr>
<td valign="top"><code>num.class</code></td>
<td valign="top"></td>
<td valign="top"><code>Fixnum</code></td>
</tr>
<tr>
<td valign="top"><code>num.kind_of? Fixnum</code></td>
<td valign="top"></td>
<td valign="top"><code>true</code></td>
</tr>
<tr>
<td valign="top"><code>num.kind_of? Numeric</code></td>
<td valign="top"></td>
<td valign="top"><code>true</code></td>
</tr>
<tr>
<td valign="top"><code>num.instance_of? Fixnum</code></td>
<td valign="top"></td>
<td valign="top"><code>true</code></td>
</tr>
<tr>
<td valign="top"><code>num.instance_of? Numeric</code></td>
<td valign="top"></td>
<td valign="top"><code>false</code></td>
</tr>
</table>
<P></P>
<h2>Looking at Classes</h2>
<P></P>
Knowing about objects is one part of reflection, but to get the whole
picture, you also need to be able to look at classes---the methods
and constants that they contain.
<P></P>
Looking at the class hierarchy is easy. You can get the parent of any
particular class using <a href="ref_c_class.html#superclass"><code>Class#superclass</code></a>. For
classes <em>and</em> modules, <a href="ref_c_module.html#ancestors"><code>Module#ancestors</code></a> lists both
superclasses and mixed-in modules.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
klass = Fixnum
begin
print klass
klass = klass.superclass
print " < " if klass
end while klass
puts
p Fixnum.ancestors
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
Fixnum < Integer < Numeric < Object
[Fixnum, Integer, Precision, Numeric, Comparable, Object, Kernel]
</pre></td></tr></table>
<P></P>
If you want to build a complete class hierarchy, just run that code
for every class in the system. We can use <code>ObjectSpace</code> to iterate
over all <code>Class</code> objects:
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
ObjectSpace.each_object(Class) do |aClass|
# ...
end
</pre></td></tr></table>
<h3>Looking Inside Classes</h3>
<P></P>
We can find out a bit more about the methods and constants in a
particular object. Instead of just checking to see whether the object
responds to a given message, we can ask for methods by access level,
we can ask for just singleton methods, and we can have a look at
the object's constants.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>class Demo</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> private</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> def privMethod</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> protected</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> def protMethod</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> public</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> def pubMethod</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code></code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> def Demo.classMethod</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code></code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> CONST = 1.23</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code></code></td>
</tr>
<tr>
<td valign="top"><code>Demo.private_instance_methods</code></td>
<td valign="top"></td>
<td valign="top"><code>["privMethod"]</code></td>
</tr>
<tr>
<td valign="top"><code>Demo.protected_instance_methods</code></td>
<td valign="top"></td>
<td valign="top"><code>["protMethod"]</code></td>
</tr>
<tr>
<td valign="top"><code>Demo.public_instance_methods</code></td>
<td valign="top"></td>
<td valign="top"><code>["pubMethod"]</code></td>
</tr>
<tr>
<td valign="top"><code>Demo.singleton_methods</code></td>
<td valign="top"></td>
<td valign="top"><code>["classMethod"]</code></td>
</tr>
<tr>
<td valign="top"><code>Demo.constants - Demo.superclass.constants</code></td>
<td valign="top"></td>
<td valign="top"><code>["CONST"]</code></td>
</tr>
</table>
<P></P>
<P></P>
<a href="ref_c_module.html#constants"><code>Module::constants</code></a> returns
<em>all</em> the constants available via a module, including
constants from the module's superclasses. We're not interested in
those just at the moment, so we'll subtract them from our list.
<P></P>
Given a list of method names, we might now be tempted to try calling them.
Fortunately, that's easy with Ruby.
<h2>Calling Methods Dynamically</h2>
<P></P>
C and Java programmers often find themselves writing some kind of
dispatch table: functions which are invoked based on a command. Think
of a typical C idiom where you have to translate a string to a
function pointer:
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
typedef struct {
char *name;
void (*fptr)();
} Tuple;
<P></P>
Tuple list[]= {
{ "play", fptr_play },
{ "stop", fptr_stop },
{ "record", fptr_record },
{ 0, 0 },
};
<P></P>
...
<P></P>
void dispatch(char *cmd) {
int i = 0;
for (; list[i].name; i++) {
if (strncmp(list[i].name,cmd,strlen(cmd)) == 0) {
list[i].fptr();
return;
}
}
/* not found */
}
</pre></td></tr></table>
<P></P>
In Ruby, you can do all this in one line. Stick all your command
functions into a class, create an instance of that class (we called it
<code>commands</code>), and ask that object to execute a method called the
same name as the command string.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
commands.send(commandString)
</pre></td></tr></table>
<P></P>
Oh, and by the way, it does much more than the C version---it's
dynamic. The Ruby version will find new methods added at runtime just
as easily.
<P></P>
You don't have to write special command classes for <code>send</code>: it
works on any object.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td valign="top"><code>"John Coltrane".send(:length)</code></td>
<td valign="top"></td>
<td valign="top"><code>13</code></td>
</tr>
<tr>
<td valign="top"><code>"Miles Davis".send("sub", /iles/, '.')</code></td>
<td valign="top"></td>
<td valign="top"><code>"M. Davis"</code></td>
</tr>
</table>
<P></P>
<P></P>
Another way of invoking methods dynamically uses <code>Method</code> objects. A
<code>Method</code> object is like a <code>Proc</code> object: it represents a chunk of
code and a context in which it executes. In this case, the code is the
body of the method, and the context is the object that created the
method. Once we have our <code>Method</code> object, we can execute it sometime
later by sending it the message <code>call</code>.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>trane = "John Coltrane".method(:length)</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>miles = "Miles Davis".method("sub")</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code></code></td>
</tr>
<tr>
<td valign="top"><code>trane.call</code></td>
<td valign="top"></td>
<td valign="top"><code>13</code></td>
</tr>
<tr>
<td valign="top"><code>miles.call(/iles/, '.')</code></td>
<td valign="top"></td>
<td valign="top"><code>"M. Davis"</code></td>
</tr>
</table>
<P></P>
<P></P>
You can pass the <code>Method</code> object around as you would any other
object, and when you invoke <a href="ref_c_method.html#call"><code>Method#call</code></a>, the method is run just
as if you had invoked it on the original object. It's like having a
C-style function pointer but in a fully object-oriented style.
<P></P>
You can also use <code>Method</code> objects with iterators.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>def double(a)</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> 2*a</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code></code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>mObj = method(:double)</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code></code></td>
</tr>
<tr>
<td valign="top"><code>[ 1, 3, 5, 7 ].collect(&mObj)</code></td>
<td valign="top"></td>
<td valign="top"><code>[2, 6, 10, 14]</code></td>
</tr>
</table>
<P></P>
<P></P>
As good things come in threes, here's yet another way to invoke
methods dynamically. The <code>eval</code>
method (and its variations such as
<code>class_eval</code>, <code>module_eval</code>, and <code>instance_eval</code>) will
parse and execute an arbitrary string of legal Ruby source code.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>trane = %q{"John Coltrane".length}</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>miles = %q{"Miles Davis".sub(/iles/, '.')}</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code></code></td>
</tr>
<tr>
<td valign="top"><code>eval trane</code></td>
<td valign="top"></td>
<td valign="top"><code>13</code></td>
</tr>
<tr>
<td valign="top"><code>eval miles</code></td>
<td valign="top"></td>
<td valign="top"><code>"M. Davis"</code></td>
</tr>
</table>
<P></P>
<P></P>
When using <code>eval</code>, it can be helpful to state explicitly the
context in which the expression should be evaluated, rather than using
the current context. You can obtain a context by calling
<a href="ref_m_kernel.html#binding"><code>Kernel#binding</code></a> at the desired point.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class CoinSlot
def initialize(amt=Cents.new(25))
@amt = amt
$here = binding
end
end
<P></P>
a = CoinSlot.new
eval "puts @amt", $here
eval "puts @amt"
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
$0.25USD
nil
</pre></td></tr></table>
<P></P>
The first <code>eval</code> evaluates <code>@amt</code> in the context of the instance
of class <code>CoinSlot</code>. The second <code>eval</code> evaluates <code>@amt</code> in
the context of <code>Object</code>, where the instance variable <code>@amt</code> is
not defined.
<h3>Performance Considerations</h3>
<P></P>
As we've seen in this section, there are several ways to invoke an
arbitrary method of some object: <a href="ref_c_object.html#send"><code>Object#send</code></a>,
<a href="ref_c_method.html#call"><code>Method#call</code></a>, and the various flavors of <code>eval</code>.
<P></P>
You may prefer to use any one of these techniques depending on your
needs, but be aware that <code>eval</code> is significantly slower than the
others (or, for optimistic readers, <code>send</code> and <code>call</code> are
significantly faster than <code>eval</code>).
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
require "benchmark" # from the Ruby Application Archive
include Benchmark
<P></P>
test = "Stormy Weather"
m = test.method(:length)
n = 100000
<P></P>
bm(12) {|x|
x.report("call") { n.times { m.call } }
x.report("send") { n.times { test.send(:length) } }
x.report("eval") { n.times { eval "test.length" } }
}
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
user system total real
call 0.270000 0.000000 0.270000 ( 0.243899)
send 0.250000 0.000000 0.250000 ( 0.227987)
eval 2.990000 0.050000 3.040000 ( 2.929909)
</pre></td></tr></table>
<h2>System Hooks</h2>
<P></P>
A <em>hook</em> is a technique that lets you trap some Ruby event, such
as object creation.
<P></P>
The simplest hook technique in Ruby is to intercept calls to methods
in system classes. Perhaps you want to log all the operating system
commands your program executes. Simply rename the method
<a href="ref_m_kernel.html#system"><code>Kernel::system</code></a><em>[This Eiffel-inspired
idiom of renaming a
feature and redefining a new one is very useful, but be aware that
it can cause problems. If a subclass does the same thing, and
renames the methods using the same names, you'll end up with an
infinite loop. You can avoid this by aliasing your methods to a
unique symbol name or by using a consistent naming convention.]</em>
and substitute it with one of your own that both logs the command and
calls the original <code>Kernel</code> method.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
module Kernel
alias_method :old_system, :system
def system(*args)
result = old_system(*args)
puts "system(#{args.join(', ')}) returned #{result}"
result
end
end
<P></P>
system("date")
system("kangaroo", "-hop 10", "skippy")
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
Sun Mar 4 23:25:46 CST 2001
system(date) returned true
system(kangaroo, -hop 10, skippy) returned false
</pre></td></tr></table>
<P></P>
A more powerful hook is catching objects as they are created.
If you can be
present when every object is born, you can do all sorts of interesting
things: you can wrap them, add methods to them, remove methods from them, add them
to containers to implement persistence, you name it. We'll show a
simple example here: we'll add a timestamp to every object as it's
created.
<P></P>
One way to hook object creation is to do our method renaming trick on
<a href="ref_c_class.html#new"><code>Class#new</code></a>, the method that's called to allocate space for a new
object. The technique isn't perfect---some built-in objects, such as
literal strings, are constructed without calling <code>new</code>---but
it'll work just fine for objects we write.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class Class
alias_method :old_new, :new
def new(*args)
result = old_new(*args)
result.timestamp = Time.now
return result
end
end
</pre></td></tr></table>
<P></P>
We'll also need to add a timestamp attribute to every object in the
system. We can do this by hacking class <code>Object</code> itself.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class Object
def timestamp
return @timestamp
end
def timestamp=(aTime)
@timestamp = aTime
end
end
</pre></td></tr></table>
<P></P>
Finally, we can run a test. We'll create a couple of objects a few
seconds apart and check their timestamps.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>class Test</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code></code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>obj1 = Test.new</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>sleep 2</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>obj2 = Test.new</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code></code></td>
</tr>
<tr>
<td valign="top"><code>obj1.timestamp</code></td>
<td valign="top"></td>
<td valign="top"><code>Sun Mar 04 23:25:46 CST 2001</code></td>
</tr>
<tr>
<td valign="top"><code>obj2.timestamp</code></td>
<td valign="top"></td>
<td valign="top"><code>Sun Mar 04 23:25:48 CST 2001</code></td>
</tr>
</table>
<P></P>
<P></P>
All this method renaming is fine, and it really does work. However,
there are other, more refined ways to get inside a running
program. Ruby provides several callback methods that let you trap
certain events in a controlled way.
<h3>Runtime Callbacks</h3>
<P></P>
You can be notified whenever one of the following events occurs:
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3">
<tr bgcolor="#ff9999">
<td valign="top"><b>Event</b></td>
<td valign="top"><b>Callback Method</b></td>
</tr>
<tr>
<td valign="top">Adding an instance method</td>
<td valign="top"><a href="ref_c_module.html#method_added"><code>Module#method_added</code></a></td>
</tr>
<tr>
<td valign="top">Adding a singleton method</td>
<td valign="top"><a href="ref_m_kernel.html#singleton_method_added"><code>Kernel::singleton_method_added</code></a></td>
</tr>
<tr>
<td valign="top">Subclassing a class</td>
<td valign="top"><a href="ref_c_class.html#inherited"><code>Class#inherited</code></a></td>
</tr>
<tr>
<td valign="top">Mixing in a module</td>
<td valign="top"><a href="ref_c_module.html#extend_object"><code>Module#extend_object</code></a></td>
</tr>
<tr><td colspan="9" bgcolor="#ff9999" height="2"><img src="dot.gif" width="1" height="1"></td></tr></table>
<P></P>
These techniques are all illustrated in the library descriptions for
each callback method. At runtime, these methods will be called by the
system when the specified event occurs. By default, these methods do
nothing. If you want to be notified when one of these events happens,
just define the callback method, and you're in.
<P></P>
Keeping track of method creation and class and module usage lets you
build an accurate picture of the dynamic state of your program. This
can be important. For example, you may have written code that wraps
all the methods in a class, perhaps to add transactional support or
to implement some form of delegation. This is only half the job: the
dynamic nature of Ruby means that users of this class could add new
methods to it at any time. Using these callbacks, you can write
code that wraps these new methods as they are created.
<h2>Tracing Your Program's Execution</h2>
<P></P>
While we're having fun reflecting on all the objects and classes in
our programs, let's not forget about the humble statements that make
our code actually do things. It turns out that Ruby lets us look at
these statements, too.
<P></P>
First, you can watch the interpreter as it executes code.
<code>set_trace_func</code>
executes a <code>Proc</code> with all sorts of juicy
debugging information whenever a new source line is executed,
methods are called, objects are created, and so on. There's a full description
on page 426, but here's a taste.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class Test
def test
a = 1
b = 2
end
end
<P></P>
set_trace_func proc { |event, file, line, id, binding, classname|
printf "%8s %s:%-2d %10s %8s\n", event, file, line, id, classname
}
t = Test.new
t.test
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
line prog.rb:11 false
c-call prog.rb:11 new Class
c-call prog.rb:11 initialize Object
c-return prog.rb:11 initialize Object
c-return prog.rb:11 new Class
line prog.rb:12 false
call prog.rb:2 test Test
line prog.rb:3 test Test
line prog.rb:4 test Test
return prog.rb:4 test Test
</pre></td></tr></table>
<P></P>
There's also a method <code>trace_var</code> (described
on page 431) that lets you add a hook to a global variable; whenever
an assignment is made to the global, your <code>Proc</code> object is invoked.
<h3>How Did We Get Here?</h3>
<P></P>
A fair question, and one we ask ourselves regularly. Mental lapses
aside, in Ruby at least you can find out exactly ``how you got there''
by using the method <code>caller</code>,
which returns an <code>Array</code> of
<code>String</code> objects representing the current call stack.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
def catA
puts caller.join("\n")
end
def catB
catA
end
def catC
catB
end
catC
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
prog.rb:5:in `catB'
prog.rb:8:in `catC'
prog.rb:10
</pre></td></tr></table>
<P></P>
Once you've figured out how you got there, where you go next is up to
you.
<h2>Marshaling and Distributed Ruby</h2>
<P></P>
Java features the ability to <em>serialize</em> objects, letting you
store them somewhere and reconstitute them when needed. You might
use this facility, for instance, to save a tree of objects that
represent some portion of application state---a document, a CAD
drawing, a piece of music, and so on.
<P></P>
Ruby calls this kind of serialization
<em>marshaling</em>.<em>[Think of railroad marshaling yards
where individual cars are assembled in sequence into a complete
train, which is then dispatched somewhere.]</em> Saving an object
and some or all of its components is done using the method
<a href="ref_m_marshal.html#dump"><code>Marshal::dump</code></a>. Typically, you will dump an entire object tree
starting with some given object. Later on, you can reconstitute the
object using <a href="ref_m_marshal.html#load"><code>Marshal::load</code></a>.
<P></P>
Here's a short example. We have a class <code>Chord</code> that holds a
collection of musical notes. We'd like to save away a particularly
wonderful chord so our grandchildren can load it into Ruby Version
23.5 and savor it, too. Let's start off with the classes for <code>Note</code>
and <code>Chord</code>.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class Note
attr :value
def initialize(val)
@value = val
end
def to_s
@value.to_s
end
end
<P></P>
class Chord
def initialize(arr)
@arr = arr
end
def play
@arr.join('-')
end
end
</pre></td></tr></table>
<P></P>
Now we'll create our masterpiece, and use <a href="ref_m_marshal.html#dump"><code>Marshal::dump</code></a> to save
a serialized version of it to disk.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
c = Chord.new( [ Note.new("G"), Note.new("Bb"),
Note.new("Db"), Note.new("E") ] )
<P></P>
File.open("posterity", "w+") do |f|
Marshal.dump(c, f)
end
</pre></td></tr></table>
<P></P>
Finally, our grandchildren read it in, and are transported by our
creation's beauty.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="500">
<tr>
<td colspan="3" valign="top"><code>File.open("posterity") do |f|</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code> chord = Marshal.load(f)</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code>end</code></td>
</tr>
<tr>
<td colspan="3" valign="top"><code></code></td>
</tr>
<tr>
<td valign="top"><code>chord.play</code></td>
<td valign="top"></td>
<td valign="top"><code>"G-Bb-Db-E"</code></td>
</tr>
</table>
<P></P>
<h3>Custom Serialization Strategy</h3>
<P></P>
Not all objects can be dumped: bindings, procedure objects, instances
of class <code>IO</code>, and singleton objects cannot be saved outside of the
running Ruby environment (a <code>TypeError</code> will be raised if you try).
Even if your object doesn't contain one of these problematic objects,
you may want to take control of object serialization yourself.
<P></P>
<code>Marshal</code> provides the hooks you need. In the objects that require
custom serialization, simply implement two methods: an instance method
called <code>_dump</code>,
which writes the object out to a string, and a
class method called <code>_load</code>, which reads a string that you'd
previously created and converts it into a new object.
<P></P>
For instance, here is a sample class that defines its own
serialization.
For whatever reasons, <code>Special</code> doesn't want to save one of its
internal data members, ``<code>@volatile</code>''.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
class Special
def initialize(valuable)
@valuable = valuable
@volatile = "Goodbye"
end
<P></P>
def _dump(depth)
@valuable.to_str
end
<P></P>
def Special._load(str)
result = Special.new(str);
end
<P></P>
def to_s
"#{@valuable} and #{@volatile}"
end
end
<P></P>
a = Special.new("Hello, World")
data = Marshal.dump(a)
obj = Marshal.load(data)
puts obj
</pre></td></tr></table>
<em>produces:</em>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
Hello, World and Goodbye
</pre></td></tr></table>
<P></P>
For more details, see the reference section on <code>Marshal</code>
beginning on page 432.
<h3>Distributed Ruby</h3>
Since we can serialize an object or a set of objects into a form
suitable for out-of-process storage, we can use this capability for
the <em>transmission</em> of objects from one process to another.
Couple this capability with the power of networking, and
<em>voil</em>: you have a distributed object system. To save you
the trouble of having to write the code, we suggest downloading
Masatoshi Seki's Distributed Ruby library (drb) from the RAA.
<P></P>
Using drb, a Ruby process may act as a server, as a client, or as both. A
drb server acts as a source of objects, while a client is a user of
those objects. To the client, it appears that the objects are local,
but in reality the code is still being executed remotely.
<P></P>
A server starts a service by associating an object with a given port.
Threads are created internally to handle incoming requests on that
port, so remember to join the drb thread before exiting your program.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
require 'drb'
<P></P>
class TestServer
def doit
"Hello, Distributed World"
end
end
<P></P>
aServerObject = TestServer.new
DRb.start_service('druby://localhost:9000', aServerObject)
DRb.thread.join # Don't exit just yet!
</pre></td></tr></table>
<P></P>
A simple drb client simply creates a local drb object and associates
it with the object on the remote server; the local object is a proxy.
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
require 'drb'
DRb.start_service()
obj = DRbObject.new(nil, 'druby://localhost:9000')
# Now use obj
p obj.doit
</pre></td></tr></table>
<P></P>
The client connects to the server and calls the method <code>doit</code>, which
returns a string that the client prints out:
<P></P>
<table bgcolor="#fff0f0" cellspacing="0" border="0" cellpadding="3" width="400"><tr><td><pre>
"Hello, Distributed World"
</pre></td></tr></table>
<P></P>
The initial <code>nil</code> argument to <code>DRbObject</code> indicates that we want
to attach to a new distributed object. We could also use an
existing object.
<P></P>
Ho hum, you say. This sounds like Java's RMI, or CORBA, or whatever.
Yes, it is a functional distributed object mechanism---but it is
written in just 200 lines of Ruby code. No C, nothing fancy, just
plain old Ruby code. Of course, there's no naming service or trader
service, or anything like you'd see in CORBA, but it is simple and
reasonably fast. On the 233MHz test system, this sample code runs at
about 50 remote message calls per second.
<P></P>
And, if you like the look of Sun's JavaSpaces, the basis of their JINI
architecture, you'll be interested to know that drb is distributed with
a short module that does the same kind of thing. JavaSpaces is based
on a technology called Linda. To prove that its Japanese author has a
sense of humor, Ruby's version of Linda is known as ``rinda.''
<h2>Compile Time? Runtime? Anytime!</h2>
<P></P>
The important thing to remember about Ruby is that there isn't a big
difference between ``compile time'' and ``runtime.'' It's all the
same. You can add code to a running process. You
can redefine methods on the fly, change their scope from <code>public</code>
to <code>private</code>, and so on. You can even alter basic types, such
as <code>Class</code> and <code>Object</code>.
<P></P>
Once you get used to this flexibility, it is hard to go back to a
static language such as C++, or even to a half-static language such as
Java.
<P></P>
But then, why would you want to?
<p></p><hr><table bgcolor="#a03030" cellpadding="10" border="0" cellspacing="0"><tr><td width="33%" align="left"><a class="subheader" href="taint.html">Previous <</a></td><td width="33%" align="center" valign="middle"><a class="subheader" href="index.html">Contents ^</a><br></td><td width="33%" align="right"><a class="subheader" href="builtins.html">Next ></a><br></td></tr></table><p></p><font size="-1">Extracted from the book "Programming Ruby -
The Pragmatic Programmer's Guide"</font><br><font size="-3">
Copyright
©
2000 Addison Wesley Longman, Inc. Released under the terms of the
<a href="http://www.opencontent.org/openpub/">Open Publication License</a> V1.0.
<br>
This reference is available for
<a href="http://www.pragmaticprogrammer.com/ruby/downloads/book.html">download</a>.
</font></body></html>
|