<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://rubyworks.github.io/facets/feed.xml" rel="self" type="application/atom+xml" /><link href="https://rubyworks.github.io/facets/" rel="alternate" type="text/html" /><updated>2026-11-09T02:47:40+00:00</updated><id>https://rubyworks.github.io/facets/feed.xml</id><title type="html">Ruby Facets</title><subtitle>Ruby Facets adds focused extensions to Ruby core classes and the standard library.</subtitle><author><name>Thomas Sawyer</name></author><entry><title type="html">What Concerns</title><link href="https://rubyworks.github.io/facets/posts/2013-01-01-what-concerns.html" rel="alternate" type="text/html" title="What Concerns" /><published>2013-01-01T00:00:00+00:00</published><updated>2013-01-01T00:00:00+00:00</updated><id>https://rubyworks.github.io/facets/posts/what-concerns</id><content type="html" xml:base="https://rubyworks.github.io/facets/posts/2013-01-01-what-concerns.html"><![CDATA[<blockquote>
  <p><strong>Update, November 2026:</strong> Nothing has changed here: including a module still doesn’t bring its singleton methods along, and modules still can’t inherit from one another, as I proposed in <a href="/facets/posts/2010-04-13-a-case-for-module-inheritance.html">The Case for Module Inheritance</a>.</p>
</blockquote>

<p>David Heinemeier Hansson, the well known creator of Rails, recently gave a little <a href="http://37signals.com/svn/posts/3372-put-chubby-models-on-a-diet-with-concerns">pep-talk</a> for the use of <code class="language-plaintext highlighter-rouge">ActiveSupport::Concern</code>, making an argument that they were sufficient to satisfy the practical needs of <a href="http://en.wikipedia.org/wiki/Data,_context_and_interaction">DCI</a>’s theory.</p>

<p>What he fails to explain is what Concerns <em>really are</em>. Truth be told, Concerns are essentially an extension of Ruby’s <code class="language-plaintext highlighter-rouge">Module</code> class to more fully support <em>multiple inheritance</em>. Whether out of indifference, simple oversight or perhaps a bit of decorum to save Matz’s sensitivities, who has a well known distaste for multiple inheritance, DHH never mentions this simple fact. Concerns are a way for Rails developers to include Modules with the same degree of functionality as inheriting from a superclass.</p>

<p>To say that Concerns are like DCI Roles, is akin to saying C structs are like OOP Objects. Yea, there’s a similarity there, but it’s vastly missing the point.</p>]]></content><author><name>Thomas Sawyer</name></author><summary type="html"><![CDATA[Update, November 2026: Nothing has changed here: including a module still doesn’t bring its singleton methods along, and modules still can’t inherit from one another, as I proposed in The Case for Module Inheritance.]]></summary></entry><entry><title type="html">About those Refinements</title><link href="https://rubyworks.github.io/facets/posts/2012-12-04-about-those-refinements.html" rel="alternate" type="text/html" title="About those Refinements" /><published>2012-12-04T00:00:00+00:00</published><updated>2012-12-04T00:00:00+00:00</updated><id>https://rubyworks.github.io/facets/posts/about-those-refinements</id><content type="html" xml:base="https://rubyworks.github.io/facets/posts/2012-12-04-about-those-refinements.html"><![CDATA[<blockquote>
  <p><strong>Update, November 2026:</strong> Refinements arrived in Ruby 2.0, and since Ruby 2.1 <code class="language-plaintext highlighter-rouge">using</code> also works inside a class or module body, so the second downside below no longer applies.</p>
</blockquote>

<p>Well, after a ridiculously long discussion about refinements, it’s finally become clear what Matz is up to. It would have helped if he had mentioned from the start that he’s patterning them directly off of Smalltalk wrappers and CLOS method combinations. Instead we get <a href="https://web.archive.org/web/20130227155903/http://bugs.ruby-lang.org:80/projects/ruby-trunk/wiki/RefinementsSpec">this</a> “official” spec. Hardly. It was only thanks to Charles Nutter’s careful <a href="https://bugs.ruby-lang.org/issues/4085#note-217">analysis</a> that I was able to get a clear picture. Oh, the time and data that could have been saved!</p>

<p>So allow me to save you all the trouble and explain refinements in a very simple phrase: <em>macros des méthodes</em>. In plain English, they are macros that act on method invocations. For example,</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">module</span> <span class="nn">M</span>
  <span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">string</span><span class="p">(</span><span class="n">object</span><span class="p">)</span>
    <span class="n">object</span><span class="p">.</span><span class="nf">to_s</span>
  <span class="k">end</span>
<span class="k">end</span>

<span class="k">module</span> <span class="nn">Q</span>
  <span class="n">refine</span> <span class="no">String</span> <span class="k">do</span>
    <span class="k">def</span> <span class="nf">to_s</span>
      <span class="s2">"Every string is </span><span class="si">#{</span><span class="k">super</span><span class="si">}</span><span class="s2">!"</span>
    <span class="k">end</span>
  <span class="k">end</span>
<span class="k">end</span>

<span class="n">using</span> <span class="no">Q</span>

<span class="no">M</span><span class="p">.</span><span class="nf">string</span><span class="p">(</span><span class="s2">"okay"</span><span class="p">)</span> <span class="c1">#=&gt; "okay"</span>
</code></pre></div></div>

<p>Notice, the <code class="language-plaintext highlighter-rouge">M.string</code> method is not affected by the refinement of <code class="language-plaintext highlighter-rouge">String#to_s</code> even though it uses <code class="language-plaintext highlighter-rouge">#to_s</code> in its definition. However, if we use <code class="language-plaintext highlighter-rouge">#to_s</code> explicitly in the scope of the refinement’s use we get:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="s2">"okay"</span><span class="p">.</span><span class="nf">to_s</span> <span class="c1">#=&gt; "Every string is okay!"</span>
</code></pre></div></div>

<p>Even though that is exactly what the definition of <code class="language-plaintext highlighter-rouge">M.string</code> is, it produces the refined result instead. Since the call was explicit the refinement interceded.</p>

<p>That’s really the crux of refinements. Most of the remaining questions pertain to the order in which multiple refinements interact, but it is all pretty much as one would intuit it to be, so we won’t go into detail in that regard.</p>

<p>Now I thought it might be helpful to take an extreme example of what one could do with refinements and see if it leads us to anything interesting.</p>

<p>Let’s take just a bare class.</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Person</span>
<span class="k">end</span>
</code></pre></div></div>

<p>Now let’s create two refinements defining two different roles a person might take.</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">module</span> <span class="nn">Buyer</span>
  <span class="n">refine</span> <span class="no">Person</span> <span class="k">do</span>
    <span class="kp">attr</span> <span class="ss">:stuff</span><span class="p">,</span> <span class="ss">:money</span>
    <span class="k">def</span> <span class="nf">initialize</span><span class="p">(</span><span class="n">money</span><span class="p">,</span> <span class="o">*</span><span class="n">stuff</span><span class="p">)</span>
      <span class="vi">@money</span> <span class="o">=</span> <span class="n">money</span><span class="p">.</span><span class="nf">to_f</span>
      <span class="vi">@stuff</span> <span class="o">=</span> <span class="n">stuff</span>
    <span class="k">end</span>
    <span class="k">def</span> <span class="nf">buy</span><span class="p">(</span><span class="n">product</span><span class="p">,</span> <span class="n">cost</span><span class="p">)</span>
      <span class="vi">@stuff</span><span class="p">.</span><span class="nf">push</span> <span class="n">product</span>
      <span class="vi">@money</span> <span class="o">-=</span> <span class="n">cost</span>
    <span class="k">end</span>
  <span class="k">end</span>
<span class="k">end</span>

