Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Ruby version of Javascript's with (See related posts)

A few different languages happily have a with block that basically calls unresolved methods on a particular object.

In Javascript, for example:
   1  
   2  with document
   3  {
   4      elt = getElementById( 'myElt' );
   5      appendChild( elt );
   6  }


Implementing a similar functionality in Ruby is stunningly simple:

   1  
   2  class Object
   3    def with_me( &block )
   4      instance_eval block
   5    end
   6  
   7    def with( object, &block )
   8      object.instance_eval &block
   9    end
  10  end


This gives us two syntaxes to work with. Assuming the same methods we saw above in Javascript are around in Ruby:
   1  
   2  with document do
   3      elt = getElementById( 'myElt' );
   4      appendChild( elt );
   5  end

or
   1  
   2  document.with_me do
   3      elt = getElementById( 'myElt' );
   4      appendChild( elt );
   5  end


The biggest issue with this is that it potentially breaks encapsulation, since calling private methods is perfectly possible in the block passed to #with or #with_me. Also significant, in Javascript the with block will call methods on the object if it can't resolve to local functions first; this code will do the opposite -- if it can't find the method in the object, it will try to find a function in the block's original enclosing scope.

You need to create an account or log in to post comments to this site.


Click here to browse all 5556 code snippets

Related Posts