<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>brain driven development &#187; ruby</title>
	<atom:link href="http://gleichmann.wordpress.com/category/ruby/feed/" rel="self" type="application/rss+xml" />
	<link>http://gleichmann.wordpress.com</link>
	<description>a development driven blog</description>
	<lastBuildDate>Wed, 21 Oct 2009 18:45:43 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain='gleichmann.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://www.gravatar.com/blavatar/471b116f17b3834243906296b3ae9511?s=96&#038;d=http://s.wordpress.com/i/buttonw-com.png</url>
		<title>brain driven development &#187; ruby</title>
		<link>http://gleichmann.wordpress.com</link>
	</image>
			<item>
		<title>ruby ruminations &#8211; singleton class</title>
		<link>http://gleichmann.wordpress.com/2007/11/21/ruby-ruminations-singleton-class/</link>
		<comments>http://gleichmann.wordpress.com/2007/11/21/ruby-ruminations-singleton-class/#comments</comments>
		<pubDate>Wed, 21 Nov 2007 21:47:19 +0000</pubDate>
		<dc:creator>Mario Gleichmann</dc:creator>
				<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://gleichmann.wordpress.com/2007/11/21/ruby-ruminations-singleton-class/</guid>
		<description><![CDATA[some call it singleton class, some metaclass or even eigenclass.
in this blog entry i will give some explanation about the concept of singleton class (which i will call it during this post) and some (more or less useful) examples of its application.
you&#8217;re one-of-a-kind
as you may know, ruby lets you enhance single objects by adding a [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gleichmann.wordpress.com&blog=2165876&post=14&subd=gleichmann&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>some call it singleton class, some metaclass or even eigenclass.<br />
in this blog entry i will give some explanation about the concept of singleton class (which i will call it during this post) and some (more or less useful) examples of its application.<span id="more-14"></span></p>
<h2><strong>you&#8217;re one-of-a-kind</strong></h2>
<p>as you may know, ruby lets you enhance single objects by adding a new method to just one instance of an arbitrary class, leveraging this specific object to a real &#8217;singleton&#8217; (in another sense, in contrast to the well known singleton pattern). since all methods are defined and housed in the objects class&#8217;, such new added methods also have to be &#8216;append&#8217; to and hence reside in the objects class.</p>
<p>lets say we want to add a  method palindrome? to only one specific instance of a string:</p>
<pre><font color="#333399">aString = "never odd or even"

class &lt;&lt; aString
    def palindrome?
        self.gsub(/\s/, '') == self.reverse.gsub(/\s/, '')
    end
end

aString.palindrome?
# =&gt; true</font></pre>
<p>only this single object of String now offers this new method palindrome? (a call to any other instance of String would result in a NoMethodError)</p>
<p>now one could ask, where this new method is going to reside. it can&#8217;t be send to the class String. if so, then all String objects would offer this method. that&#8217;s where our singleton class comes into the game &#8230;</p>
<h2><strong>especially for you</strong></h2>
<p>whenever a method is added to a single object in the above indicated way, ruby will create an extra class especially for that single object! and exactly this one is &#8211; you guessed right &#8211; our so called singleton class!</p>
<p>this singleton class is a virtual one, since it never appears as a fully-flegded member in the list of classes (remember that all classes are objects, which are accessible by their names as constants). ruby will insert this singleton class as the direct (again &#8211; virtual) class of the object. the former direct class &#8211; in the examples case the class String &#8211; will slide one level up, so the singleton class &#8217;sits&#8217; between the object and the original class of the object.<br />
now, whenever a method call (message) is send to the object, ruby will (as always) look at the direct class of the object, wheter the method is defined within that class. if so, ruby is happy and executes that method. if not, ruby will go to the ancestor (super) class (which is now the original classof the object) in order to track the message call and so on.</p>
<h2><strong>everywhere i go </strong></h2>
<p>we now saw the mechanism of how ruby is able to add methods to single instances. going one step further we could ask ourself if it&#8217;s possible to use this mechanism inside a class. we could for example offer a convenient instance method  palindromize() inside the class of String in order to add the palindrome?() method to arbitrary instances of String in a quick and easy way. and of course, it&#8217;s possible:</p>
<pre><font color="#333399">class String
    def palindromize
        class &lt;&lt; self
            def palindrome?
                self.gsub(/\s/, '') == self.reverse.gsub(/\s/, '')
            end
        end
    end
end

s = "otto"

s.respond_to?( :palindrome? )
# =&gt; false

s.palindromize
s.respond_to?( :palindrome? )
# =&gt; true</font></pre>
<p>note, that we now use <em>self</em> to &#8216;append&#8217; the new method. since we are inside an instance method, <em>self</em> refers to the object itself (on which the instance method is called) and hence the effect is the same as if you would append a new method to a single object explicitly outside a class (like in the first example)! we refer to a specific object instance in both cases.</p>
<h2><strong>catch me if you can</strong></h2>
<p>one interesting point is the scope of <em>self</em> inside of <em>class &lt;&lt; self &#8230; end</em>. as you may have suspected, we are in scope of that ominous singleton class, and you&#8217;re right &#8230;</p>
<pre><font color="#333399">class String
    def palindromize
        class &lt;&lt; self
            puts "#{self}"      # =&gt; #&lt;Class:#&lt;String:0x2b418e0&gt;&gt;
            ...
        end
    end
end </font></pre>
<p>as you can see, <em>puts</em> prints the &#8217;signature&#8217; of the singleton class &#8211; in the example&#8217;s case the singleton class for the String object <em>#&lt;String:0&#215;2b418e0&gt;</em> on which the method was called.<br />
this brings us to the point where we could dare a look at a often mentioned method (mostly even called singleton_class() or even metaclass() or eigenclass()) and understand easily what&#8217;s going on there:</p>
<pre><font color="#333399">class String # could be an arbitrary class
    def singleton_class
        class &lt;&lt; self; self; end
    end
end</font></pre>
<p>this instance(!) method is a convenient way to access the singleton class of an object on which the method gets called. as you can see (and nothing new to us), we refer to the singleton class again (<em>class &lt;&lt; self</em>), but this time not to define a new method inside the scope of that singleton class but to return the singleton class of that object itself (with <em>self</em> being the last evaluated expression of that method).</p>
<h2><strong>i count on you</strong></h2>
<p>catching that singleton class as an object gives us completely new options towards a way of metaprogramming or at least a kind of generic programming. for example, it&#8217;s easy to add this method inside a module together with some generic functions that operate on the singleton class of an object:</p>
<pre><font color="#333399">module Appendable
    def singleton_class
        class &lt;&lt; self; self; end
    end</font><font color="#333399">

    def append_method( method_name, &amp;prc )
        singleton_class.class_eval do
            define_method( method_name, prc )
        end
    end</font><font color="#333399">
end</font></pre>
<p>so what&#8217;s going on here?<br />
first of all we have the above mentioned method aside that allows us to refer to the singleton class of an object. we access the singleton class inside the method append_method(), which takes a method name and a proc. both arguments will constitute a new method that will be appended to a single object via its singleton class.<br />
since we define such a method in a completely generic way in that the name of the method to append is dynamic, we use class_eval (so we can define parts of that method in a generic way and let ruby evaluate the whole expression).</p>
<p>now we&#8217;re able to append methods very dynamic to objects of an arbitrary class which includes that module:</p>
<pre><font color="#333399">class Prototype
    include Appendable
end</font><font color="#333399">

p = Prototype.new
p.append_method( :say_hello ){|n| puts "hello #{n}" }
p.say_hello( 'Dave' )
# =&gt; hello Dave</font></pre>
<p>using <em>include</em> (in contrast to <em>extend</em>) includes the modul&#8217;s methods as instance methods. that&#8217;s what we need, since we want to catch an objects singleton class. having done so enables us to append arbitrary methods to our Prototype class in a dynamic way. calling the modul&#8217;s <em>append_method()</em>, passing a method name and a block will lead to the dynamic added method (remember, that the last argument <em>&amp;prc</em> inside the argument list of append_method() will implicit call <em>to_proc</em> which will transfer the given block into a proc object).</p>
<h2><strong>no magic at all</strong></h2>
<p>as you&#8217;ve seen, there&#8217;s no magic about this often mentioned singleton class, metaclass or eigenclass. it&#8217;s one of rubys mechanisms which allows for dynamic programming and high flexibility.<br />
once you have seen and understand the semantics behind these concept, it should be easy to build your own functionality on top of this instrument &#8230;</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/gleichmann.wordpress.com/14/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/gleichmann.wordpress.com/14/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gleichmann.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gleichmann.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gleichmann.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gleichmann.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gleichmann.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gleichmann.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gleichmann.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gleichmann.wordpress.com/14/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gleichmann.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gleichmann.wordpress.com/14/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gleichmann.wordpress.com&blog=2165876&post=14&subd=gleichmann&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://gleichmann.wordpress.com/2007/11/21/ruby-ruminations-singleton-class/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">mario.gleichmann</media:title>
		</media:content>
	</item>
		<item>
		<title>ruby ruminations &#8211; composing Procs</title>
		<link>http://gleichmann.wordpress.com/2007/11/21/ruby-ruminations-composing-procs/</link>
		<comments>http://gleichmann.wordpress.com/2007/11/21/ruby-ruminations-composing-procs/#comments</comments>
		<pubDate>Wed, 21 Nov 2007 21:23:31 +0000</pubDate>
		<dc:creator>Mario Gleichmann</dc:creator>
				<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://gleichmann.wordpress.com/2007/11/21/ruby-ruminations-composing-procs/</guid>
		<description><![CDATA[last week i had some time to play around with ruby again. in order to get deeper into it, i startet to study some foreign ruby code. amongst others, i found some very interesting libraries called ruby facets. having a look at some of their implementations caused some headache at first, but on the other [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gleichmann.wordpress.com&blog=2165876&post=13&subd=gleichmann&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p style="text-align:justify;">last week i had some time to play around with ruby again. in order to get deeper into it, i startet to study some foreign ruby code. amongst others, i found some very interesting libraries called ruby facets. having a look at some of their implementations caused some headache at first, but on the other side gave some motivation to understand what&#8217;s happening and why it&#8217;s happening in a certain way. risking a second look and having some ruminations about that code maybe gets me just a little step nearer to the white side of the force &#8230;<span id="more-13"></span></p>
<p style="text-align:justify;"> this blog entry is the first one in a series of so called ruby ruminiations, where i will pick some simple looking ruby code, asking what&#8217;s going on there.<br />
i will start with a pretty small extension of class Proc, which i found in the above mentioned ruby facets core library.</p>
<p>now here is that little darling, asking me for some extra time to stay with&#8217;em:</p>
<blockquote></blockquote>
<pre><font color="#333399"><font face="Courier New">class Proc</font></font><font color="#333399" face="Courier New">
    def *(g)
        raise ArgumentError, "arity count mismatch" unless arity == g.arity
        proc{ |*a| self[*g[*a] ] }
    end</font>
<font color="#333399"><font face="Courier New">end</font></font></pre>
<blockquote></blockquote>
<p>but from the very first &#8230;<br />
as you can see, we extend the build-in class Proc, since all of ruby&#8217;s classes are open for that kind of extension.</p>
<h2><font>Procs</font></h2>
<p>Procs are &#8211; simply said &#8211; some block of code, that have been bound to a set of local variables (see the pickaxe book). This bunch of code is captured and represented by a Proc object that can be called at any time after it&#8217;s definition:<font color="#333399"> </font></p>
<pre><font color="#333399" face="Courier New">double = Proc.new {|x| x * 2 }
double.call( 5 ) # =&gt; 10</font></pre>
<p>alternatively you can use the so called lambda operator, which will instantiate a given code block as a Proc object:</p>
<pre><font color="#333399">h</font><font color="#333399" face="Courier New">alf_of = lambda {|x| x / 2 }
half_of.call( 8 ) # =&gt; 4</font></pre>
<p style="text-align:justify;">and &#8211; not enough &#8211; another way to define a proc is using Kernel#proc:</p>
<pre><font color="#333399">square = proc {|x|x*x}
square( 4 ) # =&gt; 16</font><font>
</font></pre>
<p style="text-align:justify;">&nbsp;</p>
<h2><font>i spy with my little eye something beginning with &#8230;</font></h2>
<p>as seen, Procs can take an arbitrary number of arguments (&#8216;x&#8217; as the only argument in the above examples), delivering a return value which is by default evaluated as the last expression inside that code block &#8211; so a Proc looks like an anonymous method, which can be assigned to a variable.</p>
<p>But more than a method, a Proc is able to refer to the set of local variables bound to the context it was defined within (even if that context isn&#8217;t visible anymore to the callers environment):</p>
<pre><font color="#333399" face="courier new,courier">def salutation( male ,female )</font><font color="#333399" face="courier new,courier">
    female_names = [:Alicia, :Samantha, :Kathy]</font><font color="#333399"> </font><font color="#333399" face="courier new,courier">
    male_names = [:John,:Ben,:Harvey]</font><font color="#333399" face="courier new,courier">

    lambda do |name|</font><font color="#333399" face="courier new,courier">
        return female + name if female_names.include? name.intern</font><font color="#333399" face="courier new,courier">
        return male + name if male_names.include? name.intern</font><font color="#333399" face="courier new,courier">
        "Dear " + name</font><font color="#333399" face="courier new,courier">
    end</font><font color="#333399" face="Courier New">
end

salutation_friends = salutation("Yo ","Hi ")</font><font color="#333399" face="Courier New">
salution_pen_pals = salutation("Howdy ","Hello ")

puts salutation_friends.call("Ben")
# =&gt; 'Yo Ben'</font><font color="#333399" face="Courier New">

puts salution_pen_pals.call("Alicia")
# =&gt; 'Hello Alicia'</font><font color="#333399" face="Courier New">

puts salution_pen_pals.call("Dave")
# =&gt; 'Dear Dave'</font></pre>
<p>first of all, the two arrays defining the known male and female names are (only) visible inside the scope of method salutation(). but even after the method execution ends, the created Proc refers to that arrays when called afterwards. this is also true for the given arguments with which the method salutation() gets called. even if we invoke the method more than once with different arguments, the created Proc &#8216;remembers&#8217; those different values!<br />
furthermore, you surely have noticed that we used the do&#8230;end syntax for defining the code block. this is a very suitable way when having a code block with more than one line.</p>
<h2><font>it&#8217;s not a bird</font></h2>
<p>we can use another notation in order to invoke a Proc object. up to now, we called Proc&#8217;s instance method call() for invocation. as a shortcut you can always use []. when i saw this notation the first time, i was bit of confused &#8211; this seems a little odd since it may remind you of the notion of an array. of course ruby lets you override the [] operator in any class you want to, and so it is for class Proc as a synonym for Proc#call.</p>
<pre><font color="#333399" face="Courier New">puts salutation_friends["Kathy"]
# =&gt; 'Hi Kathy'</font></pre>
<p>whatever way you&#8217;ll choose to invoke a Proc object, you may want to know the correct number of arguments a Proc object can handle. in this case you can use the instance method Proc#arity on the object. it will betray the number of arguments, which will be processed by the Proc&#8217;s instance.<br />
in case you have a Proc object that accepts an argument array (we will have a deeper look at this kind of argument in the next section) Proc#arity will return a negative number &#8211; begining with -1 for only having an argument array, decreasing the number with every additional mentioned single argument:</p>
<pre><font color="#333399">lambda {|arg1|}.arity
# =&gt; 1

lambda {|arg1,arg2,arg3|}.arity
# =&gt; 3

lambda {|*args|}.arity
# =&gt; -1

lambda {|arg1,*args|}.arity
# =&gt; -2

lambda {|arg1,arg2,arg3,arg4,*args|}.arity
# =&gt; -5</font></pre>
<h2><font>open-hearted</font></h2>
<p>Procs are very communicative! as mentioned before, you can pass an arbitrary number of arguments to a Proc object. it&#8217;s also possible to use the array notation like in method definitions in order to access a dynamic number of arguments:</p>
<pre><font color="#333399">pick = lambda {|pos,*cards| cards[pos-1] if pos &gt; 0 and pos &lt; cards.size}

pick[3, 'diamonds', 'hearts', 'spades', 'clubs']
# =&gt; 'spades'</font></pre>
<p>you have to be careful when delegating an argument array to a Proc object, for example inside a method. if you forget to use the asterisk again when calling the Proc with the given argument array, the Proc will only receive a single, &#8216;joined&#8217; argument:</p>
<pre><font color="#333399" face="Courier New">def start_play(pick,*cards)</font><font color="#333399" face="Courier New">
    # here we delegate the argument array correctly</font><font color="#333399" face="Courier New">
    pick[1, *cards]</font><font color="#333399"> </font><font color="#333399" face="Courier New">
end

def next_move( pick, *cards )</font><font color="#333399" face="Courier New">
    # oops, we missed the asterisk !</font><font color="#333399" face="Courier New">
    pick[2, cards]</font><font color="#333399" face="Courier New">
end

first_card=start_play (pick,'diamonds','hearts','spades','clubs')
# =&gt; 'diamonds'

second_card=next_move (pick,'diamonds','hearts','spades','clubs' )
# =&gt; nil</font></pre>
<p>the same is true for return value(s). since you are able to return more than one value in ruby, you could return an array of return values:</p>
<pre><font color="#333399">words_with_length = lambda do|c,*words|
    hits = []
    words.each do |word|
        hits &lt;&lt; word if word.size == c
    end
    hits
end

words_with_length [4,"Sue","Mike","Walter","Tara","Beth","David" ]
# =&gt; ['Mike', 'Tara', 'Beth']</font></pre>
<p>again, if you want to pass an result array of a Proc as an argument to another Proc which can handle an argument array (sounds as if we could nest calls of Proc objects, eh?), again you have to watch out not to forget the asterisk! otherwise your result array will be also handed over as a single, joined argument:</p>
<pre><font color="#333399">line_print = lambda do |*words|
    words.each_index do |i|
        puts "#{i+1} #{words[i]}"
    end
end

# ok, asterisk on board !
line_print[ *words_with_length [4,"Sue","Mike","Walter","Tara","Beth","David"]]

1 Mike
2 Tara
3 Beth

# ouch, missed again:
line_print[ words_with_length [4,"Sue","Mike","Walter","Tara","Beth","David"]]

1 MikeTaraBeth</font></pre>
<h2><font>inside out</font></h2>
<p>now we have enough information to get back to our &#8216;darling from page 1&#8242; &#8230; here&#8217;s the code again:</p>
<blockquote></blockquote>
<pre><font color="#333399"><font face="Courier New">class Proc</font></font>
    <font color="#333399" face="Courier New">def *(g)
        raise ArgumentError, "arity count mismatch" unless arity == g.arity
        proc{ |*a| self[*g[*a] ] }
    end</font><font color="#333399"><font face="Courier New">
end</font></font></pre>
<p>now it&#8217;s easy to understand what&#8217;s happening inside the method Proc#*. we will go through the code from inside out:<br />
first of all, we can see, that the method will create and return another Proc object (using Kernel#proc for instaniating the Proc object), which will accept a dynamic range of arguments.</p>
<p>this argument array is passed to the proc named g. it&#8217;s the argument of Proc#*(as the newly created and returned Proc object is able to refer to all variables of its defining context, it of course can refer to Prog g when it will be called).</p>
<p>we know furthermore, that we have to keep the asterisk when passing the argument array to a Proc instance, thus also when passing it to Proc g, using the []-operator notation (&#8216;g<font color="#ff0000">[*a]</font>&#8216;).</p>
<p>So what happens next? at the end of Proc g&#8217;s execution it may will return one return value or even a return value array. since we want to be generic, we allow an arbitrary number of return values (which subsumes all Procs which will return one or no return value at all).</p>
<p>the call of Proc g is nested inside the call of the current Proc object (which is represented by &#8217;self&#8217;). so the argument of self Proc is the return of Proc g (never fear, we&#8217;ve already seen nested calls before and this is pretty the same thing).<br />
since Proc g returns at least an arbitrary number of arguments which shall be passed as an argument array to the self Proc as the receiver, again we have to keep the asterisk (&#8217;self[<font color="#ff0000">*</font>g[*a]&#8216;).</p>
<p>thats all of the relevant stuff. before creating this new Proc, which is nesting the calls of self Proc and the Proc given as the argument, there is a check, if the number of arguments of these two Procs are the same. otherwise an exception is raised. from my point of view this check acts only as a kind of makeshift, since we should check if the number of return values of the inner Proc meets the number of arguments the outer Proc is willing to accept.</p>
<p>we now could use our new notation of composing two procs:</p>
<pre><font color="#333399">square = lambda {|x| x*x}
cube_length = lambda{|volume|volume**(1.0/3)}

cube_area = square * cube_length

cube_area[100]
# =&gt; 21.5443469003188</font></pre>
<p>this is a pretty small example, but it illustrates the idea very well.<br />
composing Proc objects can now be done in a simple, concise way. since ruby doesn&#8217;t demand dot notation for method calls (the asterisk between the two Procs is automatically assumed to be a method of the object that stands on the left side of the method&#8217;s identifier) we have gained a nice and readable way of Proc composition.</p>
<p>but beside that, we may have got a little deeper insight of how Procs do their job &#8230; ;o)</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/gleichmann.wordpress.com/13/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/gleichmann.wordpress.com/13/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gleichmann.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gleichmann.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gleichmann.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gleichmann.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gleichmann.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gleichmann.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gleichmann.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gleichmann.wordpress.com/13/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gleichmann.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gleichmann.wordpress.com/13/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gleichmann.wordpress.com&blog=2165876&post=13&subd=gleichmann&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://gleichmann.wordpress.com/2007/11/21/ruby-ruminations-composing-procs/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">mario.gleichmann</media:title>
		</media:content>
	</item>
		<item>
		<title>ruby metaprogramming I</title>
		<link>http://gleichmann.wordpress.com/2007/11/21/ruby-metaprogramming-i/</link>
		<comments>http://gleichmann.wordpress.com/2007/11/21/ruby-metaprogramming-i/#comments</comments>
		<pubDate>Wed, 21 Nov 2007 21:06:07 +0000</pubDate>
		<dc:creator>Mario Gleichmann</dc:creator>
				<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://gleichmann.wordpress.com/2007/11/21/ruby-metaprogramming-i/</guid>
		<description><![CDATA[just played a little with some basic groundwork of ruby&#8217;s potentials upon metaprogramming. metaprogramming still is and even will become more important in regard to the increasing relevance due to domain specific languages (dsl). in the context of modeling such a dsl and expressing domain specific concepts within it, metaprogramming is a powerful and very [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gleichmann.wordpress.com&blog=2165876&post=11&subd=gleichmann&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>just played a little with some basic groundwork of ruby&#8217;s potentials upon metaprogramming. metaprogramming still is and even will become more important in regard to the increasing relevance due to domain specific languages (dsl). in the context of modeling such a dsl and expressing domain specific concepts within it, metaprogramming is a powerful and very flexible option, since it will provide the full power of ruby&#8217;s features when it comes to modeling domain concepts.<span id="more-11"></span></p>
<p>with the rise of java 6 and especially the support for scripting languages (jsr 223 &#8211; scripting for the java platform) such potentials could become strategic, since half typed languages like java are quite inflexible for extensions due to domain specific needs. scripting languages like ruby could play an important role in the next future, since it will be very easy to interoperate. given this, one could take the power of both sides java and ruby, when it comes to the implementation of applications. one could apply the right instrument to the approriate parts of an application in order to benefit from the strength of each particular language. for example, web application layer could be done using rails, but java provides its full power under the hood when asking for security, transactionional services, distribution or integration of legacy systems. the core business logic (especially where the domain drives complexity) could be expressed using a domain specific language, again falling back to ruby&#8217;s above mentioned potentials &#8230;</p>
<p>so much for the motivation &#8230; now to the action &#8230;</p>
<h2><strong>come in &#8211; we&#8217;re open, too</strong></h2>
<p>one basic feature of ruby&#8217;s possibilities due to metaprogramming is its facility of extending almost everything, even &#8216;build in&#8217; classes. so its very easy to enrich a given class with new features.</p>
<p>if we would ask a number if it&#8217;s an odd one, we would receive a reaction like the following:</p>
<pre><font color="#333399" face="courier new,courier" size="2"> &gt; 23.odd?</font> <font color="#333399" face="courier new,courier" size="2">
NoMethodError: undefined method `odd?' for 23:Fixnum</font></pre>
<p>this is normal behaviour since class Fixnum doesn&#8217;t provide such a method.<br />
but thanks to the openness of classes, we can enhance Fixnum at any time and pay for a new method:</p>
<pre><font color="#333399">class Fixnum</font> <font color="#333399">
    def odd?</font> <font color="#333399">
        self % 2 == 1</font> <font color="#333399">
    end</font> <font color="#333399">
end</font></pre>
<p>if we now ask the number a second time, the sun will shine again &#8230;</p>
<pre><font color="#333399" face="courier new,courier" size="2">&gt; 23.odd?</font>
<font color="#333399" size="2">=&gt; true</font></pre>
<h2><strong> enhancing class features</strong></h2>
<p>what about enhancing the features of class itself?<br />
you may know about &#8216;attr_reader&#8217; or &#8216;attr_writer&#8217; in order to define instance properties without explicitly defining &#8216;getters&#8217; and &#8217;setters&#8217; (sorry, i&#8217;m originally a java guy).</p>
<pre><font color="#333399" face="courier new,courier">class Person</font> <font color="#333399" face="courier new,courier">   </font> <font color="#333399" face="courier new,courier">
    attr_reader :firstname, :lastname, :birthday</font> <font color="#333399" face="courier new,courier">   </font> <font color="#333399" face="courier new,courier">
    attr_writer :firstname, :lastname, :birthday</font> <font color="#333399" face="courier new,courier"> </font> <font color="#333399" face="courier new,courier">
end</font></pre>
<p>we have to do so &#8211; declaring attr_reader for offering &#8216;getter&#8217; and declaring attr_writer for offering &#8217;setter&#8217; functionality &#8211; because there&#8217;s no feature of declaring both &#8217;setter&#8217; and &#8216;getter&#8217; in one go.<br />
now, if we would consider it nice to have such a feature &#8211; let&#8217;s enhance &#8230;</p>
<p>since everything is an object in Ruby world, also Class is nothing more than a specific class that &#8211; among others &#8211; inherits from Object, you can of course also enhance the definition of class and let all class definitions (which &#8216;uses&#8217; Class) benefit from that enhancements:</p>
<pre><font color="#333399" face="courier new,courier" size="2">class Class</font> <font color="#333399" face="courier new,courier" size="2">    </font> <font color="#333399" face="courier new,courier" size="2">
    def attr_rw( *attrib_names )</font> <font color="#333399" face="courier new,courier" size="2">     </font> <font color="#333399" face="courier new,courier" size="2">
        attrib_names.each do |name|</font> <font color="#333399" face="courier new,courier" size="2">       </font> <font color="#333399" face="courier new,courier" size="2">
            attr_reader name</font> <font color="#333399" face="courier new,courier" size="2">
            attr_writer name</font> <font color="#333399" face="courier new,courier" size="2">
        end</font> <font color="#333399" face="courier new,courier" size="2">
    end</font> <font color="#333399" face="courier new,courier" size="2">
end</font></pre>
<p style="background-color:#ffffff;">as you can see, Class now owns a new method attr_rw, which delegates the passed property names to both attr_reader and attr_writer, means that both &#8216;getter&#8217; and &#8217;setter&#8217; functionality will be assigned.</p>
<p style="background-color:#ffffff;">we now could use this new feature as it would be a normal &#8216;keyword&#8217; of the language, like attr_reader or attr_writer:</p>
<pre><font color="#333399">class Person</font> <font color="#333399">  </font> <font color="#333399">
    attr_rw :firstname, :lastname, :birthday</font> <font color="#333399">
end</font></pre>
<p>admitted, this is a very simple example, but it shows the power of enhancing the &#8216;core&#8217; language with new &#8216;concepts&#8217; quite well.<br />
it&#8217;s a first step towards the way of metaprogramming &#8230;</p>
<img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/gleichmann.wordpress.com/11/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/gleichmann.wordpress.com/11/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gleichmann.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gleichmann.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/gleichmann.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/gleichmann.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/gleichmann.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/gleichmann.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/gleichmann.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/gleichmann.wordpress.com/11/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/gleichmann.wordpress.com/11/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/gleichmann.wordpress.com/11/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gleichmann.wordpress.com&blog=2165876&post=11&subd=gleichmann&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://gleichmann.wordpress.com/2007/11/21/ruby-metaprogramming-i/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">mario.gleichmann</media:title>
		</media:content>
	</item>
	</channel>
</rss>