<span class="k">module</span> <span class="nn">Seller</span>
  <span class="n">refine</span> <span class="no">Person</span> <span class="k">do</span>
    <span class="kp">attr</span> <span class="ss">:stuff</span><span class="p">,</span> <span class="ss">:money</span>
    <span class="k">def</span> <span class="nf">initialize</span><span class="p">(</span><span class="n">money</span><span class="p">,</span> <span class="o">*</span><span class="n">stuff</span><span class="p">)</span>
      <span class="vi">@money</span> <span class="o">=</span> <span class="n">money</span><span class="p">.</span><span class="nf">to_f</span>
      <span class="vi">@stuff</span> <span class="o">=</span> <span class="n">stuff</span>
    <span class="k">end</span>
    <span class="k">def</span> <span class="nf">sell</span><span class="p">(</span><span class="n">product</span><span class="p">,</span> <span class="n">cost</span><span class="p">)</span>
      <span class="vi">@stuff</span><span class="p">.</span><span class="nf">delete</span> <span class="n">product</span>
      <span class="vi">@money</span> <span class="o">+=</span> <span class="n">cost</span>
    <span class="k">end</span>
  <span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>

<p>Now let’s define an activity in which persons interact as each of these roles.</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">using</span> <span class="no">Seller</span>
<span class="n">using</span> <span class="no">Buyer</span>

<span class="k">class</span> <span class="nc">SalesTransaction</span>
  <span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">make</span><span class="p">(</span><span class="n">buyer</span><span class="p">,</span> <span class="n">seller</span><span class="p">,</span> <span class="n">product</span><span class="p">,</span> <span class="n">cost</span><span class="p">)</span>
    <span class="n">buyer</span><span class="p">.</span><span class="nf">buy</span><span class="p">(</span><span class="n">product</span><span class="p">,</span> <span class="n">cost</span><span class="p">)</span>
    <span class="n">seller</span><span class="p">.</span><span class="nf">sell</span><span class="p">(</span><span class="n">product</span><span class="p">,</span> <span class="n">cost</span><span class="p">)</span>
  <span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>

<p>Interesting? Person has no built-in behavior, and yet we’ve managed to use the class to model a sales transaction and give each person state of what they own and how much money they have. And an outside interface can’t find this state out unless it knows what role to apply!</p>

<p>You might recognize the pattern of this example. It is <a href="http://en.wikipedia.org/wiki/Data,_context_and_interaction">DCI</a>. Does this mean refinements are a perfect fit for DCI-based designs? Might we see a whole new paradigm in Ruby architecture built around the DCI? That’s a good question. At first glance it certainly seems to be possible. But we should note a few obvious downsides.</p>

<ol>
  <li>Both refinements required an <code class="language-plaintext highlighter-rouge">#initialize</code> method to ensure the instance variables are initialized. So  refinements of this kind would have to be compatible in this respect in order to be used together.</li>
  <li>The context, in this case <code class="language-plaintext highlighter-rouge">SalesTransaction</code>, has to exist in its own file so only the appropriate refinements apply. There is no way to define contexts that use different refinements in the same file because refinements are applied on a per-file basis. Although, some level of cleverness could be played if certain contexts simply add additional refinements on top of those used earlier in the file.</li>
  <li>While it remains to be seen, it is unlikely that an entire system written in this fashion will be very fast. Nor is it entirely certain that it would be very comprehensible, but perhaps that has more to do with DCI than refinements.</li>
</ol>]]></content><author><name>Thomas Sawyer</name></author><summary type="html"><![CDATA[Update, November 2026: Refinements arrived in Ruby 2.0, and since Ruby 2.1 using also works inside a class or module body, so the second downside below no longer applies.]]></summary></entry><entry><title type="html">Kill the Proxy and Save Toplevel</title><link href="https://rubyworks.github.io/facets/posts/2012-06-17-kill-the-proxy-and-save-toplevel.html" rel="alternate" type="text/html" title="Kill the Proxy and Save Toplevel" /><published>2012-06-17T00:00:00+00:00</published><updated>2012-06-17T00:00:00+00:00</updated><id>https://rubyworks.github.io/facets/posts/kill-the-proxy-and-save-toplevel</id><content type="html" xml:base="https://rubyworks.github.io/facets/posts/2012-06-17-kill-the-proxy-and-save-toplevel.html"><![CDATA[<p>Ruby’s top level is an odd place. It looks like a convenient place to write
a little program, but it also participates in the behavior of objects
throughout that program. For ordinary scripts, this is often useful. For a
library that wants to host a small scripting language, it deserves a closer
look.</p>

<p>Ask Ruby what object is receiving calls at the top level:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">self</span>        <span class="c1"># =&gt; main</span>
<span class="nb">self</span><span class="p">.</span><span class="nf">class</span>  <span class="c1"># =&gt; Object</span>
</code></pre></div></div>

<p>That <code class="language-plaintext highlighter-rouge">main</code> is a particular object. It isn’t the <code class="language-plaintext highlighter-rouge">Object</code> class, and it
isn’t a module representing our script. Yet a plain method definition here
lands in <code class="language-plaintext highlighter-rouge">Object</code>:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">greeting</span>
  <span class="s1">'hello'</span>
<span class="k">end</span>

<span class="nb">method</span><span class="p">(</span><span class="ss">:greeting</span><span class="p">).</span><span class="nf">owner</span> <span class="o">==</span> <span class="no">Object</span>
<span class="c1"># =&gt; true</span>

<span class="no">Object</span><span class="p">.</span><span class="nf">private_instance_methods</span><span class="p">(</span><span class="kp">false</span><span class="p">).</span><span class="nf">include?</span><span class="p">(</span><span class="ss">:greeting</span><span class="p">)</span>
<span class="c1"># =&gt; true</span>

<span class="no">Object</span><span class="p">.</span><span class="nf">new</span><span class="p">.</span><span class="nf">send</span><span class="p">(</span><span class="ss">:greeting</span><span class="p">)</span>
<span class="c1"># =&gt; "hello"</span>
</code></pre></div></div>

<p>The method is private, but objects inheriting from <code class="language-plaintext highlighter-rouge">Object</code> can still call
it internally. A helper defined for the script has become an inherited
method available far beyond the script’s apparent boundary.</p>

<p>That is the behavior I want to question. Defining a top-level helper is
perfectly reasonable Ruby. It also has a wider effect than someone writing
an application-specific script might expect.</p>

<h2 id="the-receiver-and-the-definition-target">The receiver and the definition target</h2>

<p>Current Ruby supports dynamic top-level definitions too. On Ruby 3.4, this
works:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">define_method</span><span class="p">(</span><span class="ss">:dynamic_greeting</span><span class="p">)</span> <span class="p">{</span> <span class="s1">'dynamic hello'</span> <span class="p">}</span>
<span class="no">Object</span><span class="p">.</span><span class="nf">new</span><span class="p">.</span><span class="nf">send</span><span class="p">(</span><span class="ss">:dynamic_greeting</span><span class="p">)</span>
<span class="c1"># =&gt; "dynamic hello"</span>
</code></pre></div></div>

<p>The interesting distinction is where such definitions belong, rather than
whether a particular helper exists. <code class="language-plaintext highlighter-rouge">main</code> is still the receiver while
<code class="language-plaintext highlighter-rouge">Object</code> receives the new instance method.</p>

<p>A small declaration helper makes that difference visible:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">module</span> <span class="nn">Declarations</span>
  <span class="k">def</span> <span class="nf">field</span><span class="p">(</span><span class="nb">name</span><span class="p">)</span>
    <span class="n">declared_on</span> <span class="o">=</span> <span class="nb">self</span>
    <span class="n">define_method</span><span class="p">(</span><span class="nb">name</span><span class="p">)</span> <span class="p">{</span> <span class="n">declared_on</span> <span class="p">}</span>
  <span class="k">end</span>
