<?xml version="1.0" encoding="UTF-8"?>
<feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom">
  <title>life.events.each { |event| learn_from(event) } - Home</title>
  <id>tag:blog.withoutincident.com,2008:mephisto/</id>
  <generator version="0.7.3" uri="http://mephistoblog.com">Mephisto Noh-Varr</generator>
  <link href="http://blog.withoutincident.com/feed/atom.xml" rel="self" type="application/atom+xml"/>
  <link href="http://blog.withoutincident.com/" rel="alternate" type="text/html"/>
  <updated>2008-06-16T23:03:00Z</updated>
  <entry xml:base="http://blog.withoutincident.com/">
    <author>
      <name>shadowfiend</name>
    </author>
    <id>tag:blog.withoutincident.com,2008-06-16:113</id>
    <published>2008-06-16T22:58:00Z</published>
    <updated>2008-06-16T23:03:00Z</updated>
    <category term="Coding"/>
    <link href="http://blog.withoutincident.com/2008/6/16/awesome_fields-gets-a-formbuilder-new-headerize-plugin" rel="alternate" type="text/html"/>
    <title>awesome_fields Gets A FormBuilder, New headerize Plugin</title>
<summary type="html">&lt;p&gt;I haven&#8217;t been able to work on Quill too much lately, in part because I lost my stylus somewhere along the way (new one should be forthcoming today, actually) and in part because my day job involves Rails at the moment, so that&#8217;s the world my mind has been in. What I have been working on is my &lt;code&gt;awesome_fields&lt;/code&gt; plugin and a new plugin, &lt;a href=&quot;http://github.com/Shadowfiend/headerize&quot;&gt;&lt;code&gt;headerize&lt;/code&gt;&lt;/a&gt;. Actually, the `work&#8217; I have done on these has been extracting some stuff that I commonly do in my Rails projects into plugins. There&#8217;s very little that is technically new code from me there, though the &lt;code&gt;headerize&lt;/code&gt; plugin is well spec&#8217;ed-out.&lt;/p&gt;


	&lt;p&gt;Anyway, so &lt;a href=&quot;http://github.com/Shadowfiend/awesome_fields&quot;&gt;&lt;code&gt;awesome_fields&lt;/code&gt;&lt;/a&gt; has received a &lt;code&gt;LinedBuilder&lt;/code&gt; for creating better marked-up forms with less effort, and &lt;code&gt;headerize&lt;/code&gt; was created to facilitate putting all your stylesheets and scripts in one place (typically the document head) while still being able to include them from the view. That way, the stylesheet that needs to be included by the _form partial is included there, so that it is spatially near to the place where it is used, while the actual markup for it goes in the head, where it belongs. So I&#8217;ll hit these two separately&#8230;&lt;/p&gt;</summary><content type="html">
            &lt;p&gt;I haven&#8217;t been able to work on Quill too much lately, in part because I lost my stylus somewhere along the way (new one should be forthcoming today, actually) and in part because my day job involves Rails at the moment, so that&#8217;s the world my mind has been in. What I have been working on is my &lt;code&gt;awesome_fields&lt;/code&gt; plugin and a new plugin, &lt;a href=&quot;http://github.com/Shadowfiend/headerize&quot;&gt;&lt;code&gt;headerize&lt;/code&gt;&lt;/a&gt;. Actually, the `work&#8217; I have done on these has been extracting some stuff that I commonly do in my Rails projects into plugins. There&#8217;s very little that is technically new code from me there, though the &lt;code&gt;headerize&lt;/code&gt; plugin is well spec&#8217;ed-out.&lt;/p&gt;


	&lt;p&gt;Anyway, so &lt;a href=&quot;http://github.com/Shadowfiend/awesome_fields&quot;&gt;&lt;code&gt;awesome_fields&lt;/code&gt;&lt;/a&gt; has received a &lt;code&gt;LinedBuilder&lt;/code&gt; for creating better marked-up forms with less effort, and &lt;code&gt;headerize&lt;/code&gt; was created to facilitate putting all your stylesheets and scripts in one place (typically the document head) while still being able to include them from the view. That way, the stylesheet that needs to be included by the _form partial is included there, so that it is spatially near to the place where it is used, while the actual markup for it goes in the head, where it belongs. So I&#8217;ll hit these two separately&#8230;&lt;/p&gt;
&lt;h2&gt;&lt;code&gt;awesome_fields&lt;/code&gt; and the &lt;code&gt;LinedBuilder&lt;/code&gt;&lt;/h2&gt;


	&lt;p&gt;Let&#8217;s face it, one thing Rails sucks at is facilitating the creation of labeled form fields. Outputting errors for form fields is also a bit repetitive out of the box. It seems like this begs for a bit of &lt;span class=&quot;caps&quot;&gt;DRY&lt;/span&gt; goodness that can live in a custom &lt;code&gt;FormBuilder&lt;/code&gt;. Enter the &lt;code&gt;LinedBuilder&lt;/code&gt;, whose purpose is to make explicit labels and errors as much a part of the turbulent past as possible.&lt;/p&gt;


	&lt;p&gt;Basically, the &lt;code&gt;LinedBuilder&lt;/code&gt; gives you the usual methods, such as &lt;code&gt;text_field&lt;/code&gt;, &lt;code&gt;text_area&lt;/code&gt;, etc, but it gives them labels, wraps them in a div, and automatically includes errors in them if necessary. So let&#8217;s say I had my form:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;html&quot;&gt;&amp;lt;% form_for @model do |f| %&amp;gt;
  &amp;lt;p&amp;gt;
    &amp;lt;%= error_message_on 'model', 'name' %&amp;gt;
    &amp;lt;label for=&quot;model_name&quot;&amp;gt;Name: &amp;lt;/label&amp;gt;
    &amp;lt;%= f.text_field 'name' %&amp;gt;
  &amp;lt;/p&amp;gt;

  &amp;lt;p&amp;gt;
    &amp;lt;%= error_message_on 'model', 'author' %&amp;gt;
    &amp;lt;label for=&quot;model_author&quot;&amp;gt;Author: &amp;lt;/label&amp;gt;
    &amp;lt;%= f.text_field 'author' %&amp;gt;
  &amp;lt;/p&amp;gt;
&amp;lt;% end %&amp;gt;&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;That&#8217;s a lot of typing, plus it&#8217;s repetitive. With &lt;code&gt;awesome_fields&lt;/code&gt; (and therefore &lt;code&gt;LinedBuilder&lt;/code&gt;):&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;html&quot;&gt;&amp;lt;% lined_form_for @model do |f| %&amp;gt;
  &amp;lt;%= f.text_field 'name' %&amp;gt;
  &amp;lt;%= f.text_field 'author' %&amp;gt;
&amp;lt;% end %&amp;gt;&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Dearie me, that does look cleaner. Behind the scenes, this means we will get:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;html&quot;&gt;&amp;lt;form ...&amp;gt;
  &amp;lt;div class=&quot;form_line&quot;&amp;gt;
    &amp;lt;label for=&quot;model_name&quot;&amp;gt;Name: &amp;lt;/label&amp;gt;
    &amp;lt;input type=&quot;text&quot; id=&quot;model_name&quot; name=&quot;model[name]&quot; value=&quot;...&quot; /&amp;gt;
  &amp;lt;/div&amp;gt;
  &amp;lt;div class=&quot;form_line&quot;&amp;gt;
    &amp;lt;label for=&quot;model_author&quot;&amp;gt;Author: &amp;lt;/label&amp;gt;
    &amp;lt;input type=&quot;text&quot; id=&quot;model_author&quot; name=&quot;model[author]&quot; value=&quot;...&quot; /&amp;gt;
  &amp;lt;/div&amp;gt;
&amp;lt;/form&amp;gt;&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;And, if there is an error on the name field from &lt;code&gt;validates_presence_of&lt;/code&gt;, we get:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;html&quot;&gt;&amp;lt;form ...&amp;gt;
  &amp;lt;div class=&quot;form_line_with_errors&quot;&amp;gt;
    &amp;lt;div class=&quot;field_error&quot;&amp;gt;Name should not be blank.&amp;lt;/div&amp;gt;
    &amp;lt;label for=&quot;model_name&quot;&amp;gt;Name: &amp;lt;/label&amp;gt;
    &amp;lt;input type=&quot;text&quot; id=&quot;model_name&quot; name=&quot;model[name]&quot; value=&quot;...&quot; /&amp;gt;
  &amp;lt;/div&amp;gt;
  &amp;lt;div class=&quot;form_line&quot;&amp;gt;
    &amp;lt;label for=&quot;model_author&quot;&amp;gt;Author: &amp;lt;/label&amp;gt;
    &amp;lt;input type=&quot;text&quot; id=&quot;model_author&quot; name=&quot;model[author]&quot; value=&quot;...&quot; /&amp;gt;
  &amp;lt;/div&amp;gt;
