<?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/"
	>

<channel>
	<title>Involution &#187; Ruby</title>
	<atom:link href="http://involution.com/category/ruby/feed/" rel="self" type="application/rss+xml" />
	<link>http://involution.com</link>
	<description>Tony Perrie&#039;s Weblog</description>
	<lastBuildDate>Tue, 15 May 2012 20:48:21 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Interactive Memcached Debugging with Rails</title>
		<link>http://involution.com/2009/06/20/interactive-memcached-debugging-with-rails/</link>
		<comments>http://involution.com/2009/06/20/interactive-memcached-debugging-with-rails/#comments</comments>
		<pubDate>Sat, 20 Jun 2009 23:17:37 +0000</pubDate>
		<dc:creator>Tony Perrie</dc:creator>
				<category><![CDATA[Memcached]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://involution.com/?p=1238</guid>
		<description><![CDATA[The memcached support in Rails is great, but it&#8217;s a bit difficult to see what the heck is going on in a production environment. The first problem is, by default Rails doesn&#8217;t keep a list of all memcached keys that are available on the system. So, you have to use a plugin like memcache_store_with_delete_matched to [...]]]></description>
			<content:encoded><![CDATA[<p>The memcached support in Rails is great, but it&#8217;s a bit difficult to see what the heck is going on in a production environment.  The first problem is, by default Rails doesn&#8217;t keep a list of all memcached keys that are available on the system.  So, you have to use a plugin like <a href="http://github.com/lacomartincik/memcache_store_with_delete_matched/tree/master">memcache_store_with_delete_matched</a> to have memcache itself store a list of all available keys.  </p>
<p>You can install this plugin with the typical <code>script/plugin</code> command. </p>
<pre><code>script/plugin install git://github.com/lacomartincik/memcache-store-with-delete_matched.git
</code></pre>
<p>Then, you configure memcached in your <code>environment.rb</code> like this. </p>
<pre><code>mem_cache_options = {
    :c_threshold => 10000,
    :compression => true,
    :debug => false,
    :timeout => false,
    :namespace => 'app',
    :readonly => false,
    :urlencode => false
  }
  config.action_controller.cache_store = <b>:mem_cache_store_with_delete_matched</b>, ['127.0.0.1:11211'], mem_cache_options
</code></pre>
<p>The other benefit to using memcache_store_with_delete_matched is that regular expressions within <code>expire_fragment</code> works. </p>
<pre><code>expire_fragment(%r!/index_user_.*!)
</code></pre>
<p>So, down to debugging.  If you want to see all keys in a <code>script/console</code>, you can do the following. </p>
<pre><code>YAML.load(ActionController::Base.cache_store.fetch("memcached_store_key_list"))
</code></pre>
<p>You can select certain keys from the memcached_store_keylist. </p>
<pre><code>YAML.load(ActionController::Base.cache_store.fetch("memcached_store_key_list")) .detect{ |k| k.match(/index/) }
</code></pre>
<p>Once you have the list of keys, you can plug them into a fetch command. </p>
<pre><code>ActionController::Base.cache_store.fetch("app/blog/index")
</code></pre>
<p>You can also manually expire keys from a console. </p>
<pre><code>c = ApplicationController.new
c.expire_fragment(/index/)
</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://involution.com/2009/06/20/interactive-memcached-debugging-with-rails/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using Phusion Passenger with HAProxy</title>
		<link>http://involution.com/2009/02/25/using-phusion-passenger-with-haproxy/</link>
		<comments>http://involution.com/2009/02/25/using-phusion-passenger-with-haproxy/#comments</comments>
		<pubDate>Wed, 25 Feb 2009 21:14:33 +0000</pubDate>
		<dc:creator>Tony Perrie</dc:creator>
				<category><![CDATA[HAProxy]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://involution.com/?p=1196</guid>
		<description><![CDATA[Today I decided to turn on HAProxy to load-balance between Apache instances running Phusion Passenger on two separate machines. The results are clear. Doing this nearly doubled our ApacheBench throughput scores. This config was adaped from the 37Signals blog post here. # /etc/haproxy/haproxy.cfg global maxconn 4096 defaults mode http retries 3 option redispatch maxconn 2000 [...]]]></description>
			<content:encoded><![CDATA[<p>Today I decided to turn on HAProxy to load-balance between Apache instances running Phusion Passenger on two separate machines.  The results are clear.  Doing this nearly doubled our ApacheBench throughput scores.</p>
<p>This config was adaped from the 37Signals blog post <a href="http://www.37signals.com/svn/posts/1073-nuts-bolts-haproxy">here</a>.</p>
<pre># /etc/haproxy/haproxy.cfg
global
        maxconn 4096

defaults
        mode    http
        retries 3
        option redispatch
        maxconn 2000
        contimeout	5000
        clitimeout	50000
        srvtimeout	50000

listen web1 XXX.XXX.XXX.210:80
       mode http
       balance roundrobin
       server web1 XXX.XXX.XXX.210:8080
       server web2 XXX.XXX.XXX.211:8080
</pre>
<p>Passenger is configured the normal way. </p>
<pre><code>&lt;VirtualHost *:8080&gt;
        ServerName www.example.com
        DocumentRoot /var/www/rails_project/current/public
&lt;/VirtualHost&gt;
</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://involution.com/2009/02/25/using-phusion-passenger-with-haproxy/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Chaining Named Scopes</title>
		<link>http://involution.com/2008/11/10/chaining-named-scopes/</link>
		<comments>http://involution.com/2008/11/10/chaining-named-scopes/#comments</comments>
		<pubDate>Tue, 11 Nov 2008 03:22:44 +0000</pubDate>
		<dc:creator>Tony Perrie</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://involution.com/?p=1189</guid>
		<description><![CDATA[There aren&#8217;t many examples of how to combine named_scopes programmatically on the ol&#8217; Blogosphere these days. All I could find were a few scant references to using anonymous scopes like this. It took me quite a while to figure this out which is surprising since this use case seems like such a common thing to [...]]]></description>
			<content:encoded><![CDATA[<p>There aren&#8217;t many examples of how to combine named_scopes programmatically on the ol&#8217; Blogosphere these days.  All I could find were a few scant references to using anonymous scopes like this.  It took me quite a while to figure this out which is surprising since this use case seems like such a common thing to do.</p>
<p>If you want to stack conditions on a search form with will_paginate on top of that, this seems to be the spice.</p>
<pre><code>class Shape < ActiveRecord::Base
    named_scope :created_after, lambda { |m| {:conditions => ["created_at > ?", m]} }
    named_scope :with_color, lambda { |color| {:conditions => {:color => color}} }
end

class ShapesController < ApplicationController
  def index
    scope =  Shape.scoped({})
    scope = scope.created_after(params[:months_ago].to_i.months.ago) if params[:months_ago]
    scope = scope.with_color(params[:color]) if params[:color]
    @shapes = scope.paginate(paginate_options({:order => 'id DESC', :page => 1}))
  end
end</code></pre>
<p>I started to use <code>eval</code> to do this, but Ken Turner set me straight today.  I view <code>eval</code> as more of a last resort when all else fails.  In this case, it&#8217;s possible to tap these filters in using a rubber mallet.  No sense in busting out the sledgehammer for this one.</p>
]]></content:encoded>
			<wfw:commentRss>http://involution.com/2008/11/10/chaining-named-scopes/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Monkeypatching For Robots</title>
		<link>http://involution.com/2008/07/16/monkey-patching-for-robots/</link>
		<comments>http://involution.com/2008/07/16/monkey-patching-for-robots/#comments</comments>
		<pubDate>Wed, 16 Jul 2008 11:27:38 +0000</pubDate>
		<dc:creator>Tony Perrie</dc:creator>
				<category><![CDATA[Photos]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://involution.com/?p=1104</guid>
		<description><![CDATA[Even though Jeff Atwood believes that monkeypatching will lead to the apocalypse, I&#8217;ve discovered three cases where it has proven to be most useful. Case 1: Dynamically Patching a Plug-in Let&#8217;s face it. The Ruby on Rails wiki is littered with a cadre of unmaintained plugins. One example is file_column. Attachment_fu pretty much replaces this, [...]]]></description>
			<content:encoded><![CDATA[<p>Even though Jeff Atwood <a href="http://www.codinghorror.com/blog/archives/001151.html">believes</a> that monkeypatching will lead to the apocalypse, I&#8217;ve discovered three cases where it has proven to be most useful.  </p>
<p><b>Case 1: Dynamically Patching a Plug-in</b></p>
<p>Let&#8217;s face it.  The Ruby on Rails wiki is littered with a cadre of unmaintained plugins.  One example is file_column.  Attachment_fu pretty much replaces this, but for whatever reason, the project that I&#8217;m working on is using the old warhorse of file upload packages.  Recently, I&#8217;ve noticed several problems with file_column.  The biggest issue is that it was written pre-Leopard  So, file_column doesn&#8217;t support the new way of calling OS X&#8217;s file command.  Combining monkeypatching with the Rails alias_method_chain allows us to patch the underlying code with minimal effort.  And, keeping the dynamic patch separate, means that updating the plugin will not overwrite the patch.</p>
<pre><code># Rails lib/project_system.rb
module FileColumn
  def get_content_type_with_leopard_rules(fallback=nil)
    if not RUBY_PLATFORM.eql?('universal-darwin9.0')
      return get_content_type_for_leopard_without_apple_rules
    end
    if options[:file_exec]
      begin
        content_type = `#{@options[:file_exec]} -bI "#{@local_file_path}"`.chomp
        content_type = fallback unless $?.success?
        content_type.gsub!(/;.+$/,"") if content_type
        content_type
      rescue
        fallback
      end
    else
      fallback
    end
  end
  alias_method_chain :get_content_type, :leopard_rules
end
</code></pre>
<p><br/><br />
<b>Case 2: Adding a Feature to a Plug-in</b></p>
<p>I&#8217;m a total Unix snob.  Upper-case filenames injure what&#8217;s left of my dwindling sanity.  File_column recklessly allows the user&#8217;s filenames to be saved directly to the filesystem.  This has the side-effect of dumping a flagon full of mime-type detection FAIL when you view the files that have been uploaded to the server.  Think of users uploading images named <code>me.jpeg</code>, <code>me.JPG</code> and <code>me.Jpeg</code>.  Inconsistent capitalization is clearly evil and has to be sanitized before it gets to our precious disks.  Using a monkeypatch with alias_method_chain, you can override file_column&#8217;s sanitize_filename method to convert the filename to lowercase.</p>
<pre><code># Rails lib/project_system.rb
module FileColumn
  class << self
    def sanitize_filename_with_downcase_rules(filename)
      self.sanitize_filename_without_downcase_rules(filename).downcase.gsub(/\.jpeg$/,'jpg')
    end
    alias_method_chain :sanitize_filename, :downcase_rules
  end
end
</code></pre>
<p><br/><br />
<b>Case 3: Overriding a Native Ruby Class to Facilitate Symbol#to_proc Abuses</b></p>
<p>Ever since reading <a href="http://weblog.raganwald.com">Reg Braithwaite</a>'s <a href="http://weblog.raganwald.com/2008/02/1100inject.html">(1..100).inject(&#038;:+)</a> post, I've been mystified and rather infatuated with Rails' <code>Symbol#to_proc</code> method (which, incidentally, was only possible through Rails' monkeypatch to the Ruby Symbol class).</p>
<p>Recently, I wrote a method to detect whether any one checkbox or radio button had been selected on a HTML form.  This would serve as a form validation, but was complicated due to the fact that radio button values are arbitrary strings and checkbox values are posted as "0" and "1".  The radio button values had to be converted to boolean by the controller, but ActiveRecord's value_to_boolean method does not support this.  Monkeypatching came to the rescue yet again and allowed me to override Object in an inject-friendly way. </p>
<pre><code># Rails lib/project_system.rb
class Object
  def selected?
    return true if self and self.is_a?(String) and self.include?('location')
    ActiveRecord::ConnectionAdapters::Column.value_to_boolean(self)
  end
end
</code></pre>
<p>Rather than writing a massive case statement or nested if/elsifs, we can just write the following in a model.</p>
<p><code>
<pre># Rails app/models/model_name.rb
def selected_place?
  places.collect(&#038;:selected?).inject(&#038;:|)
  # Logically, the same as places.collect(&#038;:selected?).any?
end
</code></pre>
<p>The preceding loop calls our new Object selected? method on each of the location_types column, and the inject ORs all the data together.</p>
<p><img src="/images/robotmonkey.jpg" /></p>
<p>I don't really understand why Jeff is writing these slime pieces on monkeypatching.  Jeff's logic is equivalent to reasoning that driving should be outlawed because cars are dangerous.  However, just because a few people drive drunk doesn't mean that no one should drive!  Oddly, I would get behind a law to make drunken monkeypatching a felony. </p>
]]></content:encoded>
			<wfw:commentRss>http://involution.com/2008/07/16/monkey-patching-for-robots/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Malfeasance in 64-bit PowerPC MySQL Gem Compilation</title>
		<link>http://involution.com/2008/05/12/malfeasance-in-64-bit-powerpc-mysql-gem-compilation/</link>
		<comments>http://involution.com/2008/05/12/malfeasance-in-64-bit-powerpc-mysql-gem-compilation/#comments</comments>
		<pubDate>Tue, 13 May 2008 01:25:12 +0000</pubDate>
		<dc:creator>Tony Perrie</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://involution.com/?p=1102</guid>
		<description><![CDATA[For the three people in the world building the Rails mysql gem on a PowerPC G5-based OS X Server with the 64-bit MySQL installed getting this crazy error: lazy symbol binding failed: Symbol not found: _mysql_init The magic ninja gem install command that will cure all your ills goes a little something like this: sudo [...]]]></description>
			<content:encoded><![CDATA[<p>For the three people in the world building the Rails <code>mysql</code> gem on a PowerPC G5-based OS X Server with the 64-bit MySQL installed getting this crazy error:</p>
<pre>
lazy symbol binding failed: Symbol not found: _mysql_init
</pre>
<p>The magic ninja gem install command that will cure all your ills goes a little something like this:</p>
<pre>
sudo env ARCHFLAGS="-arch ppc64" gem install -V mysql -- --with-mysql-include=/usr/local/mysql/include/ --with-mysql-lib=/usr/local/mysql/lib --with-mysql-config=/usr/local/mysql/bin/mysql_config --with-mysql-dir=/usr/local/mysql
</pre>
<p>Pretty obvious when you think about it.  Not sure why it took me a little over an hour to discover the crucial lynchpin for correcting this system-wide thought-tastrophy.</p>
]]></content:encoded>
			<wfw:commentRss>http://involution.com/2008/05/12/malfeasance-in-64-bit-powerpc-mysql-gem-compilation/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>CSS Templating with Sass</title>
		<link>http://involution.com/2007/07/09/css-templating-with-sass/</link>
		<comments>http://involution.com/2007/07/09/css-templating-with-sass/#comments</comments>
		<pubDate>Tue, 10 Jul 2007 03:38:07 +0000</pubDate>
		<dc:creator>Tony Perrie</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://involution.com/2007/07/09/css-templating-with-sass/</guid>
		<description><![CDATA[I don&#8217;t hear many people talking about Sass, but it is indeed fantastic. Basically, Sass is kind of like the Smarty of CSS Templating. Sass files compile to CSS after every change just like Smarty&#8217;s TPL files compile directly to PHP. Sass fits well into the Rails don&#8217;t-repeat-yourself methodology because you can define color and [...]]]></description>
			<content:encoded><![CDATA[<p>I don&#8217;t hear many people talking about Sass, but it is indeed fantastic.  Basically, Sass is kind of like the Smarty of CSS Templating.  Sass files compile to CSS after every change just like Smarty&#8217;s TPL files compile directly to PHP.  Sass fits well into the Rails don&#8217;t-repeat-yourself methodology because you can define color and style constants within CSS rather than explicitly specifying them twenty times.  The beauty of Sass is that you get a level of abstraction without any runtime overhead.  As a result, Sass performs well and allows quick updates to color schemes and typography without resorting to perl/find or ninja text editor foo.  So, why aren&#8217;t more people using it?</p>
]]></content:encoded>
			<wfw:commentRss>http://involution.com/2007/07/09/css-templating-with-sass/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Ruby CAPTCHA / Ruby-GD StringFT Errors Revisited</title>
		<link>http://involution.com/2007/07/09/ruby-captcha-ruby-gd-stringft-errors-revisited/</link>
		<comments>http://involution.com/2007/07/09/ruby-captcha-ruby-gd-stringft-errors-revisited/#comments</comments>
		<pubDate>Tue, 10 Jul 2007 03:09:32 +0000</pubDate>
		<dc:creator>Tony Perrie</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://involution.com/2007/07/09/ruby-captcha-ruby-gd-stringft-errors-revisited/</guid>
		<description><![CDATA[Well, I finally solved the &#8220;undefined method `stringFT' for GD::Image:Class&#8221; error under Mac OS X. The rb-gd darwinport seems to have fallen off the face of the earth. Fortunately, I&#8217;ve learned that you can download the source from ruby-lang.org. So, I just rolled my own GD.bundle. wget http://raa.ruby-lang.org/cache/ruby-gd/ruby-GD-0.7.4-1.tar.gz cd ruby-GD-0.7.4 ruby extconf.rb --with-freetype --with-xpm --with-ttf [...]]]></description>
			<content:encoded><![CDATA[<p>Well, I finally solved the &#8220;<code>undefined method `stringFT' for GD::Image:Class</code>&#8221; error under Mac OS X.  The rb-gd darwinport seems to have fallen off the face of the earth.  Fortunately, I&#8217;ve learned that you can download the source from ruby-lang.org. So, I just rolled my own GD.bundle.</p>
<pre><code>wget http://raa.ruby-lang.org/cache/ruby-gd/ruby-GD-0.7.4-1.tar.gz
cd ruby-GD-0.7.4
ruby extconf.rb --with-freetype --with-xpm --with-ttf
make
sudo make install
sudo mv /usr/local/lib/ruby/site_ruby/1.8/i686-darwin8.8.2/GD.bundle /usr/local/lib/ruby/1.8/i686-darwin8.8.2/
</code></pre>
<p>This only works if you have an up-to-date ruby installed under /usr/local (via the <a href="http://hivelogic.com/narrative/articles/ruby-rails-mongrel-mysql-osx">Hivelogic instructions</a>).  If you&#8217;ve installed from ports or are using the older ruby shipped with Leopard, you&#8217;ll need to switch your prefix to <code>/opt/local</code> or <code>/usr</code> respectively. </p>
]]></content:encoded>
			<wfw:commentRss>http://involution.com/2007/07/09/ruby-captcha-ruby-gd-stringft-errors-revisited/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Problems with Ruby&#8217;s CAPTCHA gem</title>
		<link>http://involution.com/2007/06/11/problems-with-rubys-captcha-gem/</link>
		<comments>http://involution.com/2007/06/11/problems-with-rubys-captcha-gem/#comments</comments>
		<pubDate>Mon, 11 Jun 2007 19:03:04 +0000</pubDate>
		<dc:creator>Tony Perrie</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://involution.com/2007/06/11/problems-with-rubys-captcha-gem/</guid>
		<description><![CDATA[Even though gd, gd-devel and the ruby GD and CAPTCHA gems were installed on my Red Hat Enterprise Linux 4 server, Ruby&#8217;s CAPTCHA gem seemed to blow-up with the error: undefined method `StringFT' Hmmm. I googled around and found that you need a library to bind the GD calls to ruby. This makes perfect sense, [...]]]></description>
			<content:encoded><![CDATA[<p>Even though gd, gd-devel and the ruby GD and CAPTCHA gems were installed on my Red Hat Enterprise Linux 4 server, Ruby&#8217;s CAPTCHA gem seemed to blow-up with the error:</p>
<pre><code>undefined method `StringFT'</code></pre>
<p>Hmmm.  I googled around and found that you need a library to bind the GD calls to ruby.  This makes perfect sense, but documentation for the issue is <a href="http://www.google.com/search?q=undefined+method+stringFT">scarce</a>. </p>
<p>Eventually, I found the following rpm and installed it. </p>
<pre><code>wget http://ftp.at.gnucash.org/opsys/linux/redhat.com/contrib/libc5/i686/ruby-GD-1.0_97111
rpm -ivh ruby-GD-0.7.4-0vl1.i386.rpm
</code></pre>
<p>Unfortunately, the RPM assumed that ruby would be installed under <code>/local</code>, but on RHEL everything is under <code>/usr</code>.  So, I found where the RPM stored the library and relocated it to the proper directory.</p>
<pre><code>$ rpm -qpl ruby-GD-0.7.4-0vl1.i386.rpm
/local/lib/site_ruby/1.8/i386-linux/GD.so
sudo mv /local/lib/site_ruby/1.8/i386-linux/GD.so /usr/lib/site_ruby/1.8/i386-linux/
</code></pre>
<p>Lo and behold, Ruby&#8217;s CAPTCHA gem worked like the clappers after this was sorted.  Unfortunately, it took me over an hour to sort out the problem.  It would seem that something as mundane as CAPTCHA would have just worked under Rails.  The major problem seems to be that the ruby-gd maintainer&#8217;s site <a href="http://tam.0xfa.com/ruby-gd/">http://tam.0xfa.com</a> is out of commission.  </p>
<p>Under Mac OS X, it&#8217;s a bit easier because you can use Darwin Ports to install rb-gd.  However, that install appeared to bomb for me because I&#8217;m using the latest ruby compiled via the <a href="http://hivelogic.com/narrative/articles/ruby_rails_lighttpd_mysql_tiger?status=301">Hivelogic instructions</a>.  I attempted to symbolically link the ruby binaries to /opt/local/bin, but that didn&#8217;t resolve the issue.  I&#8217;m still looking for a workaround to this. </p>
]]></content:encoded>
			<wfw:commentRss>http://involution.com/2007/06/11/problems-with-rubys-captcha-gem/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Iterating Through The Last 30 Days with Ruby on Rails</title>
		<link>http://involution.com/2007/06/10/days-for-the-last-month/</link>
		<comments>http://involution.com/2007/06/10/days-for-the-last-month/#comments</comments>
		<pubDate>Sun, 10 Jun 2007 21:17:09 +0000</pubDate>
		<dc:creator>Tony Perrie</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://involution.com/2007/06/10/days-for-the-last-month/</guid>
		<description><![CDATA[Recently, I attempted to create a loop in Ruby on Rails that iterated through the last month worth of dates. Stupidly, I just typed in the following code, and tried to run it&#8230; (you need to require ActiveSupport for month.ago to work. # This code does not work 1.month.ago.step(Time.now, 1.day) { &#124;d&#124; print d.day,"\\n" } [...]]]></description>
			<content:encoded><![CDATA[<p>Recently, I attempted to create a loop in Ruby on Rails that iterated through the last month worth of dates.  Stupidly, I just typed in the following code, and tried to run it&#8230;  (you need to require <code>ActiveSupport</code> for <code>month.ago</code> to work.</p>
<pre><code><font color="red"># This code does not work</font>
1.month.ago.step(Time.now, 1.day) { |d|
  print d.day,"\\n"
}</code></pre>
<p>Unfortunately, that doesn&#8217;t work, because <code>ActiveSupport</code> returns a <code>Time</code> class value for <code>month.ago</code>. Ruby&#8217;s <code>Time</code> class doesn&#8217;t define a step method.  So, being lazy, I just casted the time to an integer with <code>to_i</code>, and constructed the following loop which does work. </p>
<pre><code>1.month.ago.to_i.step(Time.now.to_i,1.day.to_i) { |d|
   print Time.at(d).day,"\\n"
}</code></pre>
<p>Later on, I learned that Date&#8217;s have a step class.  So, I simplified the loop. </p>
<pre><code>1.month.ago.to_date.step(Time.now.to_date, 1.day) { |d|
    print d.day,"\\n"
}</code></pre>
<p>It seems like there should be an easier way to do this though.  Does anyone have a better idea? </p>
]]></content:encoded>
			<wfw:commentRss>http://involution.com/2007/06/10/days-for-the-last-month/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Randoword.sh</title>
		<link>http://involution.com/2006/10/30/randowordsh/</link>
		<comments>http://involution.com/2006/10/30/randowordsh/#comments</comments>
		<pubDate>Mon, 30 Oct 2006 19:37:18 +0000</pubDate>
		<dc:creator>Tony Perrie</dc:creator>
				<category><![CDATA[*nix]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://involution.com/?p=962</guid>
		<description><![CDATA[I&#8217;ve had variations of this script kicking around in my .bash_history for quite some time now. The first version of it merely printed a random word from my dictionary file at a rate of one per second. This served as a source of inspiration/entropy for irc conversations and Flickr titles. Today, I decided to extend [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve had variations of this script kicking around in my .bash_history for quite some time now.  The first version of it merely printed a random word from my dictionary file at a rate of one per second.  This served as a source of inspiration/entropy for irc conversations and Flickr titles.  Today, I decided to extend this one-liner to generate eight-words-at-a-time at a variable rate and jigger the output into an irssi process to amuse the good netizens.  Here is the implementation for <a href="http://involution.com/randoword.sh.txt">randoword.sh</a>. </p>
<pre><code>
#!/bin/sh
i=0
while true; do
  let i=$i+1
  dictionary=&quot;/usr/share/dict/linux.words&quot;
  dl=($(wc -l $dictionary))
  echo -n &quot;randowords #$i: &quot;
  for j in $( seq 1 8 ); do
    head -n$(($(head -c4 /dev/urandom | od -An -tu4) % $dl))\
    $dictionary| tail -n1
  done | xargs
  sleep $((RANDOM % 3600))
done
</code></pre>
<p><b>Update:</b> I never really understood how to use random numbers within a bash script without invoking perl (or equivalent). In light of _fool&#8217;s comment, I rewrote my script using only bash and POSIX commands.  I had to break-out /dev/urandom and od because bash&#8217;s $RANDOM variable only produces random values up to 32767.  Technically, it&#8217;d be a whole lot faster for a C program to use a pointer to jump around randomly in the dictionary, but that seems too much like work. </p>
<p><b>Update 2:</b> The <code>seq</code> command probably isn&#8217;t POSIX. </p>
<p><b>Update 3:</b> In Ruby: <code>ruby -e ' $w=STDIN.readlines; 8.times{print &quot;#{$w[rand(483523)].chomp} &quot;}' < /usr/share/dict/linux.words</code></code></p>
]]></content:encoded>
			<wfw:commentRss>http://involution.com/2006/10/30/randowordsh/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Access Gmail from Ruby using Net::POP3 and Stunnel</title>
		<link>http://involution.com/2006/07/20/access-gmail-from-ruby-using-netpop3-and-stunnel/</link>
		<comments>http://involution.com/2006/07/20/access-gmail-from-ruby-using-netpop3-and-stunnel/#comments</comments>
		<pubDate>Thu, 20 Jul 2006 14:21:40 +0000</pubDate>
		<dc:creator>Tony Perrie</dc:creator>
				<category><![CDATA[GMail]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://involution.com/2006/07/20/access-gmail-from-ruby-using-netpop3-and-stunnel/</guid>
		<description><![CDATA[I Googled around for this at one point, however, all I could find were ill-fated attempts by a couple of tortured souls on ruby-talk. Google offers POP3S access to Gmail, but, unfortunately, Ruby&#8217;s Net::POP3S module is still under development. POP3S is the much reviled and revered Post Office Protocol tunneled over a thick blanket of [...]]]></description>
			<content:encoded><![CDATA[<p>I Googled around for this at one point, however, all I could find were ill-fated attempts by a couple of tortured souls on ruby-talk.  Google offers POP3S access to Gmail, but, unfortunately, Ruby&#8217;s Net::POP3S module is still under development.  POP3S is the much reviled and revered Post Office Protocol tunneled over a thick blanket of SSL obfuscation.  Fortunately, the good Stunnel folks have anticipated this kind of thing and they&#8217;re giving out some code that can encode and decode SSL to a standard socket.  </p>
<p>This was done on OS X, but Stunnel seems to work on most platforms.  However, I wasn&#8217;t finding it in ports or fink.  So, I had to roll my own stunnel binary.</p>
<p>
<pre><b>
wget http://www.stunnel.org/download/stunnel/src/stunnel-3.22.tar.gz
tar zxf stunnel-3.22.tar.gz
cd stunnel-3.22
./configure
make
sudo make install
</b></pre>
</p>
<p>Whew.  So, after you&#8217;ve installed stunnel, you need to invoke it to redirect a local port to Google&#8217;s secure POP3 port located at pop.gmail.com on port 995.  You can redirect any local port to Google&#8217;s pop server.  I chose to use port 42 because that&#8217;s as good as anything else.   Here&#8217;s my stunnel invocation.</p>
<p>
<pre><b>
sudo /usr/local/sbin/stunnel -c -d 42 -r pop.gmail.com:995
</b></pre>
</p>
<p>So, now you can use Ruby&#8217;s Net::POP3 to access your gmail from port 42 on your local machine.  Stunnel will handle the details of SSL. </p>
<pre style="color: #660000 !important;"><b>
require 'net/pop'

pop = Net::POP3.new('localhost', 42)
pop.start('mrbeastly', 'sUp3Rs3kRiT!')
  if pop.mails.empty?
    puts 'No mail.'
  else
    i = 0
    pop.each_mail do |m|
    exit if i > 20
    puts m.pop
    i=i+1
  end
end
</b></pre>
<p>Running this code will display the first 20 emails in Gmail to your terminal.  This is really a stopgap solution until the fabled POP3S patch gets accepted into Ruby&#8217;s Net library.  This is rumored to be soon.  So, I&#8217;ll keep my hopes up. </p>
]]></content:encoded>
			<wfw:commentRss>http://involution.com/2006/07/20/access-gmail-from-ruby-using-netpop3-and-stunnel/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Reflection</title>
		<link>http://involution.com/2006/07/19/reflection/</link>
		<comments>http://involution.com/2006/07/19/reflection/#comments</comments>
		<pubDate>Wed, 19 Jul 2006 18:05:27 +0000</pubDate>
		<dc:creator>Tony Perrie</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[The Gift of Beard]]></category>

		<guid isPermaLink="false">http://involution.com/2006/07/19/reflection/</guid>
		<description><![CDATA[Jim once believed that the following Ruby code constitutes an example of reflection. def create(klass, value) klass.new(value) end g = create(Greeting, &#34;Hello&#34;) g.show Neither introspection nor metaprogramming occur in this code. This is not reflection. However, Jim argues that since getConstructor exists in Sun&#8217;s Java reflect class and because the Ruby code accomplishes the same [...]]]></description>
			<content:encoded><![CDATA[<p>Jim <a href="http://onestepback.org/articles/10things/page023.html">once believed</a> that the following Ruby code constitutes an example of <a href="http://wikipedia.org/wiki/Reflection_%28computer_science%29">reflection</a>.</p>
<pre>
def create(klass, value)
    klass.new(value)
end

g = create(Greeting, &quot;Hello&quot;)
g.show
</pre>
<p>Neither introspection nor metaprogramming occur in this code.  This is not reflection.  However, Jim argues that since getConstructor exists in Sun&#8217;s Java reflect class and because the Ruby code accomplishes the same task as his Java example that this <b>is</b> reflection.  This logic is tenuous.  However, I can defeat it because his Java code does not exemplify reflection.  </p>
<pre>
public static Object create(Class c, String value)
  throws Exception
{
  Constructor ctor = c.getConstructor(
    new Class[] { String.class } );
  return ctor.newInstance(
    new Object[] { &quot;Hello&quot; } );
}

public static void main (String args[])
  throws Exception
{
  Greeting g =
    (Greeting) create(Greeting.class, &quot;Hello&quot;);
  g.show();
}
</pre>
<p>Using Java&#8217;s reflect class does not preclude that reflection has occured.  If these examples are reflection, I could argue that the following C code is an example of reflection.</p>
<pre>
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;
#include &lt;stdlib.h&gt;

void* create(void* klass, char* value);

void* create(void* klass, char* value) {
  size_t value_length = strlen(value);
  klass = malloc(value_length+1);
  strncpy(klass,value, value_length);
  return klass;
}

int main() {
  char* Greeting;
  Greeting = create(Greeting, &quot;Hello&quot;);
  printf(&quot;%s&quot;, Greeting);
  free(Greeting);
  return 0;
}
</pre>
<p>Oh dear.  Why did I switch to Ruby anyway if I can reflect in C?  </p>
]]></content:encoded>
			<wfw:commentRss>http://involution.com/2006/07/19/reflection/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