<span class="k">end</span>

<span class="k">class</span> <span class="nc">Record</span>
  <span class="kp">extend</span> <span class="no">Declarations</span>
  <span class="n">field</span> <span class="ss">:declaration_context</span>
<span class="k">end</span>

<span class="no">Record</span><span class="p">.</span><span class="nf">new</span><span class="p">.</span><span class="nf">declaration_context</span> <span class="o">==</span> <span class="no">Record</span>
<span class="c1"># =&gt; true</span>
</code></pre></div></div>

<p>In the class body, the object receiving <code class="language-plaintext highlighter-rouge">field</code> is the class that gets the
new instance method. Now try the same declaration at the top level:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">top</span> <span class="o">=</span> <span class="nb">self</span>
<span class="kp">extend</span> <span class="no">Declarations</span>
<span class="n">field</span> <span class="ss">:top_context</span>

<span class="no">Object</span><span class="p">.</span><span class="nf">new</span><span class="p">.</span><span class="nf">send</span><span class="p">(</span><span class="ss">:top_context</span><span class="p">).</span><span class="nf">equal?</span><span class="p">(</span><span class="n">top</span><span class="p">)</span>
<span class="c1"># =&gt; true</span>

<span class="n">top</span><span class="p">.</span><span class="nf">equal?</span><span class="p">(</span><span class="no">Object</span><span class="p">)</span>
<span class="c1"># =&gt; false</span>
</code></pre></div></div>

<p>We captured <code class="language-plaintext highlighter-rouge">main</code>, while the method was defined on <code class="language-plaintext highlighter-rouge">Object</code>. Nothing
mysterious happened once the rules were understood. But a reusable DSL
cannot assume its declaration receiver and definition target are identical
in these two contexts.</p>

<p>That is what I mean by the proxy problem: the top level offers conveniences
for working with another definition context, while remaining a distinct
object with its own identity. It isn’t a general-purpose module namespace.</p>

<h2 id="give-the-script-a-namespace">Give the script a namespace</h2>

<p>My preferred alternative is to make the script’s top level a self-extended
module. Written explicitly in ordinary Ruby, that looks like this:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">module</span> <span class="nn">MAIN</span>
  <span class="kp">extend</span> <span class="nb">self</span>

  <span class="k">def</span> <span class="nf">namespaced_greeting</span>
    <span class="s1">'hello from MAIN'</span>
  <span class="k">end</span>

  <span class="n">define_method</span><span class="p">(</span><span class="ss">:namespaced_dynamic</span><span class="p">)</span> <span class="p">{</span> <span class="s1">'dynamic MAIN'</span> <span class="p">}</span>
<span class="k">end</span>

<span class="no">MAIN</span><span class="p">.</span><span class="nf">namespaced_greeting</span>
<span class="c1"># =&gt; "hello from MAIN"</span>
</code></pre></div></div>

<p>The definitions now belong to a module we can inspect and use deliberately.
They don’t become methods on every ordinary object merely because we wrote
a helper for our script. If a class does need the behavior, inclusion can
make that choice explicit:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Consumer</span>
  <span class="kp">include</span> <span class="no">MAIN</span>
<span class="k">end</span>

<span class="no">Consumer</span><span class="p">.</span><span class="nf">new</span><span class="p">.</span><span class="nf">namespaced_greeting</span>
<span class="c1"># =&gt; "hello from MAIN"</span>
</code></pre></div></div>

<p>This doesn’t abolish the distinction between module and instance calls.
A method called through <code class="language-plaintext highlighter-rouge">MAIN</code> receives <code class="language-plaintext highlighter-rouge">MAIN</code> as <code class="language-plaintext highlighter-rouge">self</code>; the same method
included in <code class="language-plaintext highlighter-rouge">Consumer</code> receives a consumer instance. Shared state and
receiver assumptions still require thought. The benefit is an explicit
boundary for the definitions.</p>

<h2 id="a-loader-can-choose-this-policy-today">A loader can choose this policy today</h2>

<p>We don’t need a language change to give one application’s scripts a module
context. A small loader can create it, install its declaration interface,
and evaluate a trusted script there:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">module</span> <span class="nn">SettingsDSL</span>
  <span class="k">def</span> <span class="nf">option</span><span class="p">(</span><span class="nb">name</span><span class="p">,</span> <span class="n">default</span><span class="p">)</span>
    <span class="n">define_method</span><span class="p">(</span><span class="nb">name</span><span class="p">)</span> <span class="p">{</span> <span class="n">default</span> <span class="p">}</span>
  <span class="k">end</span>
<span class="k">end</span>

<span class="k">module</span> <span class="nn">ScriptLoader</span>
  <span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">load</span><span class="p">(</span><span class="n">source</span><span class="p">,</span> <span class="n">filename</span> <span class="o">=</span> <span class="s1">'settings.rb'</span><span class="p">)</span>
    <span class="n">context</span> <span class="o">=</span> <span class="no">Module</span><span class="p">.</span><span class="nf">new</span>
    <span class="n">context</span><span class="p">.</span><span class="nf">extend</span><span class="p">(</span><span class="n">context</span><span class="p">)</span>
    <span class="n">context</span><span class="p">.</span><span class="nf">extend</span><span class="p">(</span><span class="no">SettingsDSL</span><span class="p">)</span>
    <span class="n">context</span><span class="p">.</span><span class="nf">module_eval</span><span class="p">(</span><span class="n">source</span><span class="p">,</span> <span class="n">filename</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
    <span class="n">context</span>
  <span class="k">end</span>
<span class="k">end</span>

</code></pre></div></div>

<p>Here is a script and the resulting interface:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">settings</span> <span class="o">=</span> <span class="no">ScriptLoader</span><span class="p">.</span><span class="nf">load</span><span class="p">(</span><span class="o">&lt;&lt;~</span><span class="no">RUBY</span><span class="p">)</span><span class="sh">
  option :port, 8080
  def label
    "demo"
  end
</span><span class="no">RUBY</span>

<span class="n">settings</span><span class="p">.</span><span class="nf">port</span>   <span class="c1"># =&gt; 8080</span>
<span class="n">settings</span><span class="p">.</span><span class="nf">label</span>  <span class="c1"># =&gt; "demo"</span>
</code></pre></div></div>

<p>The string form of
<a href="https://docs.ruby-lang.org/en/3.4/Module.html#method-i-module_eval"><code class="language-plaintext highlighter-rouge">module_eval</code></a>
evaluates these definitions in the new module. Extending that module with
itself makes its instance methods callable through the module object as
well. The filename and line number help identify errors in the evaluated
source. Each load creates a separate context, so another script can define
its own <code class="language-plaintext highlighter-rouge">port</code> without replacing this one.</p>

<p>This gives the application a namespace policy, not a security sandbox.
The evaluated Ruby can still access files, globals, and other objects.
Nor does it make <code class="language-plaintext highlighter-rouge">require</code> automatically load additional scripts into the
same context. A real loader must decide how imports and shared definitions
work. Those are part of the design rather than details a wrapper can wish
away.</p>

<p>The <a href="../examples/toplevel/namespaces.rb">runnable namespace examples</a> check
the definition targets, captured receivers, explicit inclusion, and separate
loader contexts on Ruby 3.4.9. They can be run in their own process with:</p>

<div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code>ruby namespaces.rb
</code></pre></div></div>

<h2 id="changing-rubys-default-would-be-a-larger-decision">Changing Ruby’s default would be a larger decision</h2>

<p>The explicit module is a working technique. Making it the language’s default
top level is a proposal with compatibility costs. Existing scripts expect
top-level methods to become private <code class="language-plaintext highlighter-rouge">Object</code> methods. Replacing that rule
would change lookup and could break code that relies on it.</p>

<p>A default <code class="language-plaintext highlighter-rouge">MAIN</code> would also need a clear identity: one module per file, per
application, or per loader? Where should constants go? What would a required
file share with its caller? Those questions need answers before an appealing
snippet becomes a coherent language design.</p>

<p>I still like the direction. A script’s helpers ought to have an obvious
home, and an application’s DSL ought to be able to choose its reach. A
self-extended module provides that home today when we use it explicitly.
Whether Ruby should make that the default is the more interesting argument
than whether we can add one more convenience method to <code class="language-plaintext highlighter-rouge">main</code>.</p>]]></content><author><name>Thomas Sawyer</name></author><summary type="html"><![CDATA[Ruby’s top level is an odd place. It looks like a convenient place to write a little program, but it also participates in the behavior of objects throughout that program. For ordinary scripts, this is often useful. For a library that wants to host a small scripting language, it deserves a closer look.]]></summary></entry><entry><title type="html">Autoload Smells like Denmark</title><link href="https://rubyworks.github.io/facets/posts/2012-06-14-autoload-smells-like-denmark.html" rel="alternate" type="text/html" title="Autoload Smells like Denmark" /><published>2012-06-14T00:00:00+00:00</published><updated>2012-06-14T00:00:00+00:00</updated><id>https://rubyworks.github.io/facets/posts/autoload-smells-like-denmark</id><content type="html" xml:base="https://rubyworks.github.io/facets/posts/2012-06-14-autoload-smells-like-denmark.html"><![CDATA[<blockquote>
  <p><strong>Update, November 2026:</strong> Both issues have since been dealt with. Since Ruby 2.3, autoload goes through <code class="language-plaintext highlighter-rouge">Kernel#require</code>, so overrides like RubyGems’ work with it, and Ruby 2.0 took care of the thread safety problem. Autoload wasn’t removed after all: Matz withdrew the proposal in 2019, and Rails’ Zeitwerk loader is built on it.</p>
