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

<channel>
	<title>coderrr</title>
	<atom:link href="http://coderrr.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://coderrr.wordpress.com</link>
	<description>pronounced &#34;coder&#34; not &#34;code err&#34; (extended r optional)</description>
	<lastBuildDate>Fri, 06 Nov 2009 07:44:59 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain='coderrr.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://www.gravatar.com/blavatar/2bb7acc198eb108988c3a16e267634b6?s=96&#038;d=http://s.wordpress.com/i/buttonw-com.png</url>
		<title>coderrr</title>
		<link>http://coderrr.wordpress.com</link>
	</image>
			<item>
		<title>SOCKS 4 server with ProxyMachine</title>
		<link>http://coderrr.wordpress.com/2009/11/06/socks-4-server-with-proxymachine/</link>
		<comments>http://coderrr.wordpress.com/2009/11/06/socks-4-server-with-proxymachine/#comments</comments>
		<pubDate>Fri, 06 Nov 2009 04:15:32 +0000</pubDate>
		<dc:creator>coderrr</dc:creator>
				<category><![CDATA[network]]></category>
		<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://coderrr.wordpress.com/?p=793</guid>
		<description><![CDATA[I proxy almost all my web traffic through a SOCKS proxy.  After going through a bunch of different servers, each with its own issues, I decided to just write my own.  I ended up using ProxyMachine and it only took seven lines!

# socks4.rb
proxy do &#124;data&#124;
  next  if data.size &#60; 9
  [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=coderrr.wordpress.com&blog=1719123&post=793&subd=coderrr&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>I proxy almost all my web traffic through a <a href="http://en.wikipedia.org/wiki/SOCKS">SOCKS</a> proxy.  After going through a bunch of different servers, each with its own issues, I decided to just write my own.  I ended up using <a href="http://github.com/mojombo/proxymachine">ProxyMachine</a> and it only took seven lines!</p>
<pre class="brush: ruby;">
# socks4.rb
proxy do |data|
  next  if data.size &lt; 9
  v, c, port, o1, o2, o3, o4, user = data.unpack(&quot;CCnC4a*&quot;)
  return { :close =&gt; &quot;\x0\x5b\x0\x0\x0\x0\x0\x0&quot; }  if v != 4 or c != 1
  next  if ! idx = user.index(&quot;\x0&quot;)
  { :remote =&gt; &quot;#{[o1,o2,o3,o4]*'.'}:#{port}&quot;, :reply =&gt; &quot;\x0\x5a\x0\x0\x0\x0\x0\x0&quot;, :data =&gt; data[idx+9..-1] }
end
</pre>
<p>run it with:</p>
<pre class="brush: cpp;">
$ proxymachine -h 127.0.0.1 -p 1080 -c socks4.rb
</pre>
<p>* note this only actually covers half of the SOCKS4 protocol, but it&#8217;s the only half that pretty much anyone uses</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/coderrr.wordpress.com/793/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/coderrr.wordpress.com/793/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/coderrr.wordpress.com/793/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/coderrr.wordpress.com/793/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/coderrr.wordpress.com/793/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/coderrr.wordpress.com/793/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/coderrr.wordpress.com/793/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/coderrr.wordpress.com/793/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/coderrr.wordpress.com/793/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/coderrr.wordpress.com/793/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=coderrr.wordpress.com&blog=1719123&post=793&subd=coderrr&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://coderrr.wordpress.com/2009/11/06/socks-4-server-with-proxymachine/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/af4ce9309f8c4f7fc5cb33e7a5b08c64?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">coderrr</media:title>
		</media:content>
	</item>
		<item>
		<title>How to force Flash or any program to use a SOCKS proxy using Transocks and iptables in Linux</title>
		<link>http://coderrr.wordpress.com/2009/07/29/how-to-force-flash-or-any-program-to-use-a-socks-proxy-using-transocks-and-iptables-in-linux/</link>
		<comments>http://coderrr.wordpress.com/2009/07/29/how-to-force-flash-or-any-program-to-use-a-socks-proxy-using-transocks-and-iptables-in-linux/#comments</comments>
		<pubDate>Wed, 29 Jul 2009 17:18:29 +0000</pubDate>
		<dc:creator>coderrr</dc:creator>
				<category><![CDATA[linux]]></category>
		<category><![CDATA[network]]></category>

		<guid isPermaLink="false">http://coderrr.wordpress.com/?p=771</guid>
		<description><![CDATA[The Flash plugin for Linux does not respect any browser&#8217;s SOCKS proxy settings.  This means sites which stream video through a protocol other than HTTP will go direct to the host rather than through your SOCKS proxy.
One way to force Flash or any program through a SOCKS proxy is to use iptables in combination [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=coderrr.wordpress.com&blog=1719123&post=771&subd=coderrr&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>The Flash plugin for Linux does not respect any browser&#8217;s SOCKS proxy settings.  This means sites which stream video through a protocol other than HTTP will go direct to the host rather than through your SOCKS proxy.</p>
<p>One way to force Flash or any program through a SOCKS proxy is to use <code>iptables</code> in combination with <code>transocks</code>.</p>
<p>First download my transocks+dante tarball here: <a href="http://github.com/coderrr/transocks/tarball/master">http://github.com/coderrr/transocks/tarball/master</a></p>
<p>Unpack that, and then simply run <code>make</code>.  This will compile dante (which contains a SOCKS client library that transocks depends on), and then compile transocks with that library.</p>
<p>Now that transocks is ready, we need to setup rules for iptables which will redirect our traffic to be handled by transocks.  You can put the following rules in a sh script.</p>
<p>iptables_transocks.sh:</p>
<pre class="brush: bash;">
#!/bin/sh

LOCAL_NET=192.168.1.0/24

# Flush all previous nat rules, you might not want to include this line if you already have other rules setup
iptables -t nat --flush

iptables -t nat -X SOCKSIFY
iptables -t nat -N SOCKSIFY

# Exceptions for local traffic
iptables -t nat -A SOCKSIFY -o lo -j RETURN
iptables -t nat -A SOCKSIFY --dst 127.0.0.1 -j RETURN
iptables -t nat -A SOCKSIFY --dst $LOCAL_NET -j RETURN
# Add extra local nets here as necessary

# Only proxy traffic for programs run with group 'transocks'
iptables -t nat -A SOCKSIFY -m owner ! --gid-owner transocks -j RETURN

# Send to transocks
iptables -t nat -A SOCKSIFY -p tcp -j REDIRECT --to-port 1211

# Socksify traffic leaving this host:
iptables -t nat -A OUTPUT -p tcp --syn -j SOCKSIFY
</pre>
<p>Once you&#8217;ve created the script, run it:</p>
<pre class="brush: bash;">
chmod +x iptables_transocks.sh
sudo ./iptables_transocks.sh
</pre>
<p>Note, if you need to, you can clear out all these rules with:</p>
<pre class="brush: bash;">
sudo iptables -t nat --flush
</pre>
<p>The setup I have chosen here is to only proxy traffic for programs run with the group-id of group &#8216;transocks&#8217;.  This makes it easy to socksify any program by just running it as a specific group.  So the first thing we&#8217;ll want to do is create this group:</p>
<pre class="brush: bash;">
sudo addgroup transocks
sudo gpasswd transocks
# set an empty password
</pre>
<p>Next, start up transocks</p>
<pre class="brush: bash;">
# -f means run in foreground
./transocks -f
</pre>
<p>Now that we have created the group with an empty password and started transocks we are ready to socksify whatever program we want:</p>
<pre class="brush: bash;">
sg transocks 'firefox'
sg transocks 'opera'
sg transocks 'lynx http://whatismyip.com'
</pre>
<p><code>sg</code> (set group) will run the program with your current user but with the group you specify.  This is a semi-non-invasive way of notifying iptables you want it to proxy the traffic from this program.  Note that any files this program writes out will have the group of transocks.  In most cases this won&#8217;t matter but you should be aware of this.</p>
<p>Although <code>sg</code> will prompt you for a password (even though you set a blank password), if you create an application launcher through your windowing system it should launch without having to respond to or seeing a prompt.</p>
<p>Note, if your kernel supports it, you can tell iptables to only proxy traffic for programs with certain names by using the <code>-m owner --cmd-owner [cmd name]</code> option.  The other option is to use UIDs instead of GIDs (<code>-m owner --uid-owner</code>) to notify iptables which traffic to socksify.  This of course means you&#8217;ll have to run programs as a different user which will probably cause you more pain.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/coderrr.wordpress.com/771/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/coderrr.wordpress.com/771/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/coderrr.wordpress.com/771/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/coderrr.wordpress.com/771/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/coderrr.wordpress.com/771/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/coderrr.wordpress.com/771/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/coderrr.wordpress.com/771/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/coderrr.wordpress.com/771/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/coderrr.wordpress.com/771/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/coderrr.wordpress.com/771/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=coderrr.wordpress.com&blog=1719123&post=771&subd=coderrr&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://coderrr.wordpress.com/2009/07/29/how-to-force-flash-or-any-program-to-use-a-socks-proxy-using-transocks-and-iptables-in-linux/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/af4ce9309f8c4f7fc5cb33e7a5b08c64?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">coderrr</media:title>
		</media:content>
	</item>
		<item>
		<title>More Ordered Hashes for Ruby 1.8</title>
		<link>http://coderrr.wordpress.com/2009/07/25/more-ordered-hashes-for-ruby-1-8/</link>
		<comments>http://coderrr.wordpress.com/2009/07/25/more-ordered-hashes-for-ruby-1-8/#comments</comments>
		<pubDate>Sat, 25 Jul 2009 10:59:56 +0000</pubDate>
		<dc:creator>coderrr</dc:creator>
				<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://coderrr.wordpress.com/?p=763</guid>
		<description><![CDATA[Here&#8217;s one more ParseTree based technique for ordered hashes, it&#8217;ll be the last one, I promise.  This one doesn&#8217;t require any Ruby2Ruby string building/evaling craziness.  The syntax is the same as the previous ParseTree example:

hash = H{{ :key1 =&#62; value1, 'key2' =&#62; value2 }}

But with this implementation you can only use literals as [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=coderrr.wordpress.com&blog=1719123&post=763&subd=coderrr&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Here&#8217;s one more ParseTree based technique for ordered hashes, it&#8217;ll be the last one, I promise.  This one doesn&#8217;t require any Ruby2Ruby string building/evaling craziness.  The syntax is the same as the <a href="http://coderrr.wordpress.com/2009/07/25/ordered-hashes-for-ruby-1-8-using-parsetree/">previous ParseTree</a> example:</p>
<pre class="brush: ruby;">
hash = H{{ :key1 =&gt; value1, 'key2' =&gt; value2 }}
</pre>
<p>But with this implementation you can only use literals as keys, meaning strings, symbols, and numbers.</p>
<p>First we call the block with <code>yield</code> to get the original unordered hash.  Next we use ParseTree just to find the keys of the hash in order.  Since we only support literals we can use the value straight out of the s-expression, no conversion is needed.  And we don&#8217;t need to look at the keys&#8217; values in the s-expression since we already have them in the unordered hash.  Finally, we create a new ordered hash and set each key in order, grabbing the value from the original (unordered) hash.  This allows us to simplify the use of the s-expressions from ParseTree and not have to deal with code generation at all (Ruby2Ruby).  It also gives about a 4x speedup over the previous technique.</p>
<p>Here&#8217;s the code:</p>
<pre class="brush: ruby;">
class K;end
def H(&amp;b)
  K.send :define_method, :x, &amp;b
  sexp = ParseTree.translate(K, :x)
  hash_sexp = sexp[2][2]  # skip method definition stuff

  raise &quot;block doesn't contain hash!&quot;  if hash_sexp.first != :hash
  hash_sexp.slice! 0

  unordered_hash = yield

  oh = OrderedHash.new
  until hash_sexp.empty?
    (type, k), _ = hash_sexp.slice! 0, 2
    raise &quot;bad key type: #{type}&quot;  if ! [:lit, :str].include?(type)

    oh[k] = unordered_hash[k]
  end

  oh
end
</pre>
<p>This and alternative implementations are on my <a href="http://github.com/coderrr/ordered_hash_syntax">github</a>.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/coderrr.wordpress.com/763/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/coderrr.wordpress.com/763/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/coderrr.wordpress.com/763/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/coderrr.wordpress.com/763/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/coderrr.wordpress.com/763/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/coderrr.wordpress.com/763/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/coderrr.wordpress.com/763/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/coderrr.wordpress.com/763/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/coderrr.wordpress.com/763/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/coderrr.wordpress.com/763/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=coderrr.wordpress.com&blog=1719123&post=763&subd=coderrr&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://coderrr.wordpress.com/2009/07/25/more-ordered-hashes-for-ruby-1-8/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/af4ce9309f8c4f7fc5cb33e7a5b08c64?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">coderrr</media:title>
		</media:content>
	</item>
		<item>
		<title>Ordered Hashes for Ruby 1.8 using ParseTree</title>
		<link>http://coderrr.wordpress.com/2009/07/25/ordered-hashes-for-ruby-1-8-using-parsetree/</link>
		<comments>http://coderrr.wordpress.com/2009/07/25/ordered-hashes-for-ruby-1-8-using-parsetree/#comments</comments>
		<pubDate>Sat, 25 Jul 2009 04:28:02 +0000</pubDate>
		<dc:creator>coderrr</dc:creator>
				<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://coderrr.wordpress.com/?p=757</guid>
		<description><![CDATA[Update: Added another ParseTree based ordered hash technique here
Here&#8217;s another, less invasive (depending how you look at), way to get ordered hashes in ruby 1.8:

hash = H{{ :key =&#62; val, 'key' =&#62; val, 55 =&#62; val }}
method_needs_ordered_pairs {{ :key1 =&#62; :val1, :key2 =&#62; :val2 }}
method_needs_args_and_ordered_pairs arg1, arg2, H{{ :key1 =&#62; :val1, :key2 =&#62; :val2 }}

This [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=coderrr.wordpress.com&blog=1719123&post=757&subd=coderrr&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><b>Update:</b> Added another ParseTree based ordered hash technique <a href="http://coderrr.wordpress.com/2009/07/25/more-ordered-hashes-for-ruby-1-8/">here</a></p>
<p>Here&#8217;s another, less invasive (depending how you look at), way to get ordered hashes in ruby 1.8:</p>
<pre class="brush: ruby;">
hash = H{{ :key =&gt; val, 'key' =&gt; val, 55 =&gt; val }}
method_needs_ordered_pairs {{ :key1 =&gt; :val1, :key2 =&gt; :val2 }}
method_needs_args_and_ordered_pairs arg1, arg2, H{{ :key1 =&gt; :val1, :key2 =&gt; :val2 }}
</pre>
<p>This technique uses ParseTree and Ruby2Ruby.  The reason for the double curly braces ( {{}} ) is that we need a block for ParseTree to parse (ParseTree can&#8217;t just parse any argument unless we run it on the entire file).  The first set of braces is the block, the second is the actual hash.</p>
<p>After ParseTree breaks down the hash into an s-expression we use a slightly modified Ruby2Ruby to rebuild the hash representation using an OrderedHash class instead of Hash.  Once we have the new representation as a string we eval it in the binding of block so that any method calls or local variables inside the hash definition will work as expected.</p>
<pre class="brush: ruby;">
hash = H{{ :key =&gt; val, 'key' =&gt; val, 55 =&gt; val }}
# turns into
hash = OrderedHash.new.merge!(:key =&gt; val).merge!('key' =&gt; val).merge!(55 =&gt; val)
# note: this could be optimized to something like this
hash = (__tmp1 = OrderedHash.new;__tmp1[:key]=val;__tmp1['key']=val;__tmp1[55]=val;__tmp1)
</pre>
<p>The benefits of this approach over the previous are that it doesn&#8217;t require modifying any core classes and it will work with any type of object as a key.  Of course using ParseTree and Ruby2Ruby makes it much slower, about 300x.</p>
<p>Code is on github at <a href="http://github.com/coderrr/ordered_hash_syntax/tree/master">ordered_hash_syntax</a> repo: <a href="http://github.com/coderrr/ordered_hash_syntax/blob/master/parse_tree_oh.rb">implementation</a> and <a href="http://github.com/coderrr/ordered_hash_syntax/blob/master/parse_tree_oh_test.rb">test</a> with examples of usage.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/coderrr.wordpress.com/757/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/coderrr.wordpress.com/757/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/coderrr.wordpress.com/757/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/coderrr.wordpress.com/757/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/coderrr.wordpress.com/757/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/coderrr.wordpress.com/757/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/coderrr.wordpress.com/757/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/coderrr.wordpress.com/757/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/coderrr.wordpress.com/757/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/coderrr.wordpress.com/757/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=coderrr.wordpress.com&blog=1719123&post=757&subd=coderrr&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://coderrr.wordpress.com/2009/07/25/ordered-hashes-for-ruby-1-8-using-parsetree/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/af4ce9309f8c4f7fc5cb33e7a5b08c64?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">coderrr</media:title>
		</media:content>
	</item>
		<item>
		<title>Ordered Hashes for Ruby 1.8</title>
		<link>http://coderrr.wordpress.com/2009/07/20/ordered-hashes-for-ruby-1-8/</link>
		<comments>http://coderrr.wordpress.com/2009/07/20/ordered-hashes-for-ruby-1-8/#comments</comments>
		<pubDate>Mon, 20 Jul 2009 16:33:27 +0000</pubDate>
		<dc:creator>coderrr</dc:creator>
				<category><![CDATA[ruby]]></category>

		<guid isPermaLink="false">http://coderrr.wordpress.com/?p=754</guid>
		<description><![CDATA[For those of you who want a more declarative way to define ordered hashes in ruby 1.8 (perhaps for a DSL or something) here&#8217;s something I came up with:

class Object
  def &#62;&#62;(v)
    [self, v]
  end
end

def H(*pairs)
  pairs.inject(OrderedHash.new) {&#124;oh, (k, v)&#124; oh[k] = v; oh }
end

my_hash = H :some_key &#62;&#62; [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=coderrr.wordpress.com&blog=1719123&post=754&subd=coderrr&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>For those of you who want a more declarative way to define ordered hashes in ruby 1.8 (perhaps for a DSL or something) here&#8217;s something I came up with:</p>
<pre class="brush: ruby;">
class Object
  def &gt;&gt;(v)
    [self, v]
  end
end

def H(*pairs)
  pairs.inject(OrderedHash.new) {|oh, (k, v)| oh[k] = v; oh }
end

my_hash = H :some_key &gt;&gt; 'some value', 'nother key' &gt;&gt; another_value
</pre>
<p>Of course this won&#8217;t work for <code>Fixnum</code>s as keys.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/coderrr.wordpress.com/754/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/coderrr.wordpress.com/754/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/coderrr.wordpress.com/754/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/coderrr.wordpress.com/754/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/coderrr.wordpress.com/754/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/coderrr.wordpress.com/754/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/coderrr.wordpress.com/754/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/coderrr.wordpress.com/754/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/coderrr.wordpress.com/754/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/coderrr.wordpress.com/754/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=coderrr.wordpress.com&blog=1719123&post=754&subd=coderrr&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://coderrr.wordpress.com/2009/07/20/ordered-hashes-for-ruby-1-8/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/af4ce9309f8c4f7fc5cb33e7a5b08c64?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">coderrr</media:title>
		</media:content>
	</item>
		<item>
		<title>Firefox 3 internals, blocking alerts and XMLHttpRequests</title>
		<link>http://coderrr.wordpress.com/2009/06/22/firefox-3-internals-blocking-alerts-and-xmlhttprequests/</link>
		<comments>http://coderrr.wordpress.com/2009/06/22/firefox-3-internals-blocking-alerts-and-xmlhttprequests/#comments</comments>
		<pubDate>Mon, 22 Jun 2009 19:25:18 +0000</pubDate>
		<dc:creator>coderrr</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[firefox]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://coderrr.wordpress.com/?p=741</guid>
		<description><![CDATA[In my quest to find something which acts similar to an alert() box in Firefox 3 (for anti-anti-frame-busting), but without the annoying user-experience, I discovered a few things that I thought I should share.  Note this is all FF3 specific.
Why do alert() and other javascript dialogs block javascript execution and in particular javascript timers?
It [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=coderrr.wordpress.com&blog=1719123&post=741&subd=coderrr&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>In my quest to find something which acts similar to an <code>alert()</code> box in Firefox 3 (for <a href="http://coderrr.wordpress.com/2009/06/18/anti-anti-frame-busting/">anti-anti-frame-busting</a>), but without the annoying user-experience, I discovered a few things that I thought I should share.  Note this is all FF3 specific.</p>
<p><b>Why do alert() and other javascript dialogs block javascript execution and in particular javascript timers?</b><br />
It actually turns out that they do this implicitly, as a side effect of being modal dialogs.  Modal dialogs halt the execution of the thread they have been created from until the user closes the dialog.  Since all the javascript from a single page is run in a single thread the dialog effectively stops all of it.</p>
<p><a href="http://mxr.mozilla.org/firefox/source/embedding/components/windowwatcher/src/nsWindowWatcher.cpp#949">embedding/components/windowwatcher/src/nsWindowWatcher.cpp:949</a></p>
<pre class="brush: cpp;">
// alert() eventually calls this function
nsWindowWatcher::OpenWindowJSInternal(...)
/* ... */
    printf(&quot;About to show the dialog...\n&quot;);
    newChrome-&gt;ShowAsModal();
    printf(&quot;You won't see this until the user closes the dialog\n&quot;);
</pre>
<p><b>Why don&#8217;t synchronous XMLHttpRequests block javascript timers?</b><br />
Synchronous XHRs <b>do</b> block the execution of the javascript they were called from but not the execution of other javascript timers.  That&#8217;s a little unexpected given the nature of other synchronous things like the above modal dialog.  You would expect some code which blocks your javascript function to be blocking the actual thread its executing on.  But Firefox does something interesting while making the requesting.</p>
<p><a href="http://mxr.mozilla.org/firefox/source/content/base/src/nsXMLHttpRequest.cpp#1986">content/base/src/nsXMLHTTPRequest.cpp:1986</a></p>
<pre class="brush: cpp;">
 // If we're synchronous, spin an event loop here and wait
  if (!(mState &amp; XML_HTTP_REQUEST_ASYNC)) {
    nsIThread *thread = NS_GetCurrentThread();
    while (mState &amp; XML_HTTP_REQUEST_SYNCLOOPING) {
      if (!NS_ProcessNextEvent(thread)) {
        rv = NS_ERROR_UNEXPECTED;
        break;
      }
    }
  }
</pre>
<p>Internally Firefox processes the synchronous request asynchronously, in an event loop.  And one of the things that this event loop does is schedule timers for execution.</p>
<p>Even though this event loop is asynchronously processing the XHR request.  It is still synchronous in the sense that it will block normal execution of the thread until it returns.  This can produce some interesting effects.  Take this example which performs two overlapping synchronous XHRs:</p>
<pre class="brush: jscript;">
setInterval('document.body.innerHTML += &quot;.&quot;', 1000)

xhr = new XMLHttpRequest()
xhr.open(&quot;GET&quot;, &quot;http://request-which-takes-1-second.com/&quot;, false)

setTimeout(function() {
  xhr2 = new XMLHttpRequest()
  xhr2.open(&quot;GET&quot;, &quot;http://request-which-takes-10-seconds.com/&quot;, false)

  document.body.innerHTML += 'start2'
  xhr2.send(null)
  document.body.innerHTML += 'done2'
},500)

document.body.innerHTML += 'start1'
xhr.send(null)
document.body.innerHTML += 'done1'
</pre>
<p>In this example we queue the 2nd XHR to start about half a second after the first one starts.  Since the first one only takes a second we might expect to see the text <code>done1</code> before we see <code>done2</code>.  But since it was the event loop of the first XHR which actually initiated the 2nd XHR, the first XHR won&#8217;t return until the function which initiated the 2nd XHR returns.  We end up getting output like this:</p>
<pre class="brush: cpp;">
start1start2...............done2done1
</pre>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/coderrr.wordpress.com/741/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/coderrr.wordpress.com/741/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/coderrr.wordpress.com/741/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/coderrr.wordpress.com/741/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/coderrr.wordpress.com/741/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/coderrr.wordpress.com/741/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/coderrr.wordpress.com/741/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/coderrr.wordpress.com/741/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/coderrr.wordpress.com/741/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/coderrr.wordpress.com/741/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=coderrr.wordpress.com&blog=1719123&post=741&subd=coderrr&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://coderrr.wordpress.com/2009/06/22/firefox-3-internals-blocking-alerts-and-xmlhttprequests/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/af4ce9309f8c4f7fc5cb33e7a5b08c64?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">coderrr</media:title>
		</media:content>
	</item>
		<item>
		<title>anti anti Frame Busting</title>
		<link>http://coderrr.wordpress.com/2009/06/18/anti-anti-frame-busting/</link>
		<comments>http://coderrr.wordpress.com/2009/06/18/anti-anti-frame-busting/#comments</comments>
		<pubDate>Thu, 18 Jun 2009 16:21:58 +0000</pubDate>
		<dc:creator>coderrr</dc:creator>
				<category><![CDATA[javascript]]></category>
		<category><![CDATA[security]]></category>

		<guid isPermaLink="false">http://coderrr.wordpress.com/?p=718</guid>
		<description><![CDATA[In this post I presented a way to prevent a site you were (i)framing from frame busting out.  Jeff Atwood recently contacted me to see if I knew a way to get around the prevention (to prevent sites from framing stackoverflow.com), which of course I didn&#8217;t, but I told him I&#8217;d think about it [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=coderrr.wordpress.com&blog=1719123&post=718&subd=coderrr&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>In <a href="http://coderrr.wordpress.com/2009/02/13/preventing-frame-busting-and-click-jacking-ui-redressing/">this post</a> I presented a way to prevent a site you were (i)framing from frame busting out.  Jeff Atwood recently contacted me to see if I knew a way to get around the prevention (to prevent sites from framing <a href="http://stackoverflow.com">stackoverflow.com</a>), which of course I didn&#8217;t, but I told him I&#8217;d think about it and see if I could come up with something.  A week later I had come up with a few ideas but none actually worked.</p>
<p><b>See updates below for latest/best solution</b></p>
<p>But, due to some extra motivation from his <a href="http://www.codinghorror.com/blog/archives/001277.html">post today</a> (which links to my original post), I may have just come up with something.</p>
<pre class="brush: jscript;">
  if (top != self) {
    top.location.replace(document.location)
    alert('busting you out, please wait...')
  }
</pre>
<p>It&#8217;s so stupid simple, but it seems to actually work.  If you present an <code>alert()</code> box immediately after changing <code>top.location</code> you prevent the browser from running any more JS, either from your framed site or from the framing site.  But you <b>don&#8217;t</b> prevent the browser from loading the new page.  So as long as the alert box stays up for a few seconds until the browser has loaded enough of the new page to stop running scripts on the old page, then the anti frame busting code never runs and you successfully are busted out once the user clicks OK on the alert.</p>
<p>I&#8217;ve just done a preliminary test of this in FF3 and IE7 and it worked in both.  So I&#8217;m calling it, anti-anti-frame-busting is here!</p>
<p><b>Update:</b> <a href="http://coderrr.wordpress.com/2009/06/18/anti-anti-frame-busting/#comment-1648">Jason</a> brought up in a comment the issue of a user clicking OK before the page finished loading in which case the anti-frame-bust will still prevent you from busting.  One thing you can do to make sure that the page loads extremely quickly so that no user will be able to click OK before that is to (pre-)cache it.  Here&#8217;s an example:</p>
<pre class="brush: xml;">
&lt;!-- this is the page being framed --&gt;
  &lt;script&gt;
    function bust() {
      if (top != self) {
        // this page is now cached and will load immediately
        top.location.replace(&quot;http://page-with-expires-headers.com/&quot;)
        alert('busting you out, please wait...');
      }
    }
  &lt;/script&gt;
  &lt;!-- cache it! --&gt;
  &lt;iframe onload=&quot;bust()&quot; src=&quot;http://page-with-expires-headers.com/&quot;&gt;&lt;/iframe&gt;
</pre>
<p>You should have these headers on the page to bust out with.</p>
<pre class="brush: cpp;">
      Expires: Sun, 19 Aug 2012 14:10:44 GMT    &lt;-- far enough in the future
      Last-modified: Fri, 19 Jun 2009 04:24:20 GMT    &lt;-- now
</pre>
<p>First the framed page will do the initial load of the cached page in an iframe (which you can make hidden).  Now that page will be cached and the next time you visit it the browser should make no network requests, loading the page completely from its local cache.</p>
<p>For this technique to work you&#8217;ll probly want to use it with a blank page which contains only a javascript/meta redirect to the actual page that was being framed.  For example:</p>
<pre class="brush: xml;">
&lt;html&gt;&lt;body&gt;
  redirecting...
  &lt;script&gt; if (self == top) top.location='http://site-to-redirect-to.com/'; &lt;/script&gt;
&lt;/body&gt;&lt;/html&gt;
</pre>
<p><b>Update:</b> On IE7 this caching technique alone is good enough to prevent anti-frame-busting.  Meaning no <code>alert()</code> is required after the <code>top.location</code> change.  At least this is true for a simple page which only consists of a javascript redirect:</p>
<pre class="brush: xml;">
&lt;html&gt;
  &lt;body&gt;
    we've busted out!  redirecting...
    &lt;script&gt;
      // only redirect if we're busted out
      if (top == self)  top.location = &quot;http://original-page.com&quot;;
    &lt;/script&gt;
  &lt;/body&gt;
&lt;/html&gt;
</pre>
<p><b>Update:</b> The holy grail of anti-anti-frame-busting:  This code, along with the caching technique described above, works in both FF3 and IE7 and has no negative user-experience (ie. alert boxes or frozen browsers):</p>
<pre class="brush: xml;">
  &lt;script&gt;
    function bust() {
      if (top != self)
        setInterval(&quot;top.location.replace('http://cached-bust-out-page.com/with/redirect')&quot;,1);
     }
  &lt;/script&gt;
  &lt;!-- cache it! --&gt;
  &lt;iframe onload=&quot;bust()&quot; src=&quot;http://cached-bust-out-page.com/with/redirect&quot;&gt;&lt;/iframe&gt;
</pre>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/coderrr.wordpress.com/718/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/coderrr.wordpress.com/718/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/coderrr.wordpress.com/718/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/coderrr.wordpress.com/718/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/coderrr.wordpress.com/718/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/coderrr.wordpress.com/718/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/coderrr.wordpress.com/718/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/coderrr.wordpress.com/718/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/coderrr.wordpress.com/718/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/coderrr.wordpress.com/718/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=coderrr.wordpress.com&blog=1719123&post=718&subd=coderrr&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://coderrr.wordpress.com/2009/06/18/anti-anti-frame-busting/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/af4ce9309f8c4f7fc5cb33e7a5b08c64?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">coderrr</media:title>
		</media:content>
	</item>
		<item>
		<title>Fixing constant lookup in DSLs in Ruby 1.9</title>
		<link>http://coderrr.wordpress.com/2009/06/02/fixing-constant-lookup-in-dsls-in-ruby-1-9/</link>
		<comments>http://coderrr.wordpress.com/2009/06/02/fixing-constant-lookup-in-dsls-in-ruby-1-9/#comments</comments>
		<pubDate>Tue, 02 Jun 2009 20:15:54 +0000</pubDate>
		<dc:creator>coderrr</dc:creator>
				<category><![CDATA[ruby]]></category>
		<category><![CDATA[ruby19]]></category>

		<guid isPermaLink="false">http://coderrr.wordpress.com/?p=708</guid>
		<description><![CDATA[Ruby 1.9 puts an extra hurdle in DSL development.  Consider this simple DSL example which runs fine in 1.8:

class ProxyObject
  def initialize
    @o = Array.new
  end

  def method_missing(m, *a, &#38;b)
    @o.send m, *a, &#38;b
  end
end

def dsl(&#38;b)
  ProxyObject.new.instance_eval &#38;b
end

module A
  class B; end

 [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=coderrr.wordpress.com&blog=1719123&post=708&subd=coderrr&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Ruby 1.9 puts an extra hurdle in DSL development.  Consider this simple DSL example which runs fine in 1.8:</p>
<pre class="brush: ruby;">
class ProxyObject
  def initialize
    @o = Array.new
  end

  def method_missing(m, *a, &amp;b)
    @o.send m, *a, &amp;b
  end
end

def dsl(&amp;b)
  ProxyObject.new.instance_eval &amp;b
end

module A
  class B; end

  dsl do
    p Module.nesting # =&gt; [A]
    push B
    p pop # =&gt; A::B
  end
end
</pre>
<p>This DSL simply proxies to an Array object.  In ruby 1.8 everything will work, in specific, resolving the constant B, which resolves to the class A::B.  This constant resolution works because we are in the lexical scope of class A, as we can see by the module nesting.  (For more info on <a href="http://coderrr.wordpress.com/2008/03/11/constant-name-resolution-in-ruby/">module nesting</a> see this post)</p>
<p>Now run the code in ruby 1.9:</p>
<pre class="brush: ruby;">
module A
  class B; end

  dsl do
    p Module.nesting # =&gt; [#&lt;Class:#&lt;ProxyObject:0x97beab8&gt;&gt;]
    push B  # =&gt; uninitialized constant ProxyObject::B
    p pop
  end
end
</pre>
<p>Now things break.  Our module nesting no longer contains A because instance_eval has changed the nesting to the metaclass of our ProxyObject instance, which doesn&#8217;t help us at all.  But wait&#8230; <a href="http://coderrr.wordpress.com/2009/05/18/dynamically-adding-a-constant-nesting-in-ruby-1-9/">my last blog post</a> to the rescue!  In ruby 1.9 we can dynamically add modules to our lexical scope.  So all we need to do is find the original module nesting of the block, then add those modules to our nesting, and then eval the block as we normally would:</p>
<pre class="brush: ruby;">
def dsl(&amp;b)
  modules = b.binding.eval &quot;Module.nesting&quot;
  Kernel.with_module(*modules) do
    ProxyObject.new.instance_eval &amp;b
  end
end

module A
  class B; end

  dsl do
    p Module.nesting  # =&gt; [#&lt;Class:#&lt;ProxyObject:0x8d6d190&gt;&gt;, #&lt;Class:A&gt;, A, Kernel]
    push B
    p pop  # =&gt; A::B
  end
end
</pre>
<p>Please let me know if you see any issues with this approach or have other ideas.</p>
<p>Credit goes to <a href="http://blog.methodmissing.com/">Lourens</a> for mentioning this problem with 1.9 to me.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/coderrr.wordpress.com/708/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/coderrr.wordpress.com/708/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/coderrr.wordpress.com/708/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/coderrr.wordpress.com/708/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/coderrr.wordpress.com/708/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/coderrr.wordpress.com/708/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/coderrr.wordpress.com/708/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/coderrr.wordpress.com/708/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/coderrr.wordpress.com/708/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/coderrr.wordpress.com/708/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=coderrr.wordpress.com&blog=1719123&post=708&subd=coderrr&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://coderrr.wordpress.com/2009/06/02/fixing-constant-lookup-in-dsls-in-ruby-1-9/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/af4ce9309f8c4f7fc5cb33e7a5b08c64?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">coderrr</media:title>
		</media:content>
	</item>
		<item>
		<title>Dynamically adding a constant nesting in Ruby 1.9</title>
		<link>http://coderrr.wordpress.com/2009/05/18/dynamically-adding-a-constant-nesting-in-ruby-1-9/</link>
		<comments>http://coderrr.wordpress.com/2009/05/18/dynamically-adding-a-constant-nesting-in-ruby-1-9/#comments</comments>
		<pubDate>Mon, 18 May 2009 23:37:03 +0000</pubDate>
		<dc:creator>coderrr</dc:creator>
				<category><![CDATA[ruby]]></category>
		<category><![CDATA[ruby19]]></category>

		<guid isPermaLink="false">http://coderrr.wordpress.com/?p=695</guid>
		<description><![CDATA[Wanting to see if it would be possible to somehow dynamically modify Module.nesting I hacked around looking for ways to do this for a long time in 1.8 to no avail.  But it seems that it&#8217;s somewhat trivial in 1.9.

module Kernel
  def with_module(*consts, &#38;blk)
    slf = blk.binding.eval('self')

    [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=coderrr.wordpress.com&blog=1719123&post=695&subd=coderrr&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Wanting to see if it would be possible to somehow dynamically modify <a href="http://coderrr.wordpress.com/2008/03/11/constant-name-resolution-in-ruby/">Module.nesting</a> I hacked around looking for ways to do this for a long time in 1.8 to no avail.  But it seems that it&#8217;s somewhat trivial in 1.9.</p>
<pre class="brush: ruby;">
module Kernel
  def with_module(*consts, &amp;blk)
    slf = blk.binding.eval('self')

    l = lambda { slf.instance_eval(&amp;blk) }
    consts.reverse.inject(l) {|l, k| lambda { k.class_eval(&amp;l) } }.call
  end
end
</pre>
<p>Allows you to do:</p>
<pre class="brush: ruby;">
module X
  module Y
    module Z
    end
  end

  module Y2
    class Z2
    end
  end
end

x, @x = 5, 6
with_module(X) do
  p Y, Y2 # =&gt; X::Y, X::Y2
  with_module(Y, Y2) do
    p Z, Z2  # =&gt; X::Y::Z, X::Y2::Z2
    p x, @x  # =&gt; 5, 6
  end
end
</pre>
<p>Without losing the scope of your blocks.</p>
<p>Now should you ever do this?  Probably not.  It&#8217;s usually better to actually nest inside the modules you want to be in the lexical scope of.  Or another technique, used sometimes testing situations, is to shorten a long constant name with an abbreviation constant like:</p>
<pre class="brush: ruby;">
XYZ10 = X::Y::Z::Ten
...
XYZ10.new
</pre>
<p>Please let me know if you think of a use case which one might consider &#8220;valid&#8221; or useful for with_module.</p>
<p>One interesting aspect of figuring out how to make this method work was discovering some special properties of the *eval() methods.</p>
<p>The following will not work:</p>
<pre class="brush: ruby;">
class X
  class Y
  end
end
l = lambda { p Y }
X.class_eval { l.call }  #  uninitialized constant Y (NameError)
</pre>
<p>But this will</p>
<pre class="brush: ruby;">
l = lambda { p Y }
X.class_eval(&amp;l)  # =&gt; X::Y
</pre>
<p>And so will this</p>
<pre class="brush: ruby;">
l = lambda { p Y }
s = self
X.class_eval { s.instance_eval(&amp;l) }  # =&gt; X::Y
</pre>
<p>When you eval a block directly rather than calling call on it, it will use the lexical scope of the calling scope rather than its own lexical scope at the time the block was created.</p>
<pre class="brush: ruby;">
module G
  class N; end
  $l = lambda { p N }
end
# using the lexical scope of the lambda when it was created
$l.call  # =&gt; G::N
# using the current lexical scope + X
X.class_eval &amp;$l  # uninitialized constant X::N
</pre>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/coderrr.wordpress.com/695/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/coderrr.wordpress.com/695/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/coderrr.wordpress.com/695/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/coderrr.wordpress.com/695/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/coderrr.wordpress.com/695/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/coderrr.wordpress.com/695/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/coderrr.wordpress.com/695/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/coderrr.wordpress.com/695/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/coderrr.wordpress.com/695/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/coderrr.wordpress.com/695/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=coderrr.wordpress.com&blog=1719123&post=695&subd=coderrr&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://coderrr.wordpress.com/2009/05/18/dynamically-adding-a-constant-nesting-in-ruby-1-9/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/af4ce9309f8c4f7fc5cb33e7a5b08c64?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">coderrr</media:title>
		</media:content>
	</item>
		<item>
		<title>ActiveRecord&#8217;s with_connection is now useful!</title>
		<link>http://coderrr.wordpress.com/2009/05/05/activerecords-with_connection-is-now-useful/</link>
		<comments>http://coderrr.wordpress.com/2009/05/05/activerecords-with_connection-is-now-useful/#comments</comments>
		<pubDate>Tue, 05 May 2009 22:27:13 +0000</pubDate>
		<dc:creator>coderrr</dc:creator>
				<category><![CDATA[concurrency]]></category>
		<category><![CDATA[patch]]></category>
		<category><![CDATA[rails]]></category>

		<guid isPermaLink="false">http://coderrr.wordpress.com/?p=685</guid>
		<description><![CDATA[A few days ago my with_connection (originally cleanup_connection) patch finally went in to rails trunk.  It changes the way with_connection works a little bit, but should be mostly backwards compatible.
Note, you&#8217;re probably only going to care about this if you use ActiveRecord in long running threads.
Before this patch, with_connection was useless for most Rails [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=coderrr.wordpress.com&blog=1719123&post=685&subd=coderrr&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>A few days ago my with_connection (originally cleanup_connection) <a href="https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/1752">patch</a> finally <a href="http://github.com/rails/rails/commit/5501b99a19a2a67a9a920fd3c7bff071a2ecf058">went in</a> to rails trunk.  It changes the way with_connection works a little bit, but should be mostly backwards compatible.</p>
<p>Note, you&#8217;re probably only going to care about this if you use ActiveRecord in long running threads.</p>
<p>Before this patch, with_connection was useless for most Rails devs&#8217; situations unless we wanted to execute raw SQL:</p>
<pre class="brush: ruby;">
ActiveRecord::Base.connection_pool.with_connection do |conn|
  User.find(1)  # this will NOT use the connection passed to the block (up to Rails 2.3.x), it
                    # will create a new one, or use the one that existed before we called with_connection
  conn.execute(&quot;select raw sql here&quot;)  # this is the only way to use the connection
end
</pre>
<p>So that kinda sucked.  Because the idea of with_connection is exactly what you want when you have lots of long running threads.  You want to check out a connection, use ActiveRecord as you normally would (and have it use that new connection), and then check it back in whenever you&#8217;re done instead of leaving it lying around.  This way you could have hundreds of threads using ActiveRecord sporadically with a small sized connection pool.</p>
<p>That&#8217;s what this patch allows you to do.  Now with_connection will checkout a connection and set it as the main connection for the current thread (if it doesn&#8217;t already exist).  If a connection already exists it will do nothing.  This has the nice effect of allowing you to wrap your ActiveRecord code as closely as possible with with_connection.  If with_connection always checked out a new connection no matter what, then you&#8217;d want to wrap your code at as high a level as possible which in turn would mean you would be keeping connections checked out of the pool when you didn&#8217;t really need them.</p>
<p>Here&#8217;s a (very contrived) example:</p>
<pre class="brush: ruby;">
# shorthand
def db(&amp;b); ActiveRecord::Base.connection_pool.with_connection(&amp;b); end

class User
  def update_score
    db do
      self.score = calculate_score
      save!
    end
  end

  def calcuate_score
    db { self.score_cards.sum(&amp;:points) }
  end
end

100.times { User.all.each {|u| Thread.new { u.update_score } } }
</pre>
<p>In this example we could call calculate_score directly, or indirectly through update_score, and we would never checkout more than one connection from the pool.  We could also feel free to call these methods from any number of threads and know that when the calls finish their connections will be checked back into the pool without having to deal with any special ActiveRecord cleanup methods.</p>
<p>If this is the type of thing you are doing or want to be doing but you don&#8217;t want to actually to have wrap all your code in those annoying blocks, you can check out this <a href="http://github.com/coderrr/cleanup_connection/blob/master/cleanup_connection_patch.rb">monkeypatch</a> (<a href="http://coderrr.wordpress.com/2009/01/16/monkey-patching-activerecord-to-automatically-release-connections/">blog post here</a>)  which essentially wraps all DB touching ActiveRecord methods with with_connection for you.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/coderrr.wordpress.com/685/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/coderrr.wordpress.com/685/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/coderrr.wordpress.com/685/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/coderrr.wordpress.com/685/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/coderrr.wordpress.com/685/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/coderrr.wordpress.com/685/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/coderrr.wordpress.com/685/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/coderrr.wordpress.com/685/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/coderrr.wordpress.com/685/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/coderrr.wordpress.com/685/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=coderrr.wordpress.com&blog=1719123&post=685&subd=coderrr&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://coderrr.wordpress.com/2009/05/05/activerecords-with_connection-is-now-useful/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/af4ce9309f8c4f7fc5cb33e7a5b08c64?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">coderrr</media:title>
		</media:content>
	</item>
	</channel>
</rss>