&amp;lt;/form&amp;gt;&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;As an additional bonus, say &lt;code&gt;validates_presence_of&lt;/code&gt; and &lt;code&gt;validates_numericality_of&lt;/code&gt; both fired, the error becomes:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;html&quot;&gt;  &amp;lt;div class=&quot;form_line_with_errors&quot;&amp;gt;
    &amp;lt;div class=&quot;field_error&quot;&amp;gt;Name should not be blank and should be a number.&amp;lt;/div&amp;gt;
    &amp;lt;label for=&quot;model_name&quot;&amp;gt;Name: &amp;lt;/label&amp;gt;
    &amp;lt;input type=&quot;text&quot; id=&quot;model_name&quot; name=&quot;model[name]&quot; value=&quot;...&quot; /&amp;gt;
  &amp;lt;/div&amp;gt;&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;This is because, if the object returned by &lt;code&gt;errors.[]&lt;/code&gt; responds to &lt;code&gt;to_sentence&lt;/code&gt;, then it is converted into a sentence. Since Rails defines an excellent such method for arrays, we get the above pretty output.&lt;/p&gt;


	&lt;p&gt;So that&#8217;s the &lt;code&gt;LinedBuilder&lt;/code&gt; in a nutshell. There are a few options you can pass. If using the automatic label (which is the humanized name of the field) doesn&#8217;t cut it, you can pass in a &lt;code&gt;:label&lt;/code&gt; option with the text you want to use. If you don&#8217;t want a label, you can pass in a &lt;code&gt;:no_label&lt;/code&gt; option set to true. And finally, if you need to distinguish between labels for long and short fields, you can pass in a &lt;code&gt;:long&lt;/code&gt; option set to true. If you do this with a call to &lt;code&gt;text_area&lt;/code&gt;, it will also adjust the default number of rows and columns.&lt;/p&gt;


	&lt;p&gt;For more information, see the &lt;a href=&quot;http://github.com/Shadowfiend/awesome_fields/tree/4411fcdab9dcd00c3ce1a8724bdb44b43e63d42b/lib/awesome_fields/lined_builder.rb&quot;&gt;RDocs in the source file&lt;/a&gt; . To install the plugin on Rails &amp;lt;=2.0:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;git clone git://github.com/Shadowfiend/awesome_fields.git vendor/plugins/awesome_fields&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;If you are using git, make sure to:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;rm -R vendor/plugins/awesome_fields/.git&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;So that you can check in the code. If you&#8217;re running Rails 2.1, then you can hit up:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;script/plugin install git://github.com/Shadowfiend/awesome_fields.git&lt;/code&gt;&lt;/pre&gt;

	&lt;h2&gt;&lt;code&gt;headerize&lt;/code&gt;&#8212;Javascript and Stylesheets Where They Belong&lt;/h2&gt;


	&lt;p&gt;In addition to the changes to &lt;code&gt;awesome_fields&lt;/code&gt;, &lt;code&gt;headerize&lt;/code&gt; is a new plugin that lets you put your JS and stylesheet tags where they belong (in the head of your document, technically, though some people put JS at the bottom as a loading speed optimization) while letting you include them wherever you want.&lt;/p&gt;


	&lt;p&gt;When would you use this? For Javascript, if you&#8217;re trying to write unobtrusive Javascript, you usually want to include a file for your particular view. So say you&#8217;ve got a form, and you want to make it remote. But, you want this not to clutter up your &lt;span class=&quot;caps&quot;&gt;HTML&lt;/span&gt;. So, you including a JS file called &lt;code&gt;remote_forms.js&lt;/code&gt; that has the unobtrusive javascript to make things work.&lt;/p&gt;


	&lt;p&gt;Trouble is, you don&#8217;t want to include it on every page. One way to do this is to include it anyway and just use a &lt;span class=&quot;caps&quot;&gt;CSS&lt;/span&gt; class or somesuch to ensure that only forms with the `remote&#8217; class get the behavior. But another way is just to include the script only on pages that need it. The same goes for stylesheets: if there&#8217;s no form on a page, why include the styles for it?&lt;/p&gt;


	&lt;p&gt;Since the layout in Rails is separate from the view you are rendering, however, it is annoying to include anything per-view. &lt;code&gt;headerize&lt;/code&gt; takes care of this problem. After installing it, it makes two helpers available: &lt;code&gt;add_javascript&lt;/code&gt; and &lt;code&gt;add_stylesheet&lt;/code&gt; (both exist in pluralized forms for readability when taking care of multiple items). These each behave exactly like &lt;code&gt;javascript_include_tag&lt;/code&gt; and &lt;code&gt;stylesheet_link_tag&lt;/code&gt;, only they don&#8217;t drop their links into the &lt;span class=&quot;caps&quot;&gt;HTML&lt;/span&gt; right where they are called. Instead, wherever you want your stylesheets and Javascript, you insert the output of &lt;code&gt;javascript_includes&lt;/code&gt; and &lt;code&gt;stylesheet_links&lt;/code&gt;.&lt;/p&gt;


	&lt;p&gt;For example, to deal with the above situation, I could have a layout &lt;code&gt;application.html.haml&lt;/code&gt; (in &lt;a href=&quot;http://haml.hamptoncatlin.com&quot;&gt;&lt;span class=&quot;caps&quot;&gt;HAML&lt;/span&gt;&lt;/a&gt;):&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;haml&quot;&gt;!!! XML
!!!
%html
  %head
    %title My Site
    = stylesheet_links
    = javascript_includes
  %body
    = yield&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;And, in your &lt;code&gt;new&lt;/code&gt; view, say &lt;code&gt;new.html.erb&lt;/code&gt; (in &lt;span class=&quot;caps&quot;&gt;ERB&lt;/span&gt;):&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;rhtml&quot;&gt;&amp;lt;% add_stylesheet 'forms'
  add_javascript 'remote_forms' %&amp;gt;
&amp;lt;% form_for @model do |f| %&amp;gt;
  &amp;lt;%= f.field_for :name %&amp;gt;
  &amp;lt;%= f.field_for :date %&amp;gt;
&amp;lt;% end %&amp;gt;&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;That&#8217;s it. When the view is rendered, the layout will have the right stylesheets and Javascript includes right there, easy as pie. Note that this has some implications on fragment caching (since the links and includes are built every time, if you fragment cache the portion including the stylesheet calls and it is not re-evaluated, then the stylesheets and includes will not function correctly). Also note that these functions can be called from partials, so for example an _form partial can always include the relevant stylesheets and forms and no matter where it is rendered from, the correct stuff will be included.&lt;/p&gt;


	&lt;p&gt;Also worth mentioning, as presented before, the calls to &lt;code&gt;add_stylesheet&lt;/code&gt; and &lt;code&gt;add_javascript&lt;/code&gt; are exactly the same as their inline counterparts, so you could easily do any of these:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;rhtml&quot;&gt;&amp;lt;% add_stylesheet 'print', :media =&amp;gt; 'print'
   add_javascripts 'remote_forms', 'remote_links', :cache =&amp;gt; 'remote_stuff' %&amp;gt;&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;As before, for more information, see the &lt;a href=&quot;//github.com/Shadowfiend/headerize&quot;&gt;RDocs in the source&lt;/a&gt; . To install the plugin on Rails &amp;lt;=2.0:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;git clone git://github.com/Shadowfiend/headerize.git vendor/plugins/headerize&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Again, if you are using git, make sure to:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;rm -R vendor/plugins/awesome_fields/.git&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;So that you can check in the code. If you&#8217;re running Rails 2.1, then you can hit up:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;script/plugin install git://github.com/Shadowfiend/headerize.git&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;And that&#8217;s all folks! Hope some of you get some use out of these plugins!&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://blog.withoutincident.com/">
    <author>
      <name>shadowfiend</name>
    </author>
    <id>tag:blog.withoutincident.com,2008-04-30:111</id>
    <published>2008-04-30T21:49:00Z</published>
    <updated>2008-05-01T23:42:32Z</updated>
    <category term="Coding"/>
    <link href="http://blog.withoutincident.com/2008/4/30/code-magic_fields-code-moves-to-github-renamed-to-code-awesome_fields-code" rel="alternate" type="text/html"/>
    <title>magic_fields Moves to GitHub, Renamed to awesome_fields</title>
<content type="html">
            &lt;p&gt;So Software Without Incident (the site) kind of disappeared a little while ago due to some accidents while I was toying around on the server. The &lt;span class=&quot;caps&quot;&gt;SVN&lt;/span&gt; repository&#8217;s still sitting there on my server, though, so my code&#8217;s still around. And I still pull &lt;code&gt;magic_fields&lt;/code&gt; into my new projects. I am a particular fan of the collection handling, if I do say so myself. The name, however, clashes with a term given to Rails&#8217;s built-in `magic fields&#8217; for ActiveRecord, things like &lt;code&gt;updated_at&lt;/code&gt; and &lt;code&gt;created_at&lt;/code&gt;. So I took advantage of the situation to rename the plugin &lt;code&gt;awesome_fields&lt;/code&gt;, too, so it&#8217;s a little more distinguishable.&lt;/p&gt;


	&lt;p&gt;Anyway, I went ahead and used git-svn to pull the code from the &lt;span class=&quot;caps&quot;&gt;SWI&lt;/span&gt; repository into a git repository and then pushed it off to GitHub. I&#8217;m more a fan of Bazaar myself (the documentation for it is amazing, and the commandset is readable; plus, there&#8217;s no required -a parameter for committing everything, which is the way I happen to work), but I know the Rails community is on git-mania now, so git it is. For the interested, it&#8217;s under &lt;a href=&quot;http://github.com/Shadowfiend/awesome_fields/tree/master&quot;&gt;awesome_fields&lt;/a&gt; at GitHub.&lt;/p&gt;


	&lt;p&gt;Documentation and a &lt;span class=&quot;caps&quot;&gt;README&lt;/span&gt; await there.&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://blog.withoutincident.com/">
    <author>
      <name>shadowfiend</name>
    </author>
    <id>tag:blog.withoutincident.com,2008-04-04:109</id>
    <published>2008-04-04T05:03:00Z</published>
    <updated>2008-04-04T05:30:54Z</updated>
    <category term="Coding"/>
    <link href="http://blog.withoutincident.com/2008/4/4/qt-radial-menu-for-quill" rel="alternate" type="text/html"/>
    <title>Qt Radial Menu for Quill</title>
<summary type="html">&lt;p&gt;In my forays into the world of creating a &lt;a href=&quot;http://www.trolltech.com/qt&quot;&gt;Qt&lt;/a&gt; journal application, part of what I wanted to achieve was a really easy way to get to common actions like tool changes. My two biggest gripes with &lt;a href=&quot;http://xournal.sourceforge.net/&quot;&gt;Xournal&lt;/a&gt; were always (a) that I had to keep adding an extra page after the one I was working on if I wanted to be able to see the bottom of this one (I fixed this in Quill, and made adding a new page easier, by introducing a `virtual&#8217; last page, which does not appear on any output but gives you scrolling space and, when drawn upon, becomes a regular full-blown page) and (b) that if I wanted to change tools or colors, I had to shoot up to the toolbar to do it. That&#8217;s just no fun.&lt;/p&gt;


	&lt;p&gt;So, my latest foray into &lt;a href=&quot;https://launchpad.net/quill&quot;&gt;Quill&lt;/a&gt; has been adding a radial menu to the canvas area, so that you can get a menu for doing stuff in a way optimized for the stylus. The coolest aspect of this was that it let me develop my own Qt widget, of course. The results, though, were pretty good, I thought:&lt;/p&gt;


	&lt;p&gt;&lt;img src=&quot;http://blog.withoutincident.com/assets/2008/4/4/radialMenu.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;


	&lt;p&gt;Details follow&#8230;&lt;/p&gt;</summary><content type="html">
            &lt;p&gt;In my forays into the world of creating a &lt;a href=&quot;http://www.trolltech.com/qt&quot;&gt;Qt&lt;/a&gt; journal application, part of what I wanted to achieve was a really easy way to get to common actions like tool changes. My two biggest gripes with &lt;a href=&quot;http://xournal.sourceforge.net/&quot;&gt;Xournal&lt;/a&gt; were always (a) that I had to keep adding an extra page after the one I was working on if I wanted to be able to see the bottom of this one (I fixed this in Quill, and made adding a new page easier, by introducing a `virtual&#8217; last page, which does not appear on any output but gives you scrolling space and, when drawn upon, becomes a regular full-blown page) and (b) that if I wanted to change tools or colors, I had to shoot up to the toolbar to do it. That&#8217;s just no fun.&lt;/p&gt;


	&lt;p&gt;So, my latest foray into &lt;a href=&quot;https://launchpad.net/quill&quot;&gt;Quill&lt;/a&gt; has been adding a radial menu to the canvas area, so that you can get a menu for doing stuff in a way optimized for the stylus. The coolest aspect of this was that it let me develop my own Qt widget, of course. The results, though, were pretty good, I thought:&lt;/p&gt;


	&lt;p&gt;&lt;img src=&quot;http://blog.withoutincident.com/assets/2008/4/4/radialMenu.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;


	&lt;p&gt;Details follow&#8230;&lt;/p&gt;
&lt;p&gt;Part of the awesomeness that is Qt is that every QWidget has an associated list of QActions. QWidgets in Qt are the base graphical unit&#8212;equivalent to Swing&#8217;s Component, for example. QActions are an encapsulated way of representing various actions. They are used equally in menus and toolbar, so, for example, the File&amp;gt;New action and the New toolbar button would be separate representations of the same QAction object. A model, if you will, for actions the user can take, where the toolbar and the menu represent views.&lt;/p&gt;


	&lt;p&gt;Bearing this in mind, I decided to model the RadialMenu class&#8217;s &lt;span class=&quot;caps&quot;&gt;API&lt;/span&gt; closely after QMenu&#8217;s &lt;span class=&quot;caps&quot;&gt;API&lt;/span&gt;. The advantage of this approach is that I had a model for what functions I &lt;em&gt;should&lt;/em&gt; have. And, indeed, I implemented most of them. The exceptions were few and involved things that made sense for a QMenu but not for the radial variant, and a few things that I decided to wait on until later if they became necessary. I also added a couple of useful functions specific to RadialMenu (such as centerOn() to center it on a particular point). I did not, however, extend QMenu, as the provided functionality is, I believe, too different. Perhaps in the future the functionality will align more and such an inheritance chain might be merited.&lt;/p&gt;


	&lt;p&gt;The truly painful part was implementing painting. Because Qt has styles that can style the interface differently, and some of these styles use native painting routines (as with Windows and &lt;span class=&quot;caps&quot;&gt;OS X&lt;/span&gt;), I had to model the radial gradient I needed for the menu using the Plastique style as a guide. It won&#8217;t look quite as similar to the current style&#8217;s widgets in styles other than Plastique, but it&#8217;s a good approximation. Also problematic in this context was positioning the icons. I wanted to make RadialMenu flexible, so it would adjust to the number of actions needed correctly. Thus, we have the effect of something that works equally well with the five items seen above, or with three or even six:&lt;/p&gt;


	&lt;p&gt;&lt;img src=&quot;http://blog.withoutincident.com/assets/2008/4/4/radialMenuLessItems.png&quot; alt=&quot;&quot; /&gt; &lt;img src=&quot;http://blog.withoutincident.com/assets/2008/4/4/radialMenuMoreItems.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;


	&lt;p&gt;Notice that at six we start running into some issues. Basically, the current painting code, when determining the size of the icons, only takes into account the distance between the outer radius and the inner radius&#8212;it does not take into account the distance between the right and left button boundaries at their narrowest. The painting code, however, is clearly adjustable.&lt;/p&gt;


	&lt;p&gt;Finally, RadialMenu takes care of highlighting hovered items and pressed items. Plus, thanks to QAction&#8217;s signals, the currently selected item amongst a list of, say, tools, is kept synced with the equivalent entries in the toolbar, even when both are open at the same time.&lt;/p&gt;


	&lt;p&gt;&lt;img src=&quot;http://blog.withoutincident.com/assets/2008/4/4/radialMenuHovered.png&quot; alt=&quot;&quot; /&gt; &lt;img src=&quot;http://blog.withoutincident.com/assets/2008/4/4/radialMenuPressed.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;


	&lt;p&gt;RadialMenu currently also supports, in the QAction, having a QAction with an associated RadialMenu. QActions by default can be associated with a menu, but I did not want to overload that concept&#8212;I wanted a QAction associable with both a QMenu and a RadialMenu at the same time. To this end, QActions have the concept of arbitrary user data set via the excellent QVariant class that can be used to transport essentially arbitrary data. For RadialMenu&#8217;s purposes, QAction&#8217;s user data is currently expected to be a RadialMenu when a RadialMenu should be associated to it. It is very likely that this will switch to being one of the arbitrary properties QObjects can have set and retrieved via setProperty() and property() with the name `radialMenu&#8217;. Note that the submenus aren&#8217;t currently popped up yet.&lt;/p&gt;


	&lt;p&gt;Finally, you may have noticed a small wrench in the middle of some of the screenshots. Currently there are two ways to get a hold of this menu. The first is to press the middle mouse button, which on my stylus at least is mapped to holding the side button down and pressing it. This will bring up the radial menu centered on the mouse position. The second way is that wrench. When the stylus pressure goes to zero, Quill waits for a short timeout and then displays, offset slightly from the location where the stylus was lifted, a small button:&lt;/p&gt;


	&lt;p&gt;&lt;img src=&quot;http://blog.withoutincident.com/assets/2008/4/4/toolButton.png&quot; alt=&quot;&quot; /&gt;&lt;/p&gt;


	&lt;p&gt;This button, when clicked, will also bring up the radial menu. I&#8217;m still not sure about this button and how much it gets in the way. I want to take a wait-and-see attitude on it and see what kind of feedback I get on its usefulness. I think it will be particularly nice when a stylus does not have an alternate button on it and the only way to get the menu will be to click on this one.&lt;/p&gt;


	&lt;p&gt;Also in the works for the radial menu, in addition to full support for submenus, is support for drag-based navigation of the menus; that is to say, clicking, holding, and then moving through to the final menu item you desire. This basically will make menu item selection a one-press affair, though the release will take a while to come. I also want to implement an alternate form of the pen width spinner more suited to the radial paradigm: basically a widget upon which drawing a circle clockwise will increase the value and counter-clockwise decrease it (this might need to be flipped in &lt;span class=&quot;caps&quot;&gt;RTL&lt;/span&gt; locales, as well). The idea is borrowed from InkSeine:http://research.microsoft.com/inkseine/, as referred to me on &lt;a href=&quot;https://bugs.launchpad.net/quill/+bug/209980&quot;&gt;this bug&lt;/a&gt; by Kovid Goyal.&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://blog.withoutincident.com/">
    <author>
      <name>shadowfiend</name>
    </author>
    <id>tag:blog.withoutincident.com,2008-01-03:103</id>
    <published>2008-01-03T06:00:00Z</published>
    <updated>2008-01-03T06:12:52Z</updated>
    <category term="Coding"/>
    <link href="http://blog.withoutincident.com/2008/1/3/quill-qt-tablet-journaling-program" rel="alternate" type="text/html"/>
    <title>Quill: Qt Tablet Journaling Program</title>
<content type="html">
            &lt;p&gt;What&#8217;s been keeping me up late at night recently? Well, recently, it&#8217;s been a side job; however, somewhat less recently, I started a program called Quill. Quill is a Qt equivalent to Xournal, which is a tablet journaling program written in Gtk. But I didn&#8217;t just want to make a Qt clone, as that&#8217;s neither here nor there. Instead, I used Quill to brush up on my Qt skills, as well as to play with some of the cool technology in Qt 4.3 (like the Graphics View framework and, to a much more restricted extent, scripting (which I haven&#8217;t yet been able to figure out very well)). Quill is hanging out on Launchpad at https://launchpad.net/quill. I chose Launchpad in part because I wanted to play with &lt;a href=&quot;http://bazaar-vcs.org/&quot;&gt;Bazaar&lt;/a&gt;, which I have been using since I set up the Launchpad site, and damn it&#8217;s hot. I only hope I get more opportunities to use it in the future.&lt;/p&gt;


	&lt;p&gt;Anyway, a couple of the features I&#8217;m playing with Quill. First off, I&#8217;m adding buttons to the bottoms of pages to allow inserting pages in the middle relatively easily and with no menu interaction. Likewise with deletion of a page. In addition, there&#8217;s always a ``virtual page&#8217;&#8217; after the last actual page. Writing on this page will make it a full-fledged page, but it does not appear in any printing or &lt;span class=&quot;caps&quot;&gt;PDF&lt;/span&gt; exports. This basically makes it a very easy way to add a page to the end of a document. Finally, if you hold the cursor relatively still once you stop writing, a toolbar pops up with some commonly used tools.&lt;/p&gt;


	&lt;p&gt;A lot of things need work. Right now I&#8217;m working on getting the movement of a selection to work appropriately across saves. Currently, since such a change doesn&#8217;t break up strokes, reloading the page will connect the moved lines back to their original strokes, yielding some very strange streaks. I&#8217;m working on breaking strokes apart when moves like that happen, so that this works correctly. Also, the way the toolbar appears and when it does and where it does can get annoying. This is definitely an area for improvement.&lt;/p&gt;


	&lt;p&gt;And there is also, of course, performance. QGraphicsView and QGraphicsScene are fantastic pieces of technology, but their performance has some issues&#8212;especially when moving a selection, for example, where paint clipping becomes very apparent. I intend on looking at some of these issues to see if they can be resolved with clever coding, or if I&#8217;m just being an idiot to begin with. Additionally, after a random time period, the drawing based on stylus input becomes very very very noticeably slow. I&#8217;m still not sure why this is happening, but it&#8217;s definitely my fault, as saving the document at this point and then reloading it and continuing works fine.&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://blog.withoutincident.com/">
    <author>
      <name>shadowfiend</name>
    </author>
    <id>tag:blog.withoutincident.com,2007-12-17:75</id>
    <published>2007-12-17T15:17:00Z</published>
    <updated>2007-12-17T16:22:00Z</updated>
    <category term="Coding"/>
    <link href="http://blog.withoutincident.com/2007/12/17/declarative-optional-parameters-in-ruby" rel="alternate" type="text/html"/>
    <title>Declarative Optional Parameters in Ruby</title>
<summary type="html">&lt;p&gt;There&#8217;s a common pattern in Ruby for setting up keyword parameters&#8212;optional parameters with default values that are accepted as a hash at the end of the method call. Ruby&#8217;s syntax facilitates this, with end-hashes not requiring curly braces; instead, you can do this:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;obj.method :keyword =&amp;gt; 'value', :keyword2 =&amp;gt; 3&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Many people have written about various ways of implementing this in as painless a syntax as possible, but they all involve writing a lot of boilerplate. My intent is to write code that doesn&#8217;t require such boilerplate at all, instead providing a declarative way to say `here are the optional parameters, here are their default values&#8217; and have everything taken care of for you. Moreover, the ability to provide introspection into what optional parameters are expected at runtime and the default values thereof is also something I want to try and give.&lt;/p&gt;</summary><content type="html">
            &lt;p&gt;There&#8217;s a common pattern in Ruby for setting up keyword parameters&#8212;optional parameters with default values that are accepted as a hash at the end of the method call. Ruby&#8217;s syntax facilitates this, with end-hashes not requiring curly braces; instead, you can do this:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;obj.method :keyword =&amp;gt; 'value', :keyword2 =&amp;gt; 3&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Many people have written about various ways of implementing this in as painless a syntax as possible, but they all involve writing a lot of boilerplate. My intent is to write code that doesn&#8217;t require such boilerplate at all, instead providing a declarative way to say `here are the optional parameters, here are their default values&#8217; and have everything taken care of for you. Moreover, the ability to provide introspection into what optional parameters are expected at runtime and the default values thereof is also something I want to try and give.&lt;/p&gt;
&lt;h2&gt;Specing and Thought Process&lt;/h2&gt;


	&lt;p&gt;Just to clarify, as I write this, I will be BDDing it up, so RSpec code will come first. Moreover, I&#8217;m going to write this post in a stream-of-consciousnessesque fashion. This is just something I try to do so that my thought process in getting from point A (here&#8217;s an idea!) to point B (here&#8217;s how I&#8217;ll do it!) to point C (well that&#8217;s just dumb, let&#8217;s do it this way instead&#8230;) to point D (here&#8217;s a completed bit of code!) is exposed. It&#8217;s an interesting exercise for me, and I hope it&#8217;ll be interesting for you as a reader to see this process.&lt;/p&gt;


	&lt;p&gt;Also, this idea is fairly complete in my mind, and, though its usefulness may be questionable (it&#8217;ll induce some interesting overhead), I think it&#8217;s another interesting investigation into what you can achieve with Ruby, much like my earlier implementation of the `with&#8217; keyword.&lt;/p&gt;


	&lt;h2&gt;Syntactic Sketch&lt;/h2&gt;


	&lt;p&gt;What we&#8217;re trying to get to is a way of declaring optional parameters that is almost as good as declaring them in line. We can&#8217;t declare them in line, of course, because that isn&#8217;t supported by the syntax. The ideal syntax would be something vaguely like this:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;def my_method(arg1, arg2, :arg3 =&amp;gt; 5, :arg4 =&amp;gt; 'test')&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Since we can&#8217;t do this directly, we&#8217;ll change things up a bit. Let&#8217;s envision a situation where we do this instead:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;optional(:arg3 =&amp;gt; 5, :arg4 =&amp;gt; 'test', :arg5 =&amp;gt; 'magic')
def my_method(arg1, arg2)
  # ...
end&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Some people will likely be uncomfortable given the lack of indication as to where the `optional&#8217; method stops working (if I declare another method after that, does it still apply?). The idea would be that it would only apply for the next method definition; however, let&#8217;s provide an alternate syntax to clarify that:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;with_optional(:arg3 =&amp;gt; 5, :arg4 =&amp;gt; 'test', :arg5 =&amp;gt; 'magic') do
  def my_method(arg1, arg2)
    # ...
  end
end&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Naturally, a set of optional parameters can be shared with several methods with this syntax:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;with_optional(:arg3 =&amp;gt; 5, :arg4 =&amp;gt; 'test', :arg5 =&amp;gt; 'magic') do
  def my_method(arg1, arg2)
    # ...
  end

  def my_other_method(arg6, arg7)
    # ...
  end
end&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Ok, so now we have a sketch of what we want our syntax to look like. Let&#8217;s make it happen!&lt;/p&gt;


	&lt;h2&gt;A Little Bit of Planning&lt;/h2&gt;


	&lt;p&gt;First of all, let&#8217;s think about how things will fit together. Clearly, to do this, we&#8217;ll need to hook into method creation. Fortunately, Ruby provides the &lt;code&gt;Module#method_added&lt;/code&gt; method. This method gets called when a method is added to a module (or a class). It receives, as a parameter, the name of the new method that was defined.&lt;/p&gt;


	&lt;p&gt;So we can hook into when the method is created; what we can&#8217;t do is modify the code in the actual method at runtime (well, we probably could with &lt;code&gt;ParseTree&lt;/code&gt;, but let&#8217;s not go there). Instead, we&#8217;re going to wrap the new method with our own method that will sit in between and intercept calls and take care of optional parameters automagically.&lt;/p&gt;


	&lt;p&gt;Additionally, we&#8217;re going to need at least two methods: &lt;code&gt;optional&lt;/code&gt; and &lt;code&gt;with_optional&lt;/code&gt;. In fact, we can make these the same method (by checking &lt;code&gt;block_given?&lt;/code&gt; or whether a parameter &lt;code&gt;&#38;block&lt;/code&gt; is provided, we can just specialize within the method itself). We&#8217;ll also need some helpers&#8212;one to define the wrapper method, and one or two to set when we&#8217;re monitoring added methods and when we aren&#8217;t (i.e., we&#8217;d enable monitoring when we need to add optional parameters to whatever method(s) is/are defined next, and we&#8217;d disable it once we&#8217;re done with adding optional parameters).&lt;/p&gt;


	&lt;p&gt;The details of this breakup will become clearer as we create the actual code. The last thing we&#8217;re missing is how to provide the optional parameters to the method once we&#8217;re done. In a perfect world, we could maybe inject a local variable into the method at runtime and be happy, but we can&#8217;t really do that. We could also use some external instance or global variable, but that&#8217;s both dirty and not thread-safe in any way, shape or form. Instead, we&#8217;ll go for the still-intrusive but mildly less dirty approach of making the last parameter to the declared method be some sort of placeholder for the options. This modifies our syntax into:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;optional(:arg3 =&amp;gt; 5, :arg4 =&amp;gt; 'test', :arg5 =&amp;gt; 'magic')
def my_method(arg1, arg2, options)
  # ...
end&lt;/code&gt;&lt;/pre&gt;

	&lt;h2&gt;Initial Specs and Code&lt;/h2&gt;


	&lt;p&gt;Before writing any code, we&#8217;ll need to come up with some appropriate specs that will detail how we want the code to work. For each behavior (group of specs), we will create a new testing class to use.&lt;/p&gt;


	&lt;p&gt;Let&#8217;s start with the basic version&#8212;declaring a set of optional parameters for the next method.&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;require 'optional_params'

describe OptionalParams, 'when declaring parameters for the next method' do
  before(:all) do
    class TestClassA
      include OptionalParams # include OptionalParams functionality

      optional :birth =&amp;gt; Time.now
      def create_person(name, options)
        options
      end
    end
  end

  before(:each) do
    @test = TestClassA.new
  end

  it 'should pass the optional parameters in' do
    @test.create_person('dude', :birth =&amp;gt; 'w00t').should == { :birth =&amp;gt; 'w00t' }
  end

  it 'should fill in default values when needed' do
    @test.create_person('dude')[:birth].should be_kind_of(Time)
  end
end&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;This spec will fail initially since the optional_params.rb file doesn&#8217;t exist, then because the OptionalParams module doesn&#8217;t exist, and then because there&#8217;s still no #optional method. Let&#8217;s knock these three out in one shot:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;module OptionalParams
  def optional(params = {})
  end
end&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;The next error won&#8217;t actually be with the first example&#8212;the first example actually runs fine, since options just takes the value of the hash that&#8217;s passed in, the way it usually would. The next problem happens in the second example, where we have no default value specified. So it&#8217;s time to actually create some code that&#8217;ll do what we want it to. Let&#8217;s start with the basics:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;module OptionalParams
  module ClassMethods
    def optional(params = {})
      @next_optional_params = params
    end

    def optional_params
      @optional_params ||= {}
    end
  end

  def self.included(base)
    singleton = class &amp;lt;&amp;lt;base; self; end
    singleton.class_eval do
      def method_added(meth_name)
        return unless @next_optional_params # return if there's nothing to do

        old_name = &quot;#{meth_name}_without_params&quot; 
        new_name = &quot;#{meth_name}_with_params&quot; 

        # Store the parameters permanently, then clear it out so that we don't
        # do an infinite method_added loop.
        optional_params[meth_name] = @next_optional_params
        @next_optional_params = nil

        # Create the new method, doing whatever optional parameter housekeeping
        # needs to be done.
        define_method(new_name) do |*args|
          opt_params = (Hash === args.last) ? args.pop : {}

          opt_params = self.class.optional_params[meth_name].merge(opt_params)

          self.send old_name, *(args + [opt_params])
        end

        # alias_method_chain -- replace the just-created method, wrapping it
        # with our own optional parameter handling code.
        alias_method old_name, meth_name
        alias_method meth_name, new_name
      end

      include ClassMethods
    end
  end
end&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Okay, so let&#8217;s look at what&#8217;s going on here. First off, we see that the task of the &lt;code&gt;optional&lt;/code&gt; method is pretty minimal&#8212;it just sets up the next optional parameters instance variable for &lt;code&gt;method_added&lt;/code&gt; to use when it&#8217;s wrapping a method with optional parameter handling code&lt;sup&gt;&lt;a href=&quot;#fn1&quot;&gt;1&lt;/a&gt;&lt;/sup&gt;. There&#8217;s also another auxiliary method, &lt;code&gt;optional_params&lt;/code&gt;, which provides an accessor to an instance variable. This instance variable basically keeps track of the optional parameter lists for various method names&lt;sup&gt;&lt;a href=&quot;#fn2&quot;&gt;2&lt;/a&gt;&lt;/sup&gt;.&lt;/p&gt;


	&lt;p&gt;The real work is done by &lt;code&gt;method_added&lt;/code&gt;. &lt;code&gt;method_added&lt;/code&gt; starts off by just returning if it has nothing to do (i.e., if there is no next optional parameter that it needs to set up). Otherwise, it sets up the new names for methods&#8212;we follow the Rails &lt;code&gt;alias_method_chain&lt;/code&gt; convention of renaming the original method with an _without_feature and creating a new method with a _with_feature appended to the end that gets renamed to the original method name.&lt;/p&gt;


	&lt;p&gt;Once we&#8217;ve got the method names, we pull out the next optional parameters and record them permanently (remember, we didn&#8217;t know the method name until &lt;code&gt;method_added&lt;/code&gt; was called!), then we clear out the next params variable. Note that if we don&#8217;t do this, when we define our new method, we&#8217;ll try to set up optional params for it, and we&#8217;ll go into an infinite loop of method definition-method wrapping.&lt;/p&gt;


	&lt;p&gt;Then, we go ahead and define the new method. It follows a relatively common pattern of checking if the last parameter is already a hash, and, if it is, using it instead of creating our own. We then merge in our values, and finally we call the original method. We put the hash back into the list of parameters and splat these (effectively splitting the array into separate parameters instead of one array parameter). Finally, we rename the two methods so that everything&#8217;s set up the way it should be and our new method wraps the old one.&lt;/p&gt;


	&lt;p&gt;Here, by the way, the first example comes in useful&#8212;had we merged the wrong way (i.e., if we&#8217;d merged the passed parameters with the optional parameters rather than the other way around), that example would have failed.&lt;/p&gt;


	&lt;h2&gt;Adding Blocks&lt;/h2&gt;


	&lt;p&gt;Here&#8217;re some specs:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;describe OptionalParams, 'when declaring optional parameters for multiple methods' do
  before(:all) do
    class TestClassB
      include OptionalParams # include OptionalParams functionality

      with_optional(:birth =&amp;gt; Time.now, :weight =&amp;gt; 16.5) do # in pounds
        def create_person(name, options)
          options
        end

        def create_baby(name, options)
          options
        end
      end
    end
  end

  before(:each) do
    @test = TestClassB.new
  end

  it 'should fill in the optional parameters for all methods' do
    results = @test.create_person('w00t')
    other_results = @test.create_baby('other_w00t')

    results[:birth].should be_kind_of(other_results[:birth].class)
    results[:weight].should == other_results[:weight]
  end
end&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Adding the block version is a little more involved. We still need to clear out the next optional parameters variable in that case, so that we don&#8217;t get into the aforementioned infinite loop. However, we also need to keep it around so that if multiple method definitions are done, we can still use the same parameter list. So, we&#8217;ll go ahead and fill in some code. First, we&#8217;ll add the with_optional method, and then we&#8217;ll update method_added to work in a more friendly way.&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;  def with_optional(params = {}, &#38;block)
    # Store the parameters and raise the keep_params flag, which tells
    # +method_added+ to keep this variable around.
    @next_optional_params = params
    @keep_params = true

    self.class_eval &#38;block

    # Clear the parameters and the keep_params flag, effectively ending the
    # block of methods that will take these parameters.
    @next_optional_params = nil
    @keep_params = false
  end

  # ...
      def method_added(meth_name)
        # ...
        @next_optional_params = optional_params[meth_name] if @keep_params
      end
  # ...
end&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Here, we create the &lt;code&gt;with_optional&lt;/code&gt; method, which sets up the next params variable appropriately and also raises the &lt;code&gt;keep_params&lt;/code&gt; flag. This flag tells &lt;code&gt;method_added&lt;/code&gt; that it should keep the parameters around after it runs once. To do this, we add one last line to &lt;code&gt;method_added&lt;/code&gt;, which restores &lt;code&gt;next_optional_params&lt;/code&gt; if the &lt;code&gt;keep_params&lt;/code&gt; flag is raised. Once &lt;code&gt;with_optional&lt;/code&gt;&#8217;s block is done running, we go ahead and clear both the next params variable and the keep params flag.&lt;/p&gt;


	&lt;h2&gt;Metadata&lt;/h2&gt;


	&lt;p&gt;This gives us the basic structure for the functionality. All that&#8217;s left is adding one more bit of useful functionality: metadata. Right now, we declare the optional parameters and such, but the real win of our approach is the ability to get back information about what optional parameters are expected and what their default values are. Thus, we can modify the &lt;code&gt;method&lt;/code&gt; method to give us back, inside our &lt;code&gt;Method&lt;/code&gt; object, data about the optional parameters. We can also complete the wrapping of the original method by returning a &lt;code&gt;Method&lt;/code&gt; object with the original method&#8217;s characteristics (specifically, we can use the original method&#8217;s arity, rather than the new method, which will always have an arity of -1 (since it uses *args).&lt;/p&gt;


	&lt;p&gt;First, some specs; under &#8216;when declaring optional parameters for the next method&#8217;:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;  it &quot;should keep the original Method object's arity&quot; do
    @test.method(:create_person).arity.should == 2
  end

  it &quot;should provide access to the optional parameters through the Method object&quot; do
    opt_params = @test.method(:create_person).optional_params

    opt_params.keys.length.should == 1
    opt_params[:birth].should be_kind_of(Time)
  end&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;To achieve this, we&#8217;ll have to modify the Method object itself. To achieve this wrapping, we have to store the metadata, which we can do in method_added, and then we have to wrap the &lt;code&gt;method&lt;/code&gt; method to return a modified object. In the &lt;code&gt;self.included&lt;/code&gt; method, after we do the singleton&#8217;s &lt;code&gt;class_eval&lt;/code&gt;, we drop this in:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;      base.instance_eval do
      define_method(:method_with_metadata) do |meth_name|
        if self.class.optional_params[meth_name]
          params = self.class.optional_params[meth_name]
          initial = method_without_metadata(meth_name)
          orig = method_without_metadata(&quot;#{meth_name}_without_params&quot;)

          singleton = class &amp;lt;&amp;lt;initial; self; end
          singleton.class_eval do
            define_method(:optional_params) do
              params
            end

            define_method(:arity) do
              orig.arity
            end
          end

          initial
        else
          method_without_metadata(meth_name)
        end
      end

      alias_method :method_without_metadata, :method
      alias_method :method, :method_with_metadata
    end&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;First, we define the method_with_metadata method. Inside it, we check whether there are optional parameters for the named method (recall that the &lt;strong&gt;singleton class&lt;/strong&gt; stores the list of optional parameters). Then we grab the initial Method object for the specified method, modify it so it returns the regular, un-wrapped method&#8217;s arity and the optional parameters. The extensive use of define_method and blocks lets us share local variables like &lt;code&gt;orig&lt;/code&gt; and &lt;code&gt;params&lt;/code&gt;. If there are no optional parameters, we just pass through directly to the regular &lt;code&gt;method&lt;/code&gt; method. Then, we alias the methods appropriately.&lt;/p&gt;


	&lt;p&gt;This makes the specs for &lt;code&gt;optional&lt;/code&gt; pass; let&#8217;s add some for &lt;code&gt;with_optional&lt;/code&gt; and make sure they pass, too:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;  it &quot;should keep the original Method objects' arity&quot; do
    @test.method(:create_person).arity.should == 2
    @test.method(:create_baby).arity.should == 2
  end

  it &quot;should provide access to the optional parameters through the Method objects&quot; do
    opt_params = @test.method(:create_person).optional_params

    opt_params.keys.length.should == 2
    opt_params[:birth].should be_kind_of(Time)
    opt_params[:weight].should == 16.5

    opt_params = @test.method(:create_baby).optional_params

    opt_params.keys.length.should == 2
    opt_params[:birth].should be_kind_of(Time)
    opt_params[:weight].should == 16.5
  end&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;And there we go. These specs pass, as well.&lt;/p&gt;


	&lt;p&gt;You can find the two Ruby files here: &lt;a href=&quot;http://blog.withoutincident.com/assets/2007/12/17/optional_params_spec.rb&quot;&gt;optional_params_spec.rb&lt;/a&gt;, &lt;a href=&quot;http://blog.withoutincident.com/assets/2007/12/17/optional_params.rb&quot;&gt;optional_params.rb&lt;/a&gt; .&lt;/p&gt;


	&lt;h3&gt;Parting Remarks&lt;/h3&gt;


	&lt;p&gt;Again, this is a bit of a toy. The performance degradation from wrapping methods and such might outweigh the benefits of the cleaner syntax. However, having this to encapsulate the common optional parameter idiom is, I think, pretty cool, and again showcases the power of Ruby&#8217;s metaprogramming.&lt;/p&gt;


	&lt;p&gt;&lt;sup&gt;1&lt;/sup&gt; Clever people will point out that this technique will also not be particularly threadsafe. I&#8217;m thinking the best way to get around that is to store the next optional parameter list per-thread, using a hash indexed by the thread object.&lt;/p&gt;


	&lt;p&gt;&lt;sup&gt;2&lt;/sup&gt; As a side note, this means that technically we could use this technique to wrap methods in optional parameter handlers after the fact, as well.&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://blog.withoutincident.com/">
    <author>
      <name>shadowfiend</name>
    </author>
    <id>tag:blog.withoutincident.com,2007-10-22:71</id>
    <published>2007-10-22T20:15:00Z</published>
    <updated>2007-10-22T20:15:14Z</updated>
    <category term="Coding"/>
    <link href="http://blog.withoutincident.com/2007/10/22/rubyshell-update-a-better-validator-and-path-handling" rel="alternate" type="text/html"/>
    <title>RubyShell Update: A Better Validator? And Path Handling</title>
<summary type="html">&lt;p&gt;So it&#8217;s been a while since I&#8217;ve made a post on RubyShell. I&#8217;m still working on it, so no worries, I&#8217;ve just got a little less time than usual. Anyways, an update on some things I&#8217;m working on right now; namely, a better validator and some improved path handling.&lt;/p&gt;</summary><content type="html">
            &lt;p&gt;So it&#8217;s been a while since I&#8217;ve made a post on RubyShell. I&#8217;m still working on it, so no worries, I&#8217;ve just got a little less time than usual. Anyways, an update on some things I&#8217;m working on right now; namely, a better validator and some improved path handling.&lt;/p&gt;
&lt;h2&gt;Yay &lt;code&gt;SexpProcessor&lt;/code&gt;!&lt;/h2&gt;


	&lt;p&gt;So &lt;code&gt;ParseTree&lt;/code&gt; comes with a useful little class called &lt;code&gt;SexpProcessor&lt;/code&gt; that happily provides a way to visit nodes in the parse tree. Until now, I was using some nastiness in dealing with the sexps directly to figure out when I had calls that were invalid so I could mark them as invalid Ruby. Now, however, we do something different&#8230;&lt;/p&gt;


	&lt;p&gt;Thanks to &lt;code&gt;SexpProcessor&lt;/code&gt;, I&#8217;ve replaced this less-than-spectacular methodology with a simple &lt;code&gt;SexpProcessor&lt;/code&gt; subclass that looks for the first call (fcall, vcall, or call) and tracks what it was so it can be checked later. Currently, checks for overwriting assignments (assignments to variables that will shadow existing methods) are still done manually, through what is essentially a manual &lt;code&gt;SexpProcessor&lt;/code&gt;. I&#8217;ll be rolling that into the &lt;code&gt;ValidationProcessor&lt;/code&gt; (as the new class is called) sometime today. There&#8217;s some more promising stuff that can come out of this, as it&#8217;s a cleaner solution than what we had before. Fixing corner cases should hopefully be a little easier now.&lt;/p&gt;


	&lt;p&gt;For example, invalid initial method calls are currently always marked as commands (i.e., as invalid Ruby). This is bad, as sometimes there are invalid method calls that are still clearly Ruby but are passed on to the shell as a command anyway. Here&#8217;s one:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
RubyShell&amp;gt; math.magic { |test| power }
Error: Command `math.magic' not found.
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;That should still be processed as Ruby, and instead give a Ruby error. The processor will let us do this more easily, as we can look for, say, an :iter node (for a block) and decide that that will always be valid Ruby, even if it errors out when it runs.&lt;/p&gt;


	&lt;h2&gt;Paths as First-Class Citizens&lt;/h2&gt;


	&lt;p&gt;Daniel Draper mentioned in a comment on the 0.5 release announcement post an interesting possibility:&lt;/p&gt;


&lt;blockquote&gt;
I’d love to do this:

	&lt;p&gt;Have a dir called foo/bar/ that has say 100 directories in it.&lt;/p&gt;


	&lt;p&gt;Simply do&lt;/p&gt;


	&lt;p&gt;ls foo/bar.first to see whats in the first one of those&lt;/p&gt;


	&lt;p&gt;or maybe&lt;/p&gt;


	&lt;p&gt;ls foo/bar.children.first&lt;/p&gt;


	&lt;p&gt;Then if you wanted to move all dirs up a level you could do&lt;/p&gt;


	&lt;p&gt;foo/bar.children.each_with_parent { |c,parent| mv c, parent.parent }&lt;/p&gt;


and so on.
&lt;/blockquote&gt;

	&lt;p&gt;My brain pondered this quietly for a few days, and now I&#8217;ve taken quite a liking to the idea. I&#8217;ve already opened a feature request on Rubyforge to keep track of my progress on this. Basically, i want to see if I can make paths first-class citizens.&lt;/p&gt;


	&lt;p&gt;Path notation, it bears mentioning, is fairly closely-related to Ruby&#8217;s regular expression syntax and/or its division syntax. This introduces some interesting complications if we try and support `directory literals&#8217;, so to speak, within Ruby. So instead, I decided to opt for a middle way. Within the context of commands (i.e., code that has been marked as invalid Ruby), I intend on doing some additional parsing and creating actual path objects that can be operated upon like objects. For this purpose, I&#8217;ve created a new &lt;code&gt;RubyShell::Parsing&lt;/code&gt; module to contain the &lt;code&gt;Parser&lt;/code&gt; and &lt;code&gt;CommandParser&lt;/code&gt; that will do that extra handling. Alias handling will also be moved into there.&lt;/p&gt;


	&lt;p&gt;Now, in the context of Ruby code, you&#8217;ll still be able to access the same functionality, but you&#8217;ll need to do it via a method. Right now, I&#8217;m thinking it&#8217;ll probably be named path. So you&#8217;d do something like &lt;code&gt;path('foo/bar').children.each_with_parent ...&lt;/code&gt;. It might be shortened to something else, like d (e.g., &lt;code&gt;d('foo/bar').children...)&lt;/code&gt;. Finally, I&#8217;m thinking of whether I&#8217;ll allow this kind of manipulation without that method invocation if it&#8217;s the first thing on the line. So, for example:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
RubyShell&amp;gt; foo/bar.children.each_with_parent { |c,parent| mv c, parent.parent }
RubyShell&amp;gt;  foo/bar.children.each_with_parent { |c,parent| mv c, parent.parent }
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;The former would run as if it had been a call to &lt;code&gt;path('foo/bar')&lt;/code&gt;. The latter wouldn&#8217;t, because it isn&#8217;t literally the first thing on the line (there were some issues with the leading whitespace being stripped before it was processed earlier for the alias command (which does the same thing&#8212;alias turns into alias_cmd if it&#8217;s the first thing on the line, for shortening purposes), but I think I&#8217;ve knocked those out). We&#8217;ll see whether I&#8217;ll implement this latter one or not, as I don&#8217;t want to make too many exceptions like that.&lt;/p&gt;


	&lt;p&gt;Anyway, that&#8217;s an update of what&#8217;s in the works! Output redirection is also in the back of my mind, so no worries there. I just need to sit down and map out how the implementation is going to work.&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://blog.withoutincident.com/">
    <author>
      <name>shadowfiend</name>
    </author>
    <id>tag:blog.withoutincident.com,2007-09-17:57</id>
    <published>2007-09-17T02:16:00Z</published>
    <updated>2008-01-03T06:00:31Z</updated>
    <category term="Coding"/>
    <link href="http://blog.withoutincident.com/2007/9/17/rubyshell-0-5-objects-files-interpolation-and-aliasing" rel="alternate" type="text/html"/>
    <title>RubyShell 0.5: Objects, Files, Interpolation, and Aliasing</title>
<summary type="html">&lt;p&gt;The latest release of RubyShell is so cool, it&#8217;s skipping right over 0.4 and straight to 0.5. If you want to skip the explanation, you can go ahead and &lt;a href=&quot;http://rubyforge.org/frs/?group_id=4319&#38;release_id=14527&quot;&gt;download it now&lt;/a&gt;.&lt;/p&gt;


	&lt;p&gt;It bears mentioning also that this release marks the first release of RubyShell on &lt;a href=&quot;http://rubyforge.org/projects/rbsh/&quot;&gt;Rubyforge&lt;/a&gt;. Thanks to Rubyforge for being awesome :)&lt;/p&gt;</summary><content type="html">
            &lt;p&gt;The latest release of RubyShell is so cool, it&#8217;s skipping right over 0.4 and straight to 0.5. If you want to skip the explanation, you can go ahead and &lt;a href=&quot;http://rubyforge.org/frs/?group_id=4319&#38;release_id=14527&quot;&gt;download it now&lt;/a&gt;.&lt;/p&gt;


	&lt;p&gt;It bears mentioning also that this release marks the first release of RubyShell on &lt;a href=&quot;http://rubyforge.org/projects/rbsh/&quot;&gt;Rubyforge&lt;/a&gt;. Thanks to Rubyforge for being awesome :)&lt;/p&gt;
&lt;p&gt;RubyShell 0.5 adds some tasty flavors to the table with four new treats. First up are shell objects.&lt;/p&gt;


	&lt;h3&gt;Shell Objects&lt;/h3&gt;


	&lt;p&gt;Shell objects are not my idea :) viraptor waited until the moment that RubyShell was on Rubyforge to unleash this cool little concept. Basically, these are objects that represent handy Ruby interfaces to useful concepts. Along with an initial implementation, viraptor provided two such object classes: ps and if_config. ps is used to get to information about processes, while if_config gives information about network interfaces (just like their command counterparts). Here are some examples of using ps (with some parts abbreviated):&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
RubyShell&amp;gt; procs.collect { |proc| proc.name } .inspect
=&amp;gt;[&quot;init&quot;, &quot;migration/0&quot;, &quot;ksoftirqd/0&quot;, &quot;migration/1&quot;, &quot;ksoftirqd/1&quot;,
&quot;events/0&quot;, &quot;events/1&quot;, &quot;khelper&quot;, &quot;kthread&quot;, &quot;kblockd/0&quot;, &quot;kblockd/1&quot;, 
&quot;kacpid&quot;, &quot;ksuspend_usbd&quot;, ...,&quot;artsd&quot;]
RubyShell&amp;gt; ps.named('nspluginviewer').inspect
=&amp;gt;[#&amp;lt;RubyShell::ShellObjects::Ps::Process:0xb78a3b8c @name=&quot;nspluginviewer&quot;,
@cmdline=[&quot;/usr/kde/3.5/bin/nspluginviewer&quot;, &quot;-dcopid&quot;, &quot;nspluginviewer-27450&quot;], @pid=27521&amp;gt;]
RubyShell&amp;gt; ps.named(/ns/).inspect
=&amp;gt;[#&amp;lt;RubyShell::ShellObjects::Ps::Process:0xb7878edc @name=&quot;mdnsd&quot;, @cmdline=[&quot;/usr/sbin/mdnsd&quot;],
 @pid=6809&amp;gt;, #&amp;lt;RubyShell::ShellObjects::Ps::Process:0xb785ac20 @name=&quot;nspluginviewer&quot;,
@cmdline=[&quot;/usr/kde/3.5/bin/nspluginviewer&quot;, &quot;-dcopid&quot;, &quot;nspluginviewer-27450&quot;], @pid=27521&amp;gt;]
RubyShell&amp;gt; ps.pids.inspect
=&amp;gt; [1, 2, 3, 4, 5, 6, 7, 8, 9, 88, 89, 90, 223, 226, 228, 240, 261, 262, 263, 861, 1019,
1066, 1068, 1069, 5006, 5090, 5173, 5174, 5180, 5181, 5182, 5183, 5186, 5199,
5201, 5337, 5381, 5443, 5532, 5949, 6060, 6202, 6224, 6225, 6226, 6316, 6633, ..., 29380, 31581]
RubyShell&amp;gt; ps.from_pid(1).inspect
=&amp;gt;#&amp;lt;RubyShell::ShellObjects::Ps::Process:0xb783a948 @cmdline=[&quot;init [3]&quot;], @pid=1&amp;gt;
RubyShell&amp;gt; ps.from_name('init').inspect
=&amp;gt;#&amp;lt;RubyShell::ShellObjects::Ps::Process:0xb7834ae8 @name=&quot;init&quot;, @cmdline=[&quot;init [3]&quot;], @pid=1&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;You can also kill a process (ps.from_pid(1).kill &#8216;TERM&#8217;, for example) and do a few other things like check if it&#8217;s alive or if it&#8217;s a kernel process and get the parent process.&lt;/p&gt;


	&lt;p&gt;A couple of bugs made their way into the 0.5 release, including output that doesn&#8217;t call inspect automatically on its results and a ruby indicator that isn&#8217;t followed by a space. There&#8217;s also a bug in the Process class used in ps that means if it&#8217;s printed without an inspect, an error arises. These will all be fixed in RubyShell 0.6 (and, in fact, already are in trunk).&lt;/p&gt;


	&lt;p&gt;Here is some of what you can do with if_config:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
RubyShell&amp;gt; if_config.interfaces.inspect
=&amp;gt;[#&amp;lt;RubyShell::ShellObjects::IfConfig::Base::Interface:0xb780ace8 @name=&quot;lo&quot;&amp;gt;,
#&amp;lt;RubyShell::ShellObjects::IfConfig::Base::Interface:0xb780ac48 @name=&quot;eth0&quot;&amp;gt;]
RubyShell&amp;gt; if_config.names.inspect
=&amp;gt;[&quot;lo&quot;, &quot;eth0&quot;]
RubyShell&amp;gt; if_config['eth0']
=&amp;gt;#&amp;lt;RubyShell::ShellObjects::IfConfig::Base::Interface:0xb77f4c2c @name=&quot;eth0&quot;&amp;gt;
RubyShell&amp;gt; if_config.eth0.inspect
=&amp;gt;#&amp;lt;RubyShell::ShellObjects::IfConfig::Base::Interface:0xb77f4c2c @name=&quot;eth0&quot;&amp;gt;
RubyShell&amp;gt; if_config['eth0'].ip
=&amp;gt;192.168.2.39
RubyShell&amp;gt; if_config['eth0'].mask
=&amp;gt;255.255.255.0
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;There&#8217;s the potential for much much more, but for the time being this is about it for if_config.&lt;/p&gt;


	&lt;p&gt;So these are shell objects. They&#8217;re a very promising idea, and I hope some people will contribute more objects. Note, though, that the way shell objects are implemented in 0.5 and currently in trunk is likely to change, I just haven&#8217;t thought it through 100% yet.&lt;/p&gt;


	&lt;h3&gt;File Handling&lt;/h3&gt;


	&lt;p&gt;Until 0.5, RubyShell only operated interactively&#8212;i.e., you couldn&#8217;t just hand it a file and have it read and run that file. That is no longer the case. Now, you can pass files on the command line to the ruby_shell.rb script and it will execute all of them. Currently, it executes them all in the same context; I&#8217;m still deciding whether or not I like this better than executing them in separate contexts.&lt;/p&gt;


	&lt;p&gt;Hand in hand with this new addition is the addition of an initialization file. RubyShell will now try to read a ~/.rbshrc and run whatever initialization code is there before running, either for files or interactively. This file can contain anything that&#8217;s valid RubyShell code. Here&#8217;re the contents of mine as it stands:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
require 'colored'
hostname | host = $pipe.strip
shell.prompt = Proc.new do
  &quot;\#{ENV['USER']}@\#{host}&quot;.green + &quot; \#{Dir::pwd.gsub(File.expand_path('~'), '~')} # &quot;.blue
end

alias 'ls', 'ls --color'
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Whammo! And therein lie hints as to the two remaining treats that await within&#8230;&lt;/p&gt;


	&lt;h3&gt;Interpolation&lt;/h3&gt;


	&lt;p&gt;RubyShell now supports interpolation of RubyShell code. That is to say, it supports executing code and replacing that section of the line with the code&#8217;s results. This is what&#8217;s usually done in ``s in other shells like bash. As it turns out, RubyShell 0.5 uses #{} for this, just like string interpolation for Ruby.&lt;/p&gt;


	&lt;p&gt;Sadly, this interferes with the actual string interpolation. As you can see above, you can escape such an interpolation using \#. If that isn&#8217;t done in the above section, you&#8217;d get an interpolation that would happen once when the RubyShell parser hit it, and never again&#8212;thus resulting in a prompt that never updated its values. RubyShell 0.6 will, instead, use the traditional backticks (``) to just dodge this problem entirely.&lt;/p&gt;


	&lt;h3&gt;Command Aliases&lt;/h3&gt;


	&lt;p&gt;Finally, RubyShell 0.5 supports aliasing commands. This is done through a normal Ruby method, alias_cmd. It just takes a command and what it should become. However, the command can also be a regular expression, or anything that will behave nicely under #===. For example:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
RubyShell&amp;gt; alias_cmd 'ls', 'ls --color'
RubyShell&amp;gt; alias_cmd /ram/, 'ls'
RubyShell&amp;gt; arama
*results of alsa*
&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;The value of the regular expression thing is one I&#8217;m still not 100% sure of, but it seems like it could be used for interesting and cool things. Also, through some hackery in the &lt;code&gt;RubyEvaluator&lt;/code&gt;, instead of &lt;code&gt;alias_cmd&lt;/code&gt;, you may use &lt;code&gt;alias&lt;/code&gt;. The only caveat is that &lt;code&gt;alias&lt;/code&gt; has to be the very very first thing in the statement. Otherwise, the replacement won&#8217;t take place (so that regular aliasing can be used). Thus:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;
RubyShell&amp;gt; alias 'ls', 'ls --color'
&lt;/code&gt;&lt;/pre&gt;

	&lt;h3&gt;What&#8217;s Next&lt;/h3&gt;


	&lt;p&gt;On the horizon is an implementation of output redirection. Currently, the plan is to make the syntax `word&amp;gt;&#8217;, where `word&#8217; corresponds to an actual method somewhere (haven&#8217;t decided where yet) that will take the filename as a parameter and could potentially apply transformations to the output as it goes.&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://blog.withoutincident.com/">
    <author>
      <name>shadowfiend</name>
    </author>
    <id>tag:blog.withoutincident.com,2007-08-16:47</id>
    <published>2007-08-16T06:37:00Z</published>
    <updated>2007-11-21T13:45:50Z</updated>
    <category term="Coding"/>
    <link href="http://blog.withoutincident.com/2007/8/16/rubyshell-0-3-pipes-parsing-and-cds" rel="alternate" type="text/html"/>
    <title>RubyShell 0.3: Pipes, Parsing, and CDs</title>
<summary type="html">&lt;p&gt;It turns out, RubyShell 0.2 ran code twice when you asked it to run it once. Whoops&#8230;&lt;/p&gt;


	&lt;p&gt;Anyway, once again that&#8217;s only one of the several new features (okay, that one was a bug fix, too&#8230;) in RubyShell 0.3. If you want to skip the explanation, you can go ahead and &lt;a href=&quot;http://software.withoutincident.com/projects/list_files/4&quot;&gt;download it now&lt;/a&gt; or &lt;a href=&quot;http://software.withoutincident.com/projects/list_issues/4?query_id=1&quot;&gt;look at the list of fixed/implemented issues&lt;/a&gt;.&lt;/p&gt;</summary><content type="html">
            &lt;p&gt;It turns out, RubyShell 0.2 ran code twice when you asked it to run it once. Whoops&#8230;&lt;/p&gt;


	&lt;p&gt;Anyway, once again that&#8217;s only one of the several new features (okay, that one was a bug fix, too&#8230;) in RubyShell 0.3. If you want to skip the explanation, you can go ahead and &lt;a href=&quot;http://software.withoutincident.com/projects/list_files/4&quot;&gt;download it now&lt;/a&gt; or &lt;a href=&quot;http://software.withoutincident.com/projects/list_issues/4?query_id=1&quot;&gt;look at the list of fixed/implemented issues&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;RubyShell 0.3 brings a couple of brand spankin&#8217; new things to the table. The first is the validation process.&lt;/p&gt;


	&lt;h3&gt;Parsing/Validation&lt;/h3&gt;


	&lt;p&gt;Validation is the process whereby RubyShell validates code as being Ruby. If it isn&#8217;t Ruby, then it&#8217;s run as a command. Originally, this was done using the defined? keyword, which, while kind of awesome, unfortunately actually ran the code embedded within it, which I had originally thought was not the case. Fear not, however! I have fixed this. RubyShell 0.3 uses ParseTree to make a real attempt to parse the code without any side-effects. In addition, it brings a restructuring of the validation so that validation is handled in its own class, with the evaluation class (the &lt;code&gt;RubyEvaluator&lt;/code&gt; class) acting as the &lt;code&gt;Parser&lt;/code&gt; class&#8217;s conduit to the validator. Multiline Ruby is now handled by looking for syntax errors of a particular kind, which makes it far more flexible than the previous versions, and means RubyShell should be able to handle most multiline Ruby code.&lt;/p&gt;


	&lt;p&gt;As part of this, the validation includes exceptions for two common shell practices, the trailing / and the trailing ~. For example:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;cd ~&lt;/pre&gt;&lt;/code&gt;

	&lt;p&gt;This is technically a valid first line of Ruby, with the next line promising to be the other side of the complement operator. However, since it is more common in a shell to be using ~ as `my home directory&#8217; than it is in Ruby to use the complement operator at the end of a line, this is simply considered invalid Ruby and will be run as a command. The same applies for a trailing /, which is commonly used on the end of a directory name, as in &lt;code&gt;shadowfiend/ruby/&lt;/code&gt;.&lt;/p&gt;


	&lt;h3&gt;CDs&lt;/h3&gt;


	&lt;p&gt;The &lt;code&gt;CdCommand&lt;/code&gt; got a few updates during this release. It now correctly handles tidle expansion (by using the handy &lt;code&gt;File.expand_path&lt;/code&gt; method&#8230; Kickass method, that!), and running a `cd&#8217; with no parameter is now synonymous to `cd ~&#8217;. It&#8217;s kind of awesome.&lt;/p&gt;


	&lt;h3&gt;Pipes&lt;/h3&gt;


	&lt;p&gt;Finally, and, for me, most awesomely, this release brings the improved piping syntax to RubyShell. This syntax lets you use $pipe as an implicit receiver for the first message of a line of Ruby code in a piped expression (actually, in any expression). For example, say you wanted to run an `ls&#8217; and then print each line with a trailing `RubyShell rocks!&#8217;. In RubyShell pre-0.3, you would do&lt;sup&gt;&lt;a href=&quot;#fn1&quot;&gt;1&lt;/a&gt;&lt;/sup&gt;:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;ls | $pipe.each_line { |ln| puts &quot;#{ln}RubyShell rocks!&quot; }&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Not horrendously ugly, but also not very pretty. RubyShell 0.3 still allows this syntax, of course; however, there&#8217;s a new one. Now, any calls to methods that start with with_ or and_ are assumed to mean `$pipe.&#8217;. The above example in done this way:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;ls | with_each_line { |ln| puts &quot;#{ln}RubyShell rocks!&quot; }&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;There, doesn&#8217;t that look better? How about we want to have everything in the current directory, but we want to censor any mentions of `java&#8217;:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;ls | and_gsub 'java', ''&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Shiny, eh?&lt;/p&gt;


	&lt;h3&gt;Other Fixes/Improvements&lt;/h3&gt;


	&lt;p&gt;The presence of the new validator means a lot of validation-related issues were fixed for this release. Frederick Ros also provided a patch to fix RubyShell&#8217;s crashing shamelessly when you hit `enter&#8217; with nothing on the line, &#8216;cause he&#8217;s just a fabulous person. Plus, now if a line of code wasn&#8217;t evaluated as Ruby and failed to run as a command, an error is printed. Some refinement need still be done&#8212;for example, printing an error is unnecessary if the command itself prints anything to stderr or stdout. Not sure how to determine whether that happened, though. It may be that the error will instead be printed if a valid command cannot be found. Again, however, this will be somewhat difficult to determine, since Kernel#system returns false whether that&#8217;s the case or the command just didn&#8217;t exit happily. Might be able to use the exit code for that.&lt;/p&gt;


	&lt;h3&gt;Le Future!&lt;/h3&gt;


	&lt;p&gt;Or, in Indo-Chinese&lt;sup&gt;&lt;a href=&quot;#fn2&quot;&gt;2&lt;/a&gt;&lt;/sup&gt;, `the future!&#8217; While I wanted to do output redirection for this release, I decided to shelve it for now so I could think out and research the syntax a little better. The feature issue tracking it is &lt;a href=&quot;http://software.withoutincident.com/issues/show/12&quot;&gt;over here&lt;/a&gt;, and I already posted some initial thoughts on how I might do the syntax. Also on the list is better error handling&#8212;i.e., it would be nice if RubyShell didn&#8217;t die a horrible death when you made a syntax error in the code you typed.&lt;/p&gt;


	&lt;p&gt;Further out, there&#8217;s the idea of improving shell completion, though that&#8217;s really dropping further on the list the more I think about it, since having filename completion (which is already present) is really by far the most important thing for a shell. Also on the `indeterminate future&#8217; list is an initialization file (~/.ruby_shellrc or something) and the ability to run actual files of RubyShell code. These two should be relatively simple, and the former depends on the latter. I also need to implement backtick notation (``), but making that basically interpolation of any RubyShell command, including regular Ruby. That&#8217;s all I can think of for now, but more ideas are welcome! And I&#8217;m sure I&#8217;ll come up with a few more of my own, as usual.&lt;/p&gt;


	&lt;p&gt;Enjoy!&lt;/p&gt;


&lt;hr /&gt;


	&lt;p&gt;&lt;sup&gt;1&lt;/sup&gt; Actually, whether you would really do this is anybody&#8217;s guess, since RubyShell pre-0.3 handled blocks in piped expressions a little oddly, and would sometimes explode in a shower of fiery sparks.&lt;/p&gt;


	&lt;p&gt;&lt;sup&gt;2&lt;/sup&gt; Really, that should have been `Sino-Indian&#8217;, if only to use `sino&#8217;.&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://blog.withoutincident.com/">
    <author>
      <name>shadowfiend</name>
    </author>
    <id>tag:blog.withoutincident.com,2007-08-12:40</id>
    <published>2007-08-12T21:44:00Z</published>
    <updated>2008-04-04T03:03:58Z</updated>
    <category term="Coding"/>
    <link href="http://blog.withoutincident.com/2007/8/12/rubyshell-0-2-now-with-100-more-ruby" rel="alternate" type="text/html"/>
    <title>RubyShell 0.2: Now With 100% More Ruby!</title>
<summary type="html">&lt;p&gt;It turns out, RubyShell 0.1 couldn&#8217;t handle method definitions or local variables because of the way Ruby code was being evaluated. Whoops&#8230;&lt;/p&gt;


	&lt;p&gt;Anyway, that&#8217;s only one of the several new features (okay, that one was a bug fix&#8230;) in RubyShell 0.2. If you want to skip the explanation, you can go ahead and &lt;a href=&quot;http://software.withoutincident.com/projects/list_files/4&quot;&gt;download it now&lt;/a&gt; or &lt;a href=&quot;http://software.withoutincident.com/projects/list_issues/4&quot;&gt;look at the list of fixed issues&lt;/a&gt;.&lt;/p&gt;</summary><content type="html">
            &lt;p&gt;It turns out, RubyShell 0.1 couldn&#8217;t handle method definitions or local variables because of the way Ruby code was being evaluated. Whoops&#8230;&lt;/p&gt;


	&lt;p&gt;Anyway, that&#8217;s only one of the several new features (okay, that one was a bug fix&#8230;) in RubyShell 0.2. If you want to skip the explanation, you can go ahead and &lt;a href=&quot;http://software.withoutincident.com/projects/list_files/4&quot;&gt;download it now&lt;/a&gt; or &lt;a href=&quot;http://software.withoutincident.com/projects/list_issues/4&quot;&gt;look at the list of fixed issues&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;RubyShell 0.2 brings a few new features in addition to the sizeable bug fix of working method definitions and local variables.&lt;/p&gt;


	&lt;h3&gt;Multiline Ruby&lt;/h3&gt;


	&lt;p&gt;First in my mind (probably because it was the most work) is the presence of support for multiline Ruby. For example:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;RubyShell&amp;gt; def my_method
RubyShell&amp;gt; 'test'
RubyShell&amp;gt; end
=&amp;gt; nil
RubyShell&amp;gt; my_method
=&amp;gt; &quot;test&quot;&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Other constructs supported as multiline constructs are &lt;code&gt;if&lt;/code&gt;, &lt;code&gt;while&lt;/code&gt;, &lt;code&gt;until&lt;/code&gt;, and &lt;code&gt;class&lt;/code&gt;.&lt;/p&gt;


	&lt;p&gt;There&#8217;s still no real parser for RubyShell. Our &lt;code&gt;Parser&lt;/code&gt; class is more of a decider class&#8212;deciding whether code will be run as regular Ruby or as a command. However, for this release it has taken on very limited parsing capabilities. Basically, Ruby can be handled multiline for specific constructs (see above) that appear at the start of a line. Basically, if any of these words start the line, then the `multiline level&#8217; is increased by one. Every time an `end&#8217; is seen, that level is &lt;em&gt;decreased&lt;/em&gt; by one. When it reaches 0 again (its initial state), the block is considered finished and is fully evaluated as Ruby. A backslash on the end of the line will also increase the multiline level, this time until a line appears without a backslash on its end. Finally, a &lt;code&gt;do&lt;/code&gt; anywhere in the current line will also trigger an increase in the multiline level.&lt;/p&gt;


	&lt;p&gt;Amongst other things, this approach means that commands that have the same name as any of these keywords will be completely unsupported (since seeing them automatically opens a multiline Ruby mode). This is only a small problem, since these constructs aren&#8217;t typically used as command names anyway.&lt;/p&gt;


	&lt;h3&gt;Multistatement RubyShell Code&lt;/h3&gt;


	&lt;p&gt;In addition to handling multiline Ruby, this release also supports the semicolon (;) as a statement separator. So, for example:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;RubyShell&amp;gt; def my_method; 'test'; end; echo magic
=&amp;gt; nil
magic
RubyShell&amp;gt; my_method
=&amp;gt; &quot;test&quot;&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;In this context, Ruby code and regular commands can still be freely intermixed. Internally, the parser takes this line apart and actually parses them as individual statements as if the input had come in on separate lines. Currently, splitting on the semicolon is done in a fairly hackish way (a simple split, then a recombination in a loop to handle semicolons inside strings); this would be better handled by a regular expression, but I was unable to come up with a satisfactory one. If any ideas are forthcoming, I would definitely appreciate some help in this regard.&lt;/p&gt;


	&lt;h3&gt;Shell History&lt;/h3&gt;


	&lt;p&gt;Shell history is implemented. In fact, it was a fairly trivial addition (just had to pass an extra parameter to the &lt;code&gt;readline&lt;/code&gt; method). However, it&#8217;s still missing part of what I wanted it to be able to do, namely the compression of multiline Ruby input into a single line separated by semicolons (and the ability to make that optional).&lt;/p&gt;


	&lt;h3&gt;Customizable Prompt&lt;/h3&gt;


	&lt;p&gt;The funnest new feature in this release is the customizable prompt. The prompt can now be set to either a string or a callable object (usually a proc, but anything that responds to &lt;code&gt;call&lt;/code&gt; will do, so you could technically write your own full-blown prompt-generating class if you wanted to). Some examples:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;RubyShell&amp;gt; ReadlineMonitor.prompt = 'Man am I Cool# '
=&amp;gt; &quot;Man am I Cool# &quot; 
Man am I Cool# ReadlineMonitor.prompt = lambda { &quot;#{ENV['USER']}@#{Dir::pwd}&amp;gt; &quot; }
=&amp;gt; #&amp;lt;Proc:0xb7b8b890@./ruby_shell/ruby_evaluator.rb:31&amp;gt;
shadowfiend@/home/shadowfiend/ruby_shell_tags/ruby_shell_0.2/lib&amp;gt; cd ..
shadowfiend@/home/shadowfiend/ruby_shell_tags/ruby_shell_0.2&amp;gt; &lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;&lt;span class=&quot;caps&quot;&gt;ANSI&lt;/span&gt; color codes should work for this prompt, too; so, combined with the `colored&#8217; gem:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;RubyShell&amp;gt; require 'colored'
=&amp;gt; true
RubyShell&amp;gt; ReadlineMonitor.prompt = lambda { &quot;#{ENV['USER'].green}@#{Dir::pwd.blue}&amp;gt; &quot; }
=&amp;gt; #&amp;lt;Proc:0xb7b8b890@./ruby_shell/ruby_evaluator.rb:31&amp;gt;
shadowfiend@/home/shadowfiend/ruby_shell_tags/ruby_shell_0.2/lib&amp;gt; cd ..
shadowfiend@/home/shadowfiend/ruby_shell_tags/ruby_shell_0.2&amp;gt; &lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;(But with colors this time ;))&lt;/p&gt;


	&lt;p&gt;I&#8217;m hoping to make that syntax cleaner in the future. Specifically, I&#8217;m hoping &#8220;self.prompt = &#8216;whatever&#8217;&#8221; will work. The next step would be a simple &#8220;prompt = &#8216;whatever&#8217;&#8221;, but that one requires a fair bit of voodoo, since it involves catching the assignment to a local variable and making it call a method instead. As such, I&#8217;m uncertain whether or not I&#8217;ll be implementing it.&lt;/p&gt;


	&lt;h3&gt;On the Horizon&lt;/h3&gt;


	&lt;p&gt;Items on the horizon are listed on the &lt;a href=&quot;http://software.withoutincident.com/projects/list_issues/4&quot;&gt;open issues page&lt;/a&gt; on Software Without Incident. Output redirection and more readable pipe handling in Ruby is next, with the following syntax being the target piping syntax:&lt;/p&gt;


&lt;pre&gt;&lt;code&gt;RubyShell&amp;gt; ls | with_each { |file| puts file[0..3] }
ruby
ruby&lt;/code&gt;&lt;/pre&gt;

	&lt;h3&gt;Downloading&lt;/h3&gt;


	&lt;p&gt;Again, the 0.2 release file is available on the &lt;a href=&quot;http://software.withoutincident.com/projects/list_files/4&quot;&gt;RubyShell files page&lt;/a&gt; on Software Without Incident.&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://blog.withoutincident.com/">
    <author>
      <name>shadowfiend</name>
    </author>
    <id>tag:blog.withoutincident.com,2007-07-27:35</id>
    <published>2007-07-27T02:49:00Z</published>
    <updated>2007-08-12T20:17:26Z</updated>
    <category term="Coding"/>
    <link href="http://blog.withoutincident.com/2007/7/27/a-ruby-shell-sure-rubyshell" rel="alternate" type="text/html"/>
    <title>A Ruby Shell? Sure! RubyShell!</title>
<summary type="html">&lt;p&gt;Once again, I put the Rails tutorial on the back burner (sorry folks :-/) for a coding project. This one wasn&#8217;t quite so little as the last one, though. While thoughts went through my mind about writing something similar to &lt;span class=&quot;caps&quot;&gt;JAXB&lt;/span&gt; called &lt;span class=&quot;caps&quot;&gt;RAXB&lt;/span&gt;, and I created the project on &lt;a href=&quot;http://software.withoutincident.com/&quot;&gt;Software Without Incident&lt;/a&gt; and all, that&#8217;s not what I ended up working on. Instead, my focus the last month or so has been RubyShell: a &lt;span class=&quot;caps&quot;&gt;UNIX&lt;/span&gt; shell written in Ruby with Ruby as its primary language. I&#8217;m ready now to make an initial release, so here it is: RubyShell 0.1!&lt;/p&gt;</summary><content type="html">
            &lt;p&gt;Once again, I put the Rails tutorial on the back burner (sorry folks :-/) for a coding project. This one wasn&#8217;t quite so little as the last one, though. While thoughts went through my mind about writing something similar to &lt;span class=&quot;caps&quot;&gt;JAXB&lt;/span&gt; called &lt;span class=&quot;caps&quot;&gt;RAXB&lt;/span&gt;, and I created the project on &lt;a href=&quot;http://software.withoutincident.com/&quot;&gt;Software Without Incident&lt;/a&gt; and all, that&#8217;s not what I ended up working on. Instead, my focus the last month or so has been RubyShell: a &lt;span class=&quot;caps&quot;&gt;UNIX&lt;/span&gt; shell written in Ruby with Ruby as its primary language. I&#8217;m ready now to make an initial release, so here it is: RubyShell 0.1!&lt;/p&gt;
&lt;p&gt;Before I go on, I should mention that there has been a previous attempt at a Ruby shell; it was called &lt;a href=&quot;http://rubyforge.org/projects/rush/&quot;&gt;ruSH&lt;/a&gt; and sits on RubyForge. Unfortunately, its last release was on August 28, 2005, four days after its first release. It was announced on ruby-talk and everything, but for some reason it seems to have died. The domain where it was being hosted (off RubyForge) seems to have similarly expired. That said, I only briefly glanced at the ruSH code while writing what I did, and didn&#8217;t really use any of what I saw (though I might look there again for inspiration in the future).&lt;/p&gt;


Currently, RubyShell can do a few things:
	&lt;ul&gt;
	&lt;li&gt;Run external commands. Currently, this is done through Kernel#system most of the time, which may be a bit of a cop-out; however, I believe it allows most of these commands to run on Windows. Recent revisions to the way I&#8217;m using Open3 may have dispelled these concerns, though. Using Kernel#system also gives the ability to run a program like vim without a problem, while running it with Open3 causes serious issues.&lt;/li&gt;
		&lt;li&gt;Display a prompt (I know, it&#8217;s basic, but it&#8217;s there :)).&lt;/li&gt;
		&lt;li&gt;Run single-line Ruby (including semicoloned stuff). There&#8217;s currently no parser or anything, instead we use the &lt;code&gt;defined?&lt;/code&gt; keyword, as detailed in &lt;a href=&quot;http://redhanded.hobix.com/inspect/methodCheckDefined.html&quot;&gt;this post on RedHanded&lt;/a&gt;. Sadly, as I mentioned, this means only single-line Ruby is currently supported. Whether support for multiline Ruby will come via a parser or via some quiet hackery that will allow common multiline constructs (e.g., def, class, if, etc.) is up for debate at this point.&lt;/li&gt;
		&lt;li&gt;Connect commands with pipes. This is the exception to the Kernel#system comment above. When output is being piped, external commands are run through Open3 to capture their output. Ruby code in piped commands has access to the output of the last command via the $pipe variable. Alternate syntaxes are in the works; I&#8217;ve written up some ideas as part of the &lt;a href=&quot;http://software.withoutincident.com/documents/show/3&quot;&gt;RubyShell Implementation Concepts/Ideas&lt;/a&gt; document on &lt;span class=&quot;caps&quot;&gt;SWI&lt;/span&gt;.&lt;/li&gt;
	&lt;/ul&gt;


	&lt;p&gt;That&#8217;s about all I can think of right now. Some things are hacked together in a nasty way; the way a &lt;code&gt;PassthroughCommand&lt;/code&gt; with output capturing is monitored for completion comes to mind (currently I&#8217;m using &lt;code&gt;Thread.list.length&lt;/code&gt;, which is just stupid).&lt;/p&gt;


	&lt;p&gt;I&#8217;ll be trying to establish a RubyForge project for RubyShell, but in the meantime it can be found, as with all my tinkerings, on Software Without Incident. The RubyShell project page is &lt;a href=&quot;http://software.withoutincident.com/projects/show/4&quot;&gt;here&lt;/a&gt;, and the release files are &lt;a href=&quot;http://software.withoutincident.com/projects/list_files/4&quot;&gt;here&lt;/a&gt;. Comments are welcome, help is welcome.&lt;/p&gt;


	&lt;p&gt;I&#8217;ll be off on vacation starting on Saturday for about a week, but I&#8217;ll try and keep an eye out to catch comments and such.&lt;/p&gt;


	&lt;p&gt;Enjoy!&lt;/p&gt;


	&lt;p&gt;&lt;span class=&quot;caps&quot;&gt;UPDATE&lt;/span&gt;: I&#8217;ve had a chance to try it on Windows, and it looks like Kernel#system there handles command-line arguments in a weird way. &lt;code&gt;dir /w&lt;/code&gt;, my test, didn&#8217;t seem to work, while just plain &lt;code&gt;dir&lt;/code&gt; did. Regardless, pipes still don&#8217;t work there, unsurprisingly. This is because a gets runs at least once when the first command in a list of piped commands isn&#8217;t Ruby code. On Windows, this gets blocks the application (go Windows! Not&#8230;), thus disallowing useful things like the termination check from running. Even commands like &lt;code&gt;dir&lt;/code&gt; will block it, because the gets runs whether the command expects input or not. As far as I know, there&#8217;s no way to differentiate between commands that do and don&#8217;t expect input.&lt;/p&gt;


	&lt;p&gt;I suspicion that it might be possible to use Kernel#select to see if the application wants input, but I seem to recall experimenting and seeing that it returned even if input wasn&#8217;t expected. Not only that, but it&#8217;ll register as ready for reading &lt;em&gt;and&lt;/em&gt; writing. Nonetheless, I&#8217;ll see if I can&#8217;t try and figure something out at some point to alleviate that issue. It would be kind of rockin&#8217; to have piping on Windows (outside of cygwin and such) :)&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://blog.withoutincident.com/">
    <author>
      <name>shadowfiend</name>
    </author>
    <id>tag:blog.withoutincident.com,2007-06-10:22</id>
    <published>2007-06-10T22:27:00Z</published>
    <updated>2007-06-10T22:30:42Z</updated>
    <category term="Coding"/>
    <link href="http://blog.withoutincident.com/2007/6/10/a-largely-functional-implementation-of-with-for-ruby" rel="alternate" type="text/html"/>
    <title>A Largely Functional Implementation of `with' for Ruby</title>
<summary type="html">&lt;p&gt;As a completely random exercise a month or two ago, I sat down and hacked out a &lt;a href=&quot;http://snippets.dzone.com/posts/show/3727&quot;&gt;very simple implementation&lt;/a&gt; of the Javascript &lt;code&gt;with&lt;/code&gt; keyword for Ruby. &lt;code&gt;with&lt;/code&gt; basically works like this:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;with(object)
{
    instanceMethod(); // no need to prefix with `object'
    var test = 5;
    other_instanceMethod(5);
}&lt;/pre&gt;&lt;/code&gt;

	&lt;p&gt;So basically it temporarily scopes function calls to a given object. If you call something in there that isn&#8217;t an instance method, it&#8217;ll then look for a local function with the appropriate name (note that this is contrary to the assertion I originally made in the aforementioned implementation; I&#8217;ve since verified that this is the expected behavior).&lt;/p&gt;


	&lt;p&gt;Initially, I just passed the block on to &lt;code&gt;instance_eval&lt;/code&gt; and happily went my way. It was a satisfactory solution, but not an ideal one, because, as pointed out after the snippet, it failed to respect encapsulation. Moreover, if you called something in there that wasn&#8217;t an instance method, it would fail. Now, after being spurred on by my brother&#8217;s mention of a friend&#8217;s solution that involved proxy objects, I&#8217;ve got an implementation which does not have those problems and in fact seems to largely behave the same way as the Javascript construct it is based on.&lt;/p&gt;</summary><content type="html">
            &lt;p&gt;As a completely random exercise a month or two ago, I sat down and hacked out a &lt;a href=&quot;http://snippets.dzone.com/posts/show/3727&quot;&gt;very simple implementation&lt;/a&gt; of the Javascript &lt;code&gt;with&lt;/code&gt; keyword for Ruby. &lt;code&gt;with&lt;/code&gt; basically works like this:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;javascript&quot;&gt;with(object)
{
    instanceMethod(); // no need to prefix with `object'
    var test = 5;
    other_instanceMethod(5);
}&lt;/pre&gt;&lt;/code&gt;

	&lt;p&gt;So basically it temporarily scopes function calls to a given object. If you call something in there that isn&#8217;t an instance method, it&#8217;ll then look for a local function with the appropriate name (note that this is contrary to the assertion I originally made in the aforementioned implementation; I&#8217;ve since verified that this is the expected behavior).&lt;/p&gt;


	&lt;p&gt;Initially, I just passed the block on to &lt;code&gt;instance_eval&lt;/code&gt; and happily went my way. It was a satisfactory solution, but not an ideal one, because, as pointed out after the snippet, it failed to respect encapsulation. Moreover, if you called something in there that wasn&#8217;t an instance method, it would fail. Now, after being spurred on by my brother&#8217;s mention of a friend&#8217;s solution that involved proxy objects, I&#8217;ve got an implementation which does not have those problems and in fact seems to largely behave the same way as the Javascript construct it is based on.&lt;/p&gt;
&lt;p&gt;Without too much further ado, here&#8217;s the full implementation:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;require 'pp'
module With
  def with(obj = nil, &#38;block)
    raise ArgumentError, 'Block expected.' unless block_given?

    # Collect instance methods from the block's original binding so we can pass
    # them on to the proxy object, since otherwise the +instance_eval+ will lose
    # them.
    instance_method_names = eval('methods + private_methods + protected_methods',
                                 block.binding)
    instance_methods = {}
    instance_method_names.each do |meth|
      instance_methods[meth.to_sym] = eval(&quot;self.method('#{meth}')&quot;, block.binding)
    end

    proxy = WithProxy.new(obj || self, instance_methods)

    # Inject instance variables from the block's original binding into the proxy
    # object, since otherwise the +instance_eval+ will lose them.
    instance_vars = eval('instance_variables', block.binding)
    instance_vars.each do |var|
      proxy.instance_variable_set var, eval(var, block.binding)
    end

    proxy.instance_eval &#38;block
  end

  class WithProxy
    # Kill all instance methods except __send, __id, and +instance_eval+ (which
    # we need in order to use this as a proxy in a with block.
    instance_methods.each do |meth|
      undef_method(meth) unless meth =~ /^__/ || meth == 'instance_eval' ||
        meth == 'instance_variable_set'
    end

    # Initializes a proxy object that will first try proxying methods to the
    # public methods of the passed +obj+ parameter, and, if that doesn't work,
    # try proxying to any of the +additional_methods+. +additional_methods+
    # should be a Hash indexed by the method name as a symbol.
    def initialize(obj, additional_methods)
      @obj = obj
      @additional_methods = additional_methods
    end

    def method_missing(method, *args)
      if method_allowed?(method)
        @obj.send(method, *args)
      elsif @additional_methods.include?(method)
        @additional_methods[method].call(*args)
      else
        raise NoMethodError, &quot;undefined or inaccessible method #{method} for #{@obj}&quot; 
      end
    end

    # Determines if the specified method is allowed to be passed on.
    def method_allowed?(method)
      methods_allowed[method] ||= @obj.class.public_instance_methods.include?(method.to_s)
    end

    def methods_allowed
      @methods_allowed ||= {}
    end
  end
end&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;There are a few fixes floating around here to previous problems. First and foremost, it should be clear that, instead of using &lt;code&gt;instance_eval&lt;/code&gt; on the object that we&#8217;ll be dealing with directly, we instead use a proxy object. For that purpose, we have the &lt;code&gt;WithProxy&lt;/code&gt; class. This class has all of its instance methods undef&#8217;ed except for the &lt;code&gt;__&lt;/code&gt; methods (send and id), &lt;code&gt;instance_eval&lt;/code&gt; (for obvious reasons), and &lt;code&gt;instance_variable_set&lt;/code&gt; (for reasons we&#8217;ll get to in a second). This proxy object lets us make sure to respect encapsulation by only allowing public methods to be callable.&lt;/p&gt;


	&lt;p&gt;To this end, this implementation of &lt;code&gt;with&lt;/code&gt; uses &lt;code&gt;method_missing&lt;/code&gt; to catch method calls, and checks whether they can be proxied to the original object. The &lt;code&gt;method_allowed?&lt;/code&gt; method checks whether a given method is in the list of a class&#8217;s public methods, and memoizes the result so that further calls to that method don&#8217;t induce the overhead of searching the list of public methods every time.&lt;/p&gt;


	&lt;p&gt;The second piece of the puzzle is the &lt;code class=&quot;ruby&quot;&gt;@additional_methods&lt;/code&gt; instance variable in the proxy object. This is a hash that maps method names (as symbols) to &lt;code&gt;Method&lt;/code&gt; objects. It&#8217;s used to specify additional methods that are allowed beyond the public instance methods in the original object. If you&#8217;ll recall, the behavior of &lt;code&gt;with&lt;/code&gt; in Javascript is to look for functions in the enclosing scope when no instance methods are found with the given name. This list of additional methods lets us do that. If a method is not allowed to be called on the given object, then the list of additional methods is searched and, if a matching method is found, that method is called.&lt;/p&gt;


	&lt;p&gt;Notice also that the list of additional methods is passed in to the &lt;code&gt;WithProxy&lt;/code&gt;&#8217;s constructor in the &lt;code&gt;with&lt;/code&gt; method, and it consists of all public, private, and protected methods in the enclosing scope of the passed block (retrieved using &lt;code&gt;block.binding&lt;/code&gt; and &lt;code&gt;eval&lt;/code&gt;). These are essentially all the methods that should be available without qualification within that block.&lt;/p&gt;


	&lt;p&gt;Finally, we also have to do a similar trick with instance variables. We again use &lt;code&gt;eval&lt;/code&gt; and &lt;code&gt;block.binding&lt;/code&gt; to nab instance variables available in the enclosing scope and inject them into the proxy object. Usually, instance variables are available in the context of a block, since a block is a closure; however, in this case, because we&#8217;re using &lt;code&gt;instance_eval&lt;/code&gt;, the instance context of the block changes, so that it&#8217;s executing in a different object instance than the block was originally in. Thus, we lose both the original instance methods and the original instance variables. This rather hackish fix takes care of that.&lt;/p&gt;


	&lt;p&gt;So, that said, is it worth using? I dunno. The added complexity hanging around here isn&#8217;t necessarily nice to incur in an application. Maybe it&#8217;s worth using in a short script for the purposes of saving a few keystrokes, but in general I&#8217;d say it&#8217;s just an interesting mental exercise in what&#8217;s possible in Ruby when you really put your mind to it.&lt;/p&gt;


	&lt;p&gt;You can also grab the &lt;a href=&quot;http://blog.withoutincident.com/assets/2007/6/10/with.rb&quot;&gt;original source file&lt;/a&gt; and the &lt;a href=&quot;http://blog.withoutincident.com/assets/2007/6/10/with_spec.rb&quot;&gt;related spec&lt;/a&gt;.&lt;/p&gt;
          </content>  </entry>
  <entry xml:base="http://blog.withoutincident.com/">
    <author>
      <name>shadowfiend</name>
    </author>
    <id>tag:blog.withoutincident.com,2007-06-09:20</id>
    <published>2007-06-09T22:12:00Z</published>
    <updated>2007-06-09T22:21:53Z</updated>
    <category term="Coding"/>
    <link href="http://blog.withoutincident.com/2007/6/9/automated-memoization" rel="alternate" type="text/html"/>
    <title>Automated Memoization!</title>
<summary type="html">&lt;p&gt;I saw an interesting post on something that allows you to &lt;a href=&quot;http://www.fusionsoft-online.com/articles-declarative-cache.php&quot;&gt;annotate Java fields for caching&lt;/a&gt;. That&#8217;s shiny and all, but I like to live in the Ruby world (though annotations in Java are finding some very neat uses).&lt;/p&gt;


	&lt;p&gt;In case you came hunting for Part &lt;span class=&quot;caps&quot;&gt;III&lt;/span&gt; of the Rails tutorial, don&#8217;t worry&#8212;it&#8217;s coming, but this caught my attention first.&lt;/p&gt;</summary><content type="html">
            &lt;p&gt;I saw an interesting post on something that allows you to &lt;a href=&quot;http://www.fusionsoft-online.com/articles-declarative-cache.php&quot;&gt;annotate Java fields for caching&lt;/a&gt;. That&#8217;s shiny and all, but I like to live in the Ruby world (though annotations in Java are finding some very neat uses).&lt;/p&gt;


	&lt;p&gt;In case you came hunting for Part &lt;span class=&quot;caps&quot;&gt;III&lt;/span&gt; of the Rails tutorial, don&#8217;t worry&#8212;it&#8217;s coming, but this caught my attention first.&lt;/p&gt;
&lt;p&gt;Now, in the Java world, this is the pattern demonstrated:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;java&quot;&gt;    public int getArea(){
        if (area == null)
            area = new Integer(getAreaCalculated());
        return area;
    }&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;In the Ruby world, we have a more idiomatic way of expressing it:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;  def area
    @area ||= calculate_area
  end&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;The &lt;code&gt;||=&lt;/code&gt; operator serves as a shortcut for:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;@area = (@area || calculate_area)&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;It&#8217;s basically the self-referencing form of the &lt;code&gt;||&lt;/code&gt; operator. It&#8217;s important to know how the &lt;code&gt;||&lt;/code&gt; operator works when trying to figure out what&#8217;s going on. In Java, if I type &lt;code class=&quot;java&quot;&gt;&quot;test&quot; || &quot;hello&quot;&lt;/code&gt;, I get a compilation error. Why? Because the &lt;code&gt;||&lt;/code&gt; operator is only defined for booleans. We&#8217;re trying to use it for Strings above. In Ruby, however, this is not the case. In Ruby, much like in many C derivatives, the &lt;code&gt;||&lt;/code&gt; operator evaluates to &lt;em&gt;the first non-false value&lt;/em&gt;, from left to right. Remember, too, that Ruby considers &lt;code&gt;nil&lt;/code&gt; and &lt;code&gt;false&lt;/code&gt; equivalent. So what would happen if we wrote &lt;code class=&quot;ruby&quot;&gt;&quot;test&quot; || &quot;hello&quot;&lt;/code&gt; in Ruby? We would get &lt;code class=&quot;ruby&quot;&gt;&quot;test&quot;&lt;/code&gt;. What about &lt;code class=&quot;ruby&quot;&gt;nil || &quot;hello&quot;&lt;/code&gt;? We get &lt;code class=&quot;ruby&quot;&gt;&quot;hello&quot;&lt;/code&gt;.&lt;/p&gt;


	&lt;p&gt;So let&#8217;s look a little closer at the &lt;code&gt;||=&lt;/code&gt; operator, then. When we do what we did above, we&#8217;re basically saying `put @area into @area, unless @area evaluates to false, in which case put the results of &lt;code&gt;calculate_area&lt;/code&gt; into @area&#8217;. In the Java article, this is called caching; in the Ruby world, it seems to more commonly be referred to as &lt;a href=&quot;http://en.wikipedia.org/wiki/Memoization&quot;&gt;memoization&lt;/a&gt;, which also seems the more appropriate term.&lt;/p&gt;


	&lt;h2&gt;A Flexible Memoization Solution for Ruby&lt;/h2&gt;


	&lt;h3&gt;Devising an &lt;span class=&quot;caps&quot;&gt;API&lt;/span&gt;&lt;/h3&gt;


	&lt;p&gt;The aforementioned article mentions a mechanism for annotating Java methods as cached by marking the class as @Reloadable and the method as @Cached. We&#8217;re going to do something similar, but with Ruby. Our first purpose will be to memoize any given method. The syntax I&#8217;m going for is&lt;sup&gt;&lt;a href=&quot;#fn1&quot;&gt;1&lt;/a&gt;&lt;/sup&gt;:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;memoize_method :my_method&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;I also want to simplify the creation of readers for certain instance variables that we want to memoize, but that are based on initialization code. For example, in a scraping script I wrote for getting downloads for a specific section off of the Sakai &lt;span class=&quot;caps&quot;&gt;CLE&lt;/span&gt;, I have this bit of code:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;  # Provides the configuration items for this user.
  def user_config
    @config ||= (read_cached_config || read_config)
  end&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;In this case, I either get the configuration from a separate (file-based) cache or I read it explicitly from the website. This kind of double-caching is simple enough that we probably don&#8217;t want to write an entirely separate method for it, and it&#8217;s returned from a method with a different name than the caching methods to boot. Thus our solution of &lt;code&gt;memoize_method&lt;/code&gt; isn&#8217;t as elegant. So on top of that, let&#8217;s add another syntax:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;memoized_reader :user_config { read_cached_config || read_config }&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;This lets us create an attribute reader just like &lt;code&gt;attribute_reader&lt;/code&gt; does, except this one will be memoized, and will use the passed block for the initialization code. Golden! In this same general vein, though, comes the use case of memoizing an attribute with only one method as the initializer. With the above syntax we would do:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;memoized_reader :user_config { read_config }&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;But we don&#8217;t really need a full-on block for that, so let&#8217;s switch the syntax up for that:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;memoized_reader :user_config, :read_config&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;But here what we&#8217;re really doing is a generic pattern of memoizing the result of one method and making it available as another one. So maybe we can use:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;memoize_method :read_config, :as =&amp;gt; :user_config&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Where by default it memoizes under the same name, and, if you want to, you can provide a different name&lt;sup&gt;&lt;a href=&quot;#fn2&quot;&gt;2&lt;/a&gt;&lt;/sup&gt;.&lt;/p&gt;


	&lt;h3&gt;Building the Background Syntax&lt;/h3&gt;


	&lt;p&gt;Now, this provides us with two methods for our &lt;span class=&quot;caps&quot;&gt;API&lt;/span&gt;. But are they so different? The only clear difference between &lt;code&gt;memoized_reader&lt;/code&gt; and &lt;code&gt;memoize_method&lt;/code&gt; is that &lt;code&gt;memoized_reader&lt;/code&gt; will create an instance variable of the same name you pass it, whereas &lt;code&gt;memoize_method&lt;/code&gt; will do&#8230; Something else. We don&#8217;t really know what; it&#8217;ll store the results in some nebulous place that we don&#8217;t really need to know about. But let&#8217;s unify syntaxes a little. Right now, we pass &lt;code&gt;memoize_method&lt;/code&gt; a method name and, optionally, an alias for it. But it doesn&#8217;t take a block. &lt;code&gt;memoize_reader&lt;/code&gt;, on the other hand, will take a block, but it won&#8217;t take an alternate method name under which to return the memoized variable.&lt;/p&gt;


	&lt;p&gt;In the background, hidden from a prying developer&#8217;s view, why don&#8217;t we introduce a unifying syntax? It&#8217;ll be a little uglier, but more flexible, and will allow the other two to exist on top of it.  Here&#8217;s an idea for the syntax:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;memoize :as =&amp;gt; :user_config { read_config }
memoize :read_config, :as =&amp;gt; :user_config
memoize :read_config, :as =&amp;gt; :user_config, :in_variable =&amp;gt; :@config
memoize :as =&amp;gt; :config, :in_variable =&amp;gt; :@config { read_cached_config || read_config }&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Why use this syntax? It unifies the syntaxes for both of the other methods. Why not use it as the main syntax? It&#8217;s not as clean and shiny. This is that bastard syntax we don&#8217;t want people to know we came up with because they might &lt;a href=&quot;http://www.auntiemomo.com/cakeordeath/d2ktranscription.html#puberty&quot;&gt;kill us with sticks&lt;/a&gt;, you know?&lt;/p&gt;


	&lt;p&gt;So now, we&#8217;ve got a full planned syntax. Time to write code!&lt;/p&gt;


	&lt;h3&gt;Spec&#8217;ing it Out!&lt;/h3&gt;


	&lt;p&gt;That&#8217;s right. Our first step? Write some specs! Let&#8217;s &lt;acronym title=&quot;Behavior-Driven Development&quot;&gt;&lt;span class=&quot;caps&quot;&gt;BDD&lt;/span&gt;&lt;/acronym&gt; it up! We&#8217;ll use RSpec to write some specs for what we&#8217;re expecting these fine methods to do:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;require 'automated_memoization'
describe AutomatedMemoization, 'when memoizing my_method' do
  before(:all) do
    class TestClassA
      include AutomatedMemoization
      def my_method; Time.now; end
      memoize :my_method
    end
  end

  before(:each) do
    @test = TestClassA.new
  end

  it 'should alias my_method to my_method_without_memoization' do
    lambda { @test.method(:my_method_without_memoization) }.should_not raise_error(NameError)
  end

  it 'should call the memoized method once and only once' do
    @test.should_receive(:my_method_without_memoization).once.and_return(Time.now)

    3.times { @test.my_method}
  end

  it 'should return the same object after the first call to my_method' do
    orig_value = @test.my_method

    @test.my_method.should equal(orig_value) # equal checks for object identity!
  end
end&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;At its base, we require that when memoizing a method we get a certain alias and that alias is only called once (since the results should be memoized). We also require that calls past the first one always return the same object. We test this with &lt;code class=&quot;ruby&quot;&gt;should equal()&lt;/code&gt;, which checks for object &lt;em&gt;identity&lt;/em&gt;&#8212;i.e., that they are exactly the same object, not just equivalent ones. Because we check for identity, it isn&#8217;t really necessary to use the time (which would be useful if we were just checking for equality), but hey, whatever.&lt;/p&gt;


	&lt;h3&gt;Basic Memoiziation&lt;/h3&gt;


	&lt;p&gt;Let&#8217;s get ourselves some basic memoiziation, then:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;module AutomatedMemoization
  # Include methods in ClassMethods as (surprise!) class methods.
  def self.included(mod)
    class &amp;lt;&amp;lt; mod; include ClassMethods; end
  end

  # Make sure we have a memoization hash when we need it.
  def __memoize_hash__
    @__memoized__ ||= {}
  end

  module ClassMethods
    def memoize(method)
      old_method_name = &quot;#{method}_without_memoization&quot;.to_sym
      new_method_name = &quot;#{method}_with_memoization&quot;.to_sym
      self.class_eval do
        define_method(new_method_name) do |*args|
          self.__memoize_hash__[method] ||= self.send(old_method_name, *args)
        end

        alias_method(old_method_name, method) # alias out the current method
        alias_method(method, new_method_name) # alias in the new method
      end
    end
  end
end&lt;/pre&gt;&lt;/code&gt;

	&lt;p&gt;There&#8217;s a bit of Ruby magic going on here, so let&#8217;s think about what&#8217;s happening. First of all, we&#8217;ll be sticking our code into a module. We can mix that module in wherever we need memoization, or, if we really want to, we can mix it into &lt;code&gt;Module&lt;/code&gt; to get it everywhere.  Inside this module, we define &lt;code&gt;included&lt;/code&gt;. This method gets called whenever this module is included somewhere else. Because inclusion by default includes all methods as instance methods, and we want these as class methods, we use the &lt;code class=&quot;ruby&quot;&gt;class &amp;lt;&amp;lt; mod&lt;/code&gt; syntax to get the class&#8217;s metaclass and include the class methods there, effectively making them class methods.&lt;/p&gt;


	&lt;p&gt;Inside the class methods, we have the &lt;code&gt;memoize&lt;/code&gt; method. This method currently just takes one parameter, the name of the method we&#8217;re going to memoize. Then, we generate the name we&#8217;re going to be renaming that method to and the name we&#8217;ll be using for the new method. Finally, we do an instance_eval on &lt;code&gt;self&lt;/code&gt;. &lt;code&gt;self&lt;/code&gt; in this case will be the class, so a class_eval does basically the same thing as reopening the class for modification.  First, we create a new method, using our new method name, and make it automatically add an entry to an &lt;code class=&quot;ruby&quot;&gt;@__memoized__&lt;/code&gt; hash. Notice also that we take an arbitrary number of parameters and pass them on to the original method&#8212;this is because we don&#8217;t actually know whether the method we&#8217;re memoizing takes parameters or not. If it does, great! If not, then it&#8217;ll still work fine. You&#8217;ll notice that we use a memoizing method to create that hash the first time we need it. We call the instance variable and its corresponding method with surrounding __s largely to avoid name clashes, as well as to emphasize that they shouldn&#8217;t really be accessed outside of what we&#8217;re doing.  Then, we alias the method to what we&#8217;ll be using as its `old&#8217; name, and alias the new method to the method&#8217;s original name&lt;sup&gt;&lt;a href=&quot;#fn3&quot;&gt;3&lt;/a&gt;&lt;/sup&gt;. Note also that we use &lt;code&gt;alias_method&lt;/code&gt; instead of &lt;code&gt;alias&lt;/code&gt;. This is because &lt;code&gt;alias&lt;/code&gt;, if given the two variables we gave it, would interpret those as method names, since it&#8217;s an actual Ruby keyword and a Ruby statement. &lt;code&gt;alias_method&lt;/code&gt; takes two strings or symbols and deals with those as such.&lt;/p&gt;


	&lt;p&gt;Now, our new method should take care of all the magical memoization! Our next step is to add the &lt;code class=&quot;ruby&quot;&gt;:as&lt;/code&gt; parameter.&lt;/p&gt;


	&lt;h3&gt;Spec&#8217;ing and Coding &lt;code&gt;:as&lt;/code&gt;&lt;/h3&gt;


	&lt;p&gt;Here&#8217;s a spec (assuming it&#8217;s already got TestClass as above):&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;describe AutomatedMemoization, 'when memoizing my_method as my_memoized_method' do
  before(:all) do
    class TestClassB
      include AutomatedMemoization
      def my_method; Time.now; end
      memoize :my_method, :as =&amp;gt; :my_memoized_method
    end
  end

  before(:each) do
    @test = TestClassB.new
  end

  it 'should keep my_method' do
    lambda { @test.method(:my_method) }.should_not raise_error(NameError)
  end

  it 'should create my_memoized_method' do
    lambda { @test.method(:my_memoized_method) }.should_not raise_error(NameError)
  end

  it 'should call the memoized method once and only once' do
    @test.should_receive(:my_method).once.and_return(Time.now)

    3.times { @test.my_memoized_method}
  end

  it 'should return the same object after the first call to my_memoized_method' do
    orig_value = @test.my_memoized_method

    @test.my_memoized_method.should equal(orig_value) # equal checks for object identity!
  end
end&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Here, we&#8217;re checking a few things. First of all, we&#8217;re checking that &lt;code&gt;my_method&lt;/code&gt; isn&#8217;t aliased in this case (no need, since there won&#8217;t be any name clashes). Second of all, we&#8217;re checking that &lt;code&gt;my_memoized_method&lt;/code&gt; is at least created. Third, we&#8217;re checking that the memoized method is called once (as before), and that we get the same object every time from my_memoized_method.&lt;/p&gt;


	&lt;p&gt;Now let&#8217;s see the code that makes this happen (I&#8217;ll replicate the above code with relevant changes made, but only in the memoize method):&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;module AutomatedMemoization
  module ClassMethods
    def memoize(method, options = {})
      options = { :as =&amp;gt; method }.merge(options)

      if (options[:as] == method)
        old_method_name = &quot;#{method}_without_memoization&quot;.to_sym
        new_method_name = &quot;#{method}_with_memoization&quot;.to_sym

        generate_memo_method(old_method_name, new_method_name)
        self.class_eval do
          alias_method(old_method_name, method) # alias out the current method
          alias_method(method, new_method_name) # alias in the new method
        end
      else
        generate_memo_method(method, options[:as])
      end
    end

    # Generates a memoizing method for +method+ named +memoized_method+.
    def generate_memo_method(method, memoized_method)
      self.class_eval do
        define_method(memoized_method) do |*args|
          self.__memoize_hash__[method] ||= self.send(method,  *args)
        end
      end
    end
  end
end&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Now we&#8217;ve added a helper method that generates a memoizing method by a certain name that memoizes a method of a different name. `Ah-hah!&#8217; you might be thinking. `There&#8217;s a difference here! This code creates a different entry in the &lt;code&gt;__memoized__&lt;/code&gt; hash than the other one does!&#8217; That&#8217;s very true. When we use &lt;code&gt;memoize&lt;/code&gt; without providing an &lt;code class=&quot;ruby&quot;&gt;:at&lt;/code&gt; parameter, we use the &lt;code&gt;old_method_name&lt;/code&gt; for the entry in the hash, whereas before we were using the &lt;em&gt;original&lt;/em&gt; method name. Not to worry, however. That&#8217;s an implementation detail, and no one should be relying directly on our code besides ourselves anyway.&lt;/p&gt;


	&lt;p&gt;So what&#8217;s the next option we need to support? &lt;code class=&quot;ruby&quot;&gt;:in_variable&lt;/code&gt;, which makes us store the results of the method in a specific instance variable.&lt;/p&gt;


	&lt;h3&gt;Spec&#8217;ing and Coding &lt;code&gt;:in_variable&lt;/code&gt;&lt;/h3&gt;


	&lt;p&gt;First, let&#8217;s spec out this functionality&lt;sup&gt;&lt;a href=&quot;#fn4&quot;&gt;4&lt;/a&gt;&lt;/sup&gt;:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;describe AutomatedMemoization, 'when memoizing my_method into an instance variable' do
  before(:all) do
    class TestClassC
      include AutomatedMemoization
      def my_method; Time.now; end
      memoize :my_method, :in_variable =&amp;gt; :@my_var
    end
  end

  before(:each) do
    @test = TestClassC.new
  end

  it 'should alias my_method to my_method_without_memoization' do
    lambda { @test.method(:my_method_without_memoization) }.should_not raise_error(NameError)
  end

  it 'should call the memoized method once and only once' do
    @test.should_receive(:my_method_without_memoization).once.and_return(Time.now)

    3.times { @test.my_method}
  end

  it 'should return the same object after the first call to my_method' do
    orig_value = @test.my_method

    @test.my_method.should equal(orig_value) # equal checks for object identity!
  end

  it 'should store the object returned after the first call to my_method ' +
     'in the @my_var instance variable' do
    orig_value = @test.my_method

    @test.instance_variable_get(:@my_var).should == orig_value
  end
end&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Now, let&#8217;s code this baby out:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;    def memoize(method, options = {})
      options = { :as =&amp;gt; method, :in_variable =&amp;gt; nil }.merge(options)

      if (options[:as] == method)
        old_method_name = &quot;#{method}_without_memoization&quot;.to_sym
        new_method_name = &quot;#{method}_with_memoization&quot;.to_sym

        generate_memo_method(old_method_name, new_method_name, options[:in_variable])
        self.class_eval do
          alias_method(old_method_name, method) # alias out the current method
          alias_method(method, new_method_name) # alias in the new method
        end
      else
        generate_memo_method(method, options[:as], options[:in_variable])
      end
    end

    # Generates a memoizing method for +method+ named +memoized_method+.
    # If non-nil, destination_var is the instance variable within which the memoized
    # value will be stored.
    def generate_memo_method(method, memoized_method, destination_var)
      if destination_var.nil?
        self.class_eval do
          define_method(memoized_method) do |*args|
             self.__memoize_hash__[method] ||= self.send(method, *args)
          end
        end
      else
        self.class_eval do
          define_method(memoized_method) do |*args|
            self.instance_variable_get(destination_var) or
              self.instance_variable_set(destination_var, self.send(method, *args))
          end
        end
      end
    end&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;So, admittedly, this isn&#8217;t the shiniest looking code. See that big if statement in &lt;code&gt;generate_memo_method&lt;/code&gt; where both of them do a class_eval? It&#8217;d be nicer to stick that if statement inside the class_eval, right? Maybe we&#8217;ll go ahead and fix some of this in the next round&#8230; Notice also that we don&#8217;t use the ||= syntax with the instance variable setting version, because there&#8217;s no way to do it &lt;del&gt;- we have no =-based accessor. Instead, we use &lt;code&gt;instance_variable_set&lt;/code&gt; and &lt;code&gt;instance_variable_get&lt;/code&gt; to return either it or the appropriate value after we set it. The &lt;code class=&quot;ruby&quot;&gt;or&lt;/code&gt; operator will run everything to its left and then everything to its right if the code to its left evaluated to false or nil. In particular, the difference between &lt;code&gt;or&lt;/code&gt; and &lt;code&gt;||&lt;/code&gt; is that &lt;code&gt;or&lt;/code&gt; has very low precedence -&lt;/del&gt; i.e., just about everything will run before it gets checked, without needing extra parentheses.&lt;/p&gt;


	&lt;p&gt;Another alternative to the above approach is to pass a block containing the &lt;code&gt;self.send&lt;/code&gt; bit to a setter method which handles the logic of whether to use the instance variable or the memoize_hash. Again, though, if we did this, we would get the check for whether destination_var was the one to use every time we ran the method.&lt;/p&gt;


	&lt;p&gt;Now that we&#8217;ve got that done, all we&#8217;ve got left is accepting the block instead of a method! We&#8217;re in the home stretch!&lt;/p&gt;


	&lt;h3&gt;Spec&#8217;ing and Coding the Block Acceptor&lt;/h3&gt;


	&lt;p&gt;So let&#8217;s write some specs for the system when it takes a block:&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;describe AutomatedMemoization, 'when memoizing a block as my_memoized_block' do
  before(:all) do
    class TestClassD
      include AutomatedMemoization
    end

    block = Proc.new { Time.now }
    TestClassD.class_eval do
      memoize(:as =&amp;gt; :my_memoized_block, &#38;block)
    end
    @block = block
  end

  before(:each) do
    @test = TestClassD.new
  end

  it 'should create my_memoized_block' do
    lambda { @test.method(:my_memoized_block) }.should_not raise_error(NameError)
  end

  it 'should call the memoized block once and only once' do
    @block.should_receive(:call).once.and_return(Time.now)

    3.times { @test.my_memoized_block }
  end

  it 'should return the same object after the first call to my_memoized_block' do
    orig_value = @test.my_memoized_block

    @test.my_memoized_block.should equal(orig_value) # equal checks for object identity!
  end
end&lt;/pre&gt;&lt;/code&gt;

	&lt;p&gt;As usual, we check that the block is only called once, that it returns the same object after the first call, and that &lt;code&gt;my_memoized_block&lt;/code&gt; is created.&lt;/p&gt;


	&lt;p&gt;Now, let&#8217;s code it up!&lt;/p&gt;


&lt;pre&gt;&lt;code class=&quot;ruby&quot;&gt;module AutomatedMemoization
  module ClassMethods
    def memoize(method = nil, options = {}, &#38;block)
      options = method and method = nil if method.is_a?(Hash)
      options = { :as =&amp;gt; method, :in_variable =&amp;gt; nil }.merge(options)

      raise ArgumentError, 'If you pass a block, you must pass the :as option.' \
        if options[:as].nil? &#38;&#38; method.nil?

      if (options[:as] == method)
        old_method_name = &quot;#{method}_without_memoization&quot;.to_sym
        new_method_name = &quot;#{method}_with_memoization&quot;.to_sym

        generate_memo_method(old_method_name, new_method_name,
                             options[:in_variable], block)
        self.class_eval do
          alias_method(old_method_name, method) # alias out the current method
          alias_method(method, new_method_name) # alias in the new method
        end
      else
        generate_memo_method(method, options[:as], options[:in_variable], block)
      end
    end

    # Delegates to either +generate_sending_memo_method+ or to
    # +generate_calling_memo_method+ to generate an appropriate memoizing
    # method.
    def generate_memo_method(method, memoized_method, destination_var, block)
      self.class_eval do
        if block
         define_method(memoized_method,
           &#38;generate_calling_memo_body(method, memoized_method,
                                       destination_var, block))
        else
          define_method(memoized_method,
            &#38;generate_sending_memo_body(method, memoized_method,
                                        destination_var, block))
        end
      end
    end

    def generate_calling_memo_body(method, memoized_method, destination_var,
                                   block)
      if destination_var.nil?
        Proc.new do |*args|
          self.__memoize_hash__[block] ||= block.call(*args)
        end
      else
        Proc.new do |*args|
          self.instance_variable_get(destination_var) or
            self.instance_variable_set(destination_var, block.call(*args))
        end
      end
    end

    def generate_sending_memo_body(method, memoized_method, destination_var,
                                   block)
      if destination_var.nil?
        Proc.new do |*args|
          self.__memoize_hash__[method] ||= self.send(method, *args)
        end
      else
        Proc.new do |*args|
          self.instance_variable_get(destination_var) or
            self.instance_variable_set(destination_var, self.send(method, *args))
        end
      end
    end
  end
end&lt;/code&gt;&lt;/pre&gt;

	&lt;p&gt;Ah! Code explosion! What happened? Well, we did a lot of refactoring there to try and minimze the amount of repetition in our code. First of all, we refactored the decision of whether to send a signal to the instance or