</blockquote>

<p>Ruby has a very cool feature called <em>autoload</em>. With autoload, any undefined constant can automatically trigger the loading of a library file. Effectively this gives Ruby a convenient means of lazy loading. For example, let’s say some of our app’s executable scripts ultimately use the ANSI library, but others do not. We can use <code class="language-plaintext highlighter-rouge">autoload</code> to only load the ANSI library when it is needed.</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">autoload</span> <span class="ss">:ANSI</span><span class="p">,</span> <span class="s1">'ansi'</span>
</code></pre></div></div>

<p>This says to <code class="language-plaintext highlighter-rouge">require "ansi"</code> the first time an undefined ANSI constant is encountered.</p>

<p>As wonderful as autoload seems, it has two glaring issues: 1) It doesn’t use standard Kernel#require and 2) It is not thread safe.</p>

<p>For the first, this means that any overriding of #require will not be supported by autoload. Of course such a thing is very rare, but it does occur. For instance the <a href="https://rubygems.org/gems/roll">Roll</a> library is all about overriding <code class="language-plaintext highlighter-rouge">#require</code>. Also RubyGems overrides #require, and in fact one can cause a bug to occur when using autoload because of it. Here’s a very simple <a href="http://stackoverflow.com/questions/849622/autoload-raises-an-error-but-require-does-not-ruby">example</a>.</p>

<p>On the second case the issue seems much more complicated, and a solution seems so unlikely that Matz has called for #autoload to be <a href="http://bugs.ruby-lang.org/issues/5653">removed</a> from Ruby by v3.0.0. That’s a long way off but just the same it doesn’t bode well for autoload.</p>

<p>Now that Matz has effectively declared <code class="language-plaintext highlighter-rouge">#autoload</code> a code smell, I wonder if developers will take heed and stop using it? I have my doubts –it’s just too damn convenient. I just wish it would use <code class="language-plaintext highlighter-rouge">Kernel#require</code> so I could use it along with Rolls.</p>]]></content><author><name>Thomas Sawyer</name></author><summary type="html"><![CDATA[Update, November 2026: Both issues have since been dealt with. Since Ruby 2.3, autoload goes through Kernel#require, so overrides like RubyGems’ work with it, and Ruby 2.0 took care of the thread safety problem. Autoload wasn’t removed after all: Matz withdrew the proposal in 2019, and Rails’ Zeitwerk loader is built on it.]]></summary></entry><entry><title type="html">Instance Variables as Syntax Sugar</title><link href="https://rubyworks.github.io/facets/posts/2012-06-13-instance-variables-as-syntax-sugar.html" rel="alternate" type="text/html" title="Instance Variables as Syntax Sugar" /><published>2012-06-13T00:00:00+00:00</published><updated>2012-06-13T00:00:00+00:00</updated><id>https://rubyworks.github.io/facets/posts/instance-variables-as-syntax-sugar</id><content type="html" xml:base="https://rubyworks.github.io/facets/posts/2012-06-13-instance-variables-as-syntax-sugar.html"><![CDATA[<blockquote>
  <p><strong>Update, November 2026:</strong> Ruby never made <code class="language-plaintext highlighter-rouge">@</code> a hash, but Ruby 2.6’s <code class="language-plaintext highlighter-rouge">to_h</code> with a block does shorten the serialization loop below: <code class="language-plaintext highlighter-rouge">instance_variables.to_h { |v| [v, instance_variable_get(v)] }</code>. Facets had something close as <code class="language-plaintext highlighter-rouge">Kernel#instance</code>; it’s now the separate instance gem.</p>
</blockquote>

<p>What are instance variables? If we think of them as a single unit we note that they represent an object <em>state</em>, which as a data structure is really nothing more than a <em>hash</em>. Indeed, it is quite feasible to forgo the use of instance variables altogether save one, to serve as the object’s state.</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Example</span>
  <span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">attr_reader</span><span class="p">(</span><span class="nb">name</span><span class="p">)</span>
    <span class="n">define_method</span><span class="p">(</span><span class="nb">name</span><span class="p">){</span> <span class="vi">@state</span><span class="p">[</span><span class="nb">name</span><span class="p">.</span><span class="nf">to_sym</span><span class="p">]</span> <span class="p">}</span>
  <span class="k">end</span>

  <span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">attr_writer</span><span class="p">(</span><span class="nb">name</span><span class="p">)</span>
    <span class="n">define_method</span><span class="p">(</span><span class="s2">"</span><span class="si">#{</span><span class="nb">name</span><span class="si">}</span><span class="s2">="</span><span class="p">){</span> <span class="o">|</span><span class="n">v</span><span class="o">|</span> <span class="vi">@state</span><span class="p">[</span><span class="nb">name</span><span class="p">.</span><span class="nf">to_sym</span><span class="p">]</span> <span class="o">=</span> <span class="n">v</span> <span class="p">}</span>
  <span class="k">end</span>

  <span class="k">def</span> <span class="nc">self</span><span class="o">.</span><span class="nf">attr_accessor</span><span class="p">(</span><span class="nb">name</span><span class="p">)</span>
    <span class="nb">attr_reader</span><span class="p">(</span><span class="nb">name</span><span class="p">)</span>
    <span class="nb">attr_writer</span><span class="p">(</span><span class="nb">name</span><span class="p">)</span>
  <span class="k">end</span>

  <span class="k">def</span> <span class="nf">initialize</span>
    <span class="vi">@state</span> <span class="o">=</span> <span class="p">{}</span>
  <span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>

<p>So if instance variables are essentially a hash, why is it that we cannot work with them as such? In other words, why not have <code class="language-plaintext highlighter-rouge">@</code> just represent a syntax sugar for a special hash (even if it’s not a standard Ruby Hash instance under the hood, it can behave as if it were). With such a change, handling instance variables immediately becomes much easier and intuitive since we can apply all our knowledge of hashes.</p>

<p>Some neat capabilities immediately become apparent. Looking up an instance variable given a variable name can be done with:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="err">@</span><span class="p">[</span><span class="nb">name</span><span class="p">]</span>
</code></pre></div></div>

<p>Assigning an instance variable likewise can be done with:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="err">@</span><span class="p">[</span><span class="nb">name</span><span class="p">]</span> <span class="o">=</span> <span class="n">value</span>
</code></pre></div></div>

<p>No longer would the long-winded <code class="language-plaintext highlighter-rouge">instance_variable_get</code> and <code class="language-plaintext highlighter-rouge">instance_variable_set</code> be needed.</p>

<p>Let’s take a more complex example. Have you ever wanted to reproduce the name and values of an object instance variable? It’s not uncommon really. Any type of object serialization is going to need such a routine – YAML, Marshal, etc. To do this presently requires some verbose code:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">hash</span> <span class="o">=</span> <span class="p">{}</span>
<span class="nb">instance_variables</span><span class="p">.</span><span class="nf">each</span> <span class="k">do</span> <span class="o">|</span><span class="n">var</span><span class="o">|</span>
  <span class="nb">hash</span><span class="p">[</span><span class="n">var</span><span class="p">]</span> <span class="o">=</span> <span class="nb">instance_variable_get</span><span class="p">(</span><span class="n">var</span><span class="p">)</span>
<span class="k">end</span>
<span class="nb">hash</span>
</code></pre></div></div>

<p>But with <code class="language-plaintext highlighter-rouge">@</code> sugar we can simply use:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">hash</span> <span class="o">=</span> <span class="err">@</span><span class="p">.</span><span class="nf">to_h</span>
</code></pre></div></div>

<p>Or if we just want to iterate over them:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="err">@</span><span class="p">.</span><span class="nf">each</span> <span class="k">do</span> <span class="o">|</span><span class="n">k</span><span class="p">,</span><span class="n">v</span><span class="o">|</span>
  <span class="o">...</span>
<span class="k">end</span>
</code></pre></div></div>

<p>Since we have #each, then all Enumerable methods would be at our disposal.</p>

<p>For a public interface <code class="language-plaintext highlighter-rouge">instance_variables</code> could reference the internal <code class="language-plaintext highlighter-rouge">@</code> instead of just the list of instance variable names. We could deprecate <code class="language-plaintext highlighter-rouge">#instance_variable_get</code> and <code class="language-plaintext highlighter-rouge">#instance_variable_set</code> altogether.</p>

<p>By recognizing the nature of instance variables and applying the preexisting functionality of Hash, we gain much greater capability while using fewer brain cells to do it. And that’s always a win.</p>]]></content><author><name>Thomas Sawyer</name></author><summary type="html"><![CDATA[Update, November 2026: Ruby never made @ a hash, but Ruby 2.6’s to_h with a block does shorten the serialization loop below: instance_variables.to_h { |v| [v, instance_variable_get(v)] }. Facets had something close as Kernel#instance; it’s now the separate instance gem.]]></summary></entry><entry><title type="html">Real Metal</title><link href="https://rubyworks.github.io/facets/posts/2012-05-23-real-metal.html" rel="alternate" type="text/html" title="Real Metal" /><published>2012-05-23T00:00:00+00:00</published><updated>2012-05-23T00:00:00+00:00</updated><id>https://rubyworks.github.io/facets/posts/real-metal</id><content type="html" xml:base="https://rubyworks.github.io/facets/posts/2012-05-23-real-metal.html"><![CDATA[<blockquote>
  <p><strong>Update, November 2026:</strong> Ruby 2.0 fixed the third shortcoming: a method taken from a module can now be bound to any object, BasicObject included. And Ruby 2.7’s <code class="language-plaintext highlighter-rouge">bind_call</code> makes the technique cheaper: <code class="language-plaintext highlighter-rouge">Kernel.instance_method(:class).bind_call(obj)</code>. No <code class="language-plaintext highlighter-rouge">$</code> notation, though.</p>
</blockquote>

<p>One of the most regarded capabilities of Ruby, in contrast to many other programming languages, is its powerful meta-programming chops. While not every aspect of the language is meta-programmable, the vast majority of Ruby is. But despite its prowess, there is a serious weakness in its design: <em>The functions on which meta-coders depend have no guarantee</em>.</p>

<p>Consider the most basic reflection method of determining the class of an object, fundamental to almost any meta-programming (and some not-so-meta-programming). We can write a class that completely subverts the ability to determine an object’s class.</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">Foo</span>
  <span class="k">def</span> <span class="nf">class</span>
    <span class="s2">"I Confuse You!"</span>
  <span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>

<p>Because <code class="language-plaintext highlighter-rouge">Foo</code> has overridden the <code class="language-plaintext highlighter-rouge">#class</code> method, there is no way to determine the class of an instance of Foo. Any code dependent on the <code class="language-plaintext highlighter-rouge">#class</code> method “contract” is going to choke.</p>

<p>We can be thankful that most programs will, by simple happenstance, never tread on any of these important methods. In the few cases where they might, most Ruby coders are aware enough to steer clear. Yet there are other cases not so easily handled. Consider Ruby’s relatively new BasicObject class. It has the minimal number of methods necessary to function as an object in Ruby. This is excellent for the construction of open classes akin to OpenStruct, but consequently there is no way to find out what methods are defined on such an object because there is no such methods as <code class="language-plaintext highlighter-rouge">#methods</code> or <code class="language-plaintext highlighter-rouge">#instance_methods</code>. Moreover, BasicObject is still not completely empty. It still defines <code class="language-plaintext highlighter-rouge">__id__</code>, <code class="language-plaintext highlighter-rouge">__send__</code>, <code class="language-plaintext highlighter-rouge">instance_eval</code>, <code class="language-plaintext highlighter-rouge">instance_exec</code> and a few others, without which an object simply wouldn’t be usable.</p>

<p>So basically Ruby has settled on a “close enough” approach to handling reflection and meta-programming. But why should we be willing to settle for any risk at all? The reasoning I have most often heard is an OOPL ideological principle arguing that no method should stand outside the realm of the inheritance chain, and thus all methods are necessarily subject to overrides. But I am not convinced for the simple reason that meta-programming is by its nature “<em>meta</em>”.</p>

<p>As an experiment, I developed a small library to take the risk out of meta-coding. The library basically works as follows:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="vg">$meta</span> <span class="o">=</span> <span class="no">Proc</span><span class="p">.</span><span class="nf">new</span> <span class="k">do</span> <span class="o">|</span><span class="n">obj</span><span class="o">|</span>
  <span class="no">Functor</span><span class="p">.</span><span class="nf">new</span> <span class="k">do</span> <span class="o">|</span><span class="n">op</span><span class="p">,</span> <span class="o">*</span><span class="n">a</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">b</span><span class="o">|</span>
    <span class="no">Kernel</span><span class="p">.</span><span class="nf">instance_method</span><span class="p">(</span><span class="n">op</span><span class="p">).</span><span class="nf">bind</span><span class="p">(</span><span class="n">obj</span><span class="p">).</span><span class="nf">call</span><span class="p">(</span><span class="o">*</span><span class="n">a</span><span class="p">,</span> <span class="o">&amp;</span><span class="n">b</span><span class="p">)</span>
  <span class="k">end</span>
<span class="k">end</span>

<span class="vg">$meta</span><span class="p">[</span><span class="s2">"some string"</span><span class="p">].</span><span class="nf">class</span> <span class="c1">#=&gt; String</span>
</code></pre></div></div>

<p>This meta-function works fairly well in most cases. However it has three shortcomings that make it essentially impractical for production use: 1) It lacks module methods; 2) It is terribly inefficient; and 3) It doesn’t work for BasicObject instances.</p>

<p>While my little library might be improved upon, ideally Ruby would provide a set of “meta-functions” that cannot be overridden in-class. These methods could all be defined in a special module, but used via alternate notation so as not to conflict with ordinary methods. To that end I suggest using <code class="language-plaintext highlighter-rouge">$</code> on regular objects:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">obj</span> <span class="o">=</span> <span class="no">Object</span><span class="p">.</span><span class="nf">new</span>
<span class="n">obj</span><span class="vg">$class</span> <span class="c1">#=&gt; Object</span>
</code></pre></div></div>

<p>Numerous other methods would be made available through this, in general all public Kernel methods are candidates for inclusion, and some Module methods usable just for classes and modules, such as <code class="language-plaintext highlighter-rouge">#instance_methods</code>.</p>

<p>The robustness this would bring to Ruby’s meta-programming would be a great boon and should not be understated. When a single line of code can so easily cause every object in a program to fail, it’s not unreasonable to prefer some guarantees. Moreover, it makes the meta-programmer’s task much easier –he knows exactly what methods on which to depend.</p>]]></content><author><name>Thomas Sawyer</name></author><summary type="html"><![CDATA[Update, November 2026: Ruby 2.0 fixed the third shortcoming: a method taken from a module can now be bound to any object, BasicObject included. And Ruby 2.7’s bind_call makes the technique cheaper: Kernel.instance_method(:class).bind_call(obj). No $ notation, though.]]></summary></entry><entry><title type="html">Setting Priorities Trumps Warnings</title><link href="https://rubyworks.github.io/facets/posts/2012-02-25-setting-priorities-trumps-warnings.html" rel="alternate" type="text/html" title="Setting Priorities Trumps Warnings" /><published>2012-02-25T00:00:00+00:00</published><updated>2012-02-25T00:00:00+00:00</updated><id>https://rubyworks.github.io/facets/posts/setting-priorities-trumps-warnings</id><content type="html" xml:base="https://rubyworks.github.io/facets/posts/2012-02-25-setting-priorities-trumps-warnings.html"><![CDATA[<blockquote>
  <p><strong>Update, November 2026:</strong> Ruby never adopted anything like this. It went with warning categories instead: since Ruby 2.7, categories like <code class="language-plaintext highlighter-rouge">:deprecated</code> can be switched on and off, and since Ruby 2.4, <code class="language-plaintext highlighter-rouge">Warning.warn</code> can be overridden to handle warnings however you like. <code class="language-plaintext highlighter-rouge">$VERBOSE</code> still has just three settings.</p>
</blockquote>

<p>Today I had to consider how best to handle omission exceptions in the context of test frameworks, and their use case to mark <em>pending tests</em>. In the course of doing so, I realized there are at least two reasonable levels of omission, those that are “ASAP” and those that are “NSM” (Not So Much). Whereas other frameworks used their own specially defined classes for these, e.g. <code class="language-plaintext highlighter-rouge">Pending</code> and <code class="language-plaintext highlighter-rouge">Omission</code>, my approach is to re-utilize Ruby’s own <code class="language-plaintext highlighter-rouge">NotImplementedError</code>. But then I had to consider how to differentiate between these priorities.</p>

<p>And that’s when the more general notion occurred to me of <strong>Exception Priorities</strong>.</p>

<p>Consider that instead of raising a warning:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">warn</span> <span class="s2">"Don't do it, mate!"</span>
</code></pre></div></div>

<p>We could use the Exception system, setting a low “warning” level priority.</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">raise</span> <span class="s2">"Don't do it, mate!"</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span>
</code></pre></div></div>

<p>All things being nominal, Ruby would see the priority of this exception is below 0, output the message to <code class="language-plaintext highlighter-rouge">$stderr</code> if <code class="language-plaintext highlighter-rouge">$VERBOSE=true</code> and then continue on. Hence it is a warning!</p>

<p>With this, <code class="language-plaintext highlighter-rouge">#warn</code> could become a simple alias for <code class="language-plaintext highlighter-rouge">#raise</code> with a default negative priority.</p>

<p>Now, if that was all there was to it, then there would be little reason to adopt the idea. But there are some really nice advantages to this approach.</p>

<p>With regards to warning messages, we could use the <code class="language-plaintext highlighter-rouge">$VERBOSE</code> setting to refine the level of warning we want to be notified about.</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="vg">$VERBOSE</span> <span class="o">=</span> <span class="o">-</span><span class="mi">1</span>
<span class="k">raise</span> <span class="s2">"More Serious Warning!"</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span>
<span class="k">raise</span> <span class="s2">"Less Serious Warning!"</span><span class="p">,</span> <span class="o">-</span><span class="mi">2</span>
</code></pre></div></div>

<p>In this case we would never see the <code class="language-plaintext highlighter-rouge">-2</code> level warning b/c we’ve indicated we don’t want to see those by setting $VERBOSE to a higher specific level.</p>

<p>Interestingly enough, we can do the same for actually raising errors! Let’s call the setting <code class="language-plaintext highlighter-rouge">$PRIORITY</code> for the sake of discussion.</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="vg">$PRIORITY</span> <span class="o">=</span> <span class="o">-</span><span class="mi">1</span>
<span class="k">raise</span> <span class="s2">"More Serious Warning!"</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span>
<span class="k">raise</span> <span class="s2">"Less Serious Warning!"</span><span class="p">,</span> <span class="o">-</span><span class="mi">2</span>
</code></pre></div></div>

<p>Whereas before, the “More Serious Warning” would just have printed a warning message to <code class="language-plaintext highlighter-rouge">$stderr</code>, in this case the Exception will actually be raised, b/c we have lowered the threshold at which exceptions are to be raised.</p>

<p>This refinement to Ruby’s Exception system, effectively subsuming the warning system within it, makes for a much more powerful, flexible and thus useful system. Take my original use case, I can set the priority of NotImplementedError to <code class="language-plaintext highlighter-rouge">1</code> for ASAPs and <code class="language-plaintext highlighter-rouge">0</code> for NSMs, and I can go further allowing testers to set high priorities to be selectable from the command line.</p>

<p>Want another use case? How about a <code class="language-plaintext highlighter-rouge">DeprecatedError</code> that has a default priority of <code class="language-plaintext highlighter-rouge">-1</code>.</p>

<p>I am certain others will think of other use cases as well. This is one of those pliable features that tend to have far wider applicability than the originating use case.</p>

<p>P.S. I’ve always thought it would make more sense if <code class="language-plaintext highlighter-rouge">$VERBOSE</code> were called <code class="language-plaintext highlighter-rouge">$WARN</code>.</p>]]></content><author><name>Thomas Sawyer</name></author><summary type="html"><![CDATA[Update, November 2026: Ruby never adopted anything like this. It went with warning categories instead: since Ruby 2.7, categories like :deprecated can be switched on and off, and since Ruby 2.4, Warning.warn can be overridden to handle warnings however you like. $VERBOSE still has just three settings.]]></summary></entry><entry><title type="html">Ruby’s Exceptional Exception Constructor</title><link href="https://rubyworks.github.io/facets/posts/2012-01-19-rubys-unexceptional-exception-constructor.html" rel="alternate" type="text/html" title="Ruby’s Exceptional Exception Constructor" /><published>2012-01-19T00:00:00+00:00</published><updated>2012-01-19T00:00:00+00:00</updated><id>https://rubyworks.github.io/facets/posts/rubys-unexceptional-exception-constructor</id><content type="html" xml:base="https://rubyworks.github.io/facets/posts/2012-01-19-rubys-unexceptional-exception-constructor.html"><![CDATA[<blockquote>
  <p><strong>Update, November 2026:</strong> Still the case: <code class="language-plaintext highlighter-rouge">raise</code> passes only the message to <code class="language-plaintext highlighter-rouge">initialize</code> and sets the backtrace separately. The <code class="language-plaintext highlighter-rouge">set_message</code> I asked for in that issue was rejected.</p>
</blockquote>

<p>You would think after all this time Ruby’s Exception class would be a rather robust and clearly comprehensible class.</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">raise</span><span class="p">(</span><span class="n">exception</span> <span class="p">[,</span> <span class="n">string</span> <span class="p">[,</span> <span class="n">array</span><span class="p">]])</span>
</code></pre></div></div>

<p>Now let’s try something:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">MyError</span> <span class="o">&lt;</span> <span class="no">Exception</span>
  <span class="k">def</span> <span class="nf">initialize</span><span class="p">()</span>
    <span class="k">super</span><span class="p">()</span>
  <span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">&gt;&gt;</span> <span class="k">raise</span> <span class="no">MyError</span>
<span class="no">MyError</span><span class="p">:</span> <span class="no">MyError</span>
	<span class="n">from</span> <span class="p">(</span><span class="n">irb</span><span class="p">):</span><span class="mi">12</span>
	<span class="n">from</span> <span class="sr">/home/</span><span class="n">trans</span><span class="o">/</span><span class="p">.</span><span class="nf">rbenv</span><span class="o">/</span><span class="n">versions</span><span class="o">/</span><span class="mf">1.9</span><span class="o">.</span><span class="mi">3</span><span class="o">-</span><span class="n">rc1</span><span class="o">/</span><span class="n">bin</span><span class="o">/</span><span class="n">irb</span><span class="p">:</span><span class="mi">12</span><span class="ss">:in</span> <span class="sb">`&lt;main&gt;'
</span></code></pre></div></div>

<p>No problem. But now let’s try to set the message and the backtrace.</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">&gt;&gt;</span> <span class="k">raise</span> <span class="no">MyError</span><span class="p">,</span> <span class="s2">"This is an error!"</span>
<span class="no">ArgumentError</span><span class="p">:</span> <span class="n">wrong</span> <span class="n">number</span> <span class="n">of</span> <span class="n">arguments</span> <span class="p">(</span><span class="mi">1</span> <span class="k">for</span> <span class="mi">0</span><span class="p">)</span>
	<span class="n">from</span> <span class="p">(</span><span class="n">irb</span><span class="p">):</span><span class="mi">8</span><span class="ss">:in</span> <span class="sb">`initialize'
	from (irb):13:in `</span><span class="n">exception</span><span class="s1">'
	from (irb):13:in `raise'</span>
</code></pre></div></div>

<p>Clearly Ruby expects any Exception’s initialize method to handle the message argument. That’s a rather strict contract for something Ruby is letting us override. But okay, let’s take that as a given. Obviously Ruby is routing the #raise call to the exception’s initializer. So then we should expect that the third <code class="language-plaintext highlighter-rouge">array</code> argument would be passed along too. Turns out that’s not the case.</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">class</span> <span class="nc">MyError</span> <span class="o">&lt;</span> <span class="no">Exception</span>
  <span class="k">def</span> <span class="nf">initialize</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">)</span>
    <span class="nb">p</span> <span class="n">args</span>
    <span class="k">super</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">)</span>
  <span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">&gt;&gt;</span> <span class="k">raise</span> <span class="no">MyError</span><span class="p">,</span> <span class="s2">"This is an error!"</span><span class="p">,</span> <span class="nb">caller</span>
<span class="p">[</span><span class="s2">"This is an error!"</span><span class="p">]</span>
<span class="no">MyError</span><span class="p">:</span> <span class="no">This</span> <span class="n">is</span> <span class="n">an</span> <span class="n">error!</span>
	<span class="n">from</span> <span class="p">(</span><span class="n">irb</span><span class="p">):</span><span class="mi">1</span>
	<span class="n">from</span> <span class="sr">/home/</span><span class="n">trans</span><span class="o">/</span><span class="p">.</span><span class="nf">rbenv</span><span class="o">/</span><span class="n">versions</span><span class="o">/</span><span class="mf">1.9</span><span class="o">.</span><span class="mi">3</span><span class="o">-</span><span class="n">rc1</span><span class="o">/</span><span class="n">bin</span><span class="o">/</span><span class="n">irb</span><span class="p">:</span><span class="mi">12</span><span class="ss">:in</span> <span class="sb">`&lt;main&gt;'
</span></code></pre></div></div>

<p>Nope. No caller in sight. So where did it go? Turns out Ruby is setting the caller via the error’s <code class="language-plaintext highlighter-rouge">#set_backtrace</code> method and doesn’t depend on the initializer to handle it at all. This seems rather odd, since it was keen on letting the initializer handle the message argument, and would blow-up if the class won’t take it.</p>

<p>So the upshot seems to be that we can’t customize an exception’s initializer and expect <code class="language-plaintext highlighter-rouge">#raise</code> to play along.</p>

<p>I actually had another point to make about how things get even worse. Unfortunately I had to take care of other chores and by the time I got back to this blog post (months later) I forgot what these “worse things” were. I think it had something to do with how <code class="language-plaintext highlighter-rouge">#message</code> calls <code class="language-plaintext highlighter-rouge">#to_s</code> rather than returning the message passed to the initializer. But as said I am not certain now.</p>

<p>My conclusion however is this. I was attempting to make use of an Exception class as something more than a mere container for a string message for the <a href="http://github.com/rubyworks/assay">Assay</a> project. That is when I ran into these oddities which made doing so quite unpleasant. To my dismay I ended up abandoning the approach. I brought some aspects of this up in an <a href="http://bugs.ruby-lang.org/issues/5898">issue report</a>.</p>

<p>For reference, here is the relevant Ruby <a href="https://github.com/ruby/ruby/blob/87daaf61b9a6db7d4e4c7df9c72c4621ef0162c2/eval.c">source code</a>.</p>]]></content><author><name>Thomas Sawyer</name></author><summary type="html"><![CDATA[Update, November 2026: Still the case: raise passes only the message to initialize and sets the backtrace separately. The set_message I asked for in that issue was rejected.]]></summary></entry><entry><title type="html">Lazy Plus Enumerable Begats Denumerable</title><link href="https://rubyworks.github.io/facets/posts/2011-10-04-lazy-plus-enumerable-begats-denumerable.html" rel="alternate" type="text/html" title="Lazy Plus Enumerable Begats Denumerable" /><published>2011-10-04T00:00:00+00:00</published><updated>2011-10-04T00:00:00+00:00</updated><id>https://rubyworks.github.io/facets/posts/lazy-plus-enumerable-begats-denumerable</id><content type="html" xml:base="https://rubyworks.github.io/facets/posts/2011-10-04-lazy-plus-enumerable-begats-denumerable.html"><![CDATA[<blockquote>
  <p><strong>Update, November 2026:</strong> Ruby 2.0 added <code class="language-plaintext highlighter-rouge">Enumerable#lazy</code>, which does what <code class="language-plaintext highlighter-rouge">defer</code> does here, and Facets has deprecated <code class="language-plaintext highlighter-rouge">defer</code> in its favor. <code class="language-plaintext highlighter-rouge">Denumerable</code> and <code class="language-plaintext highlighter-rouge">Denumerator</code> are still in Facets.</p>
</blockquote>

<p>All Rubyists know and love Enumerable. It’s really the showcase of Ruby’s mixin system. Some Rubyists also know and appreciate <a href="https://web.archive.org/web/20110912073235/http://moonbase.rydia.net:80/software/lazy.rb/">lazy.rb</a> MenTaLguY’s excellent lazy evaluation library. But did you know there is library that essentially cross-breeds the ideas of both? It’s called <a href="https://github.com/rubyworks/facets/blob/main/lib/core/facets/denumerable.rb">Denumerable</a> and is included in Ruby Facets (<code class="language-plaintext highlighter-rouge">require 'facets/denumerable'</code>).</p>

<p>According to Webster’s The term <code class="language-plaintext highlighter-rouge">denumerable</code> is just a synonym for <code class="language-plaintext highlighter-rouge">enumerable</code>. In Ruby parlance, it takes a more useful distinction of “deferred enumerable”. In other words Denumerable defers actual calculations of a chain of enumerable method calls until the results are actually needed. That’s where the “laziness” comes in. By deferring calculation Ruby is able to optimize the algorithm, in many cases greatly improving performance. It’s even possible to enumerate infinite ranges if the end result itself is finite.</p>

<p>To make it even more convenient there is <a href="https://github.com/rubyworks/facets/blob/main/lib/core/facets/enumerable/defer.rb">Enumerable#defer</a> (<code class="language-plaintext highlighter-rouge">require 'facets/enumerable/defer'</code>) which delegates an Enumerable object through a Denumerator, just like Ruby’s core Enumerator class.</p>

<p>So, enough talk, right? How about an example.</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">a</span> <span class="o">=</span> <span class="p">(</span><span class="mi">1</span><span class="o">..</span><span class="mi">1_000_000_000</span><span class="p">).</span><span class="nf">defer</span><span class="p">.</span><span class="nf">select</span><span class="p">{</span> <span class="o">|</span><span class="n">i</span><span class="o">|</span> <span class="n">i</span> <span class="o">%</span> <span class="mi">2</span> <span class="o">==</span> <span class="mi">0</span> <span class="p">}.</span>
                             <span class="nf">map</span><span class="p">{</span> <span class="o">|</span><span class="n">i</span><span class="o">|</span> <span class="n">i</span> <span class="o">+</span> <span class="mi">100</span> <span class="p">}.</span>
                             <span class="nf">take</span><span class="p">(</span><span class="mi">10</span><span class="p">).</span><span class="nf">to_a</span>
<span class="o">=&gt;</span> <span class="p">[</span><span class="mi">102</span><span class="p">,</span> <span class="mi">104</span><span class="p">,</span> <span class="mi">106</span><span class="p">,</span> <span class="mi">108</span><span class="p">,</span> <span class="mi">110</span><span class="p">,</span> <span class="mi">112</span><span class="p">,</span> <span class="mi">114</span><span class="p">,</span> <span class="mi">116</span><span class="p">,</span> <span class="mi">118</span><span class="p">,</span> <span class="mi">120</span><span class="p">]</span>
</code></pre></div></div>

<p>The performance gains of Denumerable cannot be understated. The above example takes 1/10000th of a second to run on my system. I wanted to provide the time it takes to run without <code class="language-plaintext highlighter-rouge">defer</code>, but after an hour of waiting and listening to it eat my hard drive for breakfast, I gave up.</p>]]></content><author><name>Thomas Sawyer</name></author><summary type="html"><![CDATA[Update, November 2026: Ruby 2.0 added Enumerable#lazy, which does what defer does here, and Facets has deprecated defer in its favor. Denumerable and Denumerator are still in Facets.]]></summary></entry><entry><title type="html">Indentured Stringitude</title><link href="https://rubyworks.github.io/facets/posts/2011-10-02-indentured-stringitude.html" rel="alternate" type="text/html" title="Indentured Stringitude" /><published>2011-10-02T00:00:00+00:00</published><updated>2011-10-02T00:00:00+00:00</updated><id>https://rubyworks.github.io/facets/posts/indentured-stringitude</id><content type="html" xml:base="https://rubyworks.github.io/facets/posts/2011-10-02-indentured-stringitude.html"><![CDATA[<blockquote>
  <p><strong>Update, November 2026:</strong> Ruby never got a <code class="language-plaintext highlighter-rouge">%L</code> literal, but Ruby 2.3’s squiggly heredoc, <code class="language-plaintext highlighter-rouge">&lt;&lt;~</code>, strips leading indentation, which takes care of the <code class="language-plaintext highlighter-rouge">help_text</code> case. In Facets 3.0, <code class="language-plaintext highlighter-rouge">margin</code> was renamed <code class="language-plaintext highlighter-rouge">trim</code>, and <code class="language-plaintext highlighter-rouge">margin(n)</code> took over from <code class="language-plaintext highlighter-rouge">tabto</code>.</p>
</blockquote>

<p>One of the great things about Ruby is the extensive collection of methods
available to the core classes. Of these the String class reigns supreme with
over 100 methods from which to make good use. Among these methods are those we
all use almost every time a string is laid to editor, such as #strip, #+ and #«.
Others are present that have more specific but important uses, such as #lines, #scan
and #getbyte. There are even a few that can leave one scratching ones head
a bit trying to fathom the usecase, such as #sum.</p>

<p>Yet, despite its wide address, there is a set of methods that have gone
completely overlooked, which is really remarkable when you consider their
purpose, the frequency of their utility and the code savings they provide
when used. These are methods dealing with <em>indentation</em>.</p>

<p>It was many years ago when I first was introduced to these three methods by
Gavin Sinclair: #tab, #tabto and #indent. Their interfaces are:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>tab(n)
Aligns each line n spaces.

tabto(n)
Preserves relative tabbing in which the first non-empty line ends up
with n spaces before non-space.

indent(n, c=' ')
Indent left or right by n spaces.
</code></pre></div></div>

<p>So clearly useful, these were some of the first to make their way in to Ruby
Facets, and they have proven invaluable to me in numerous projects ever since.</p>

<p>Sometime shortly there after, another related method also proved useful at
times, String#margin. It is documented:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>margin(n=0)
Provides a margin controlled string.

  x = %Q{
        |This
        |  is
        |    margin controlled!
        }.margin
</code></pre></div></div>

<p>This method is useful largely because it prevents a horrible code smell.
How often have you seen some jutting HERE doc that threw all that nicely
indented Ruby code to the wall.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    def help_text
      &lt;&lt;-HERE
Usage: foo bar
-x some option
-y another option
      HERE
    end
</code></pre></div></div>

<p>This all too common eye blight was the inspiration for the creation of #margin.
In fact, so confident were Peter and I in this approach to remove these ugly
code-squids that we conceived a %-literal to support such a construct would
be an unimpeachable addition to the language itself, allowing the even more
elegant notation:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>x = %L|Usage: foo bar
      |-x some option
      |-y another option
</code></pre></div></div>

<p>Such a syntax, being built into Ruby proper, would not suffer the computational
overhead of the pure Ruby implementation, or the extraneous brackets.</p>

<p>In all my years of coding Ruby, it seems to me, these are the clearest
omissions that I have repeatedly found need. And so concluded that they really
should be a part of Ruby proper. And as much as I owe Ruby’s String class for all
the time saving methods it provides, in this case, as often as I’ve had copy and
paste or add a dependency to ‘facets’ just to get these methods, I think the
String class owes me one!</p>

<!--
title      : String Indenture
author     : trans
categories : [string, ruby]
date       : 2011-10-02
layout     : post
-->]]></content><author><name>Thomas Sawyer</name></author><summary type="html"><![CDATA[Update, November 2026: Ruby never got a %L literal, but Ruby 2.3’s squiggly heredoc, &lt;&lt;~, strips leading indentation, which takes care of the help_text case. In Facets 3.0, margin was renamed trim, and margin(n) took over from tabto.]]></summary></entry></feed>