<?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>Blog.ubrious &#187; Ruby</title>
	<atom:link href="http://blog.ubrio.us/tag/ruby/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.ubrio.us</link>
	<description>An Ordinary Web Developer's Blog</description>
	<lastBuildDate>Thu, 19 Jan 2012 00:44:59 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Rails Metal and ActiveRecord Sessions</title>
		<link>http://blog.ubrio.us/ruby/rails-metal-and-activerecord-sessions/</link>
		<comments>http://blog.ubrio.us/ruby/rails-metal-and-activerecord-sessions/#comments</comments>
		<pubDate>Wed, 04 Mar 2009 17:47:41 +0000</pubDate>
		<dc:creator>Rob Hurring</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[hack]]></category>
		<category><![CDATA[rails]]></category>

		<guid isPermaLink="false">http://blog.ubrio.us/?p=121</guid>
		<description><![CDATA[I was playing around in Rails 2.3 and wanted to mess with Metal for a very simple API. The release notes say that it supports sessions &#8212; and that may be true for memcache and cookie stores, but I couldn&#8217;t get it working with ActiveRecord.
I sniffed around and noticed that abstract stores aren&#8217;t getting loaded [...]]]></description>
			<content:encoded><![CDATA[<p>I was playing around in Rails 2.3 and wanted to mess with Metal for a very simple API. The release notes say that it supports sessions &#8212; and that may be true for memcache and cookie stores, but I couldn&#8217;t get it working with ActiveRecord.</p>
<p>I sniffed around and noticed that abstract stores aren&#8217;t getting loaded as of this version (RC1).</p>
<pre class="brush: ruby;">
# action_controller/session/abstract_store.rb
def get_session(env, sid)
  raise '#get_session needs to be implemented.'
end

def set_session(env, sid, session_data)
  raise '#set_session needs to be implemented.'
end
</pre>
<p>So, to work around that, I grabbed the actual get_session code from actioncontroller&#8217;s SqlBypass class and got it working within metal:</p>
<pre class="brush: ruby;">
def self.call(env)
  if env[&quot;PATH_INFO&quot;] =~ /^\/test/

    request = Rack::Request.new(env)
    session_options = env['rack.session.options']
    sid = request.cookies[session_options[:key]]
    session = ActiveRecord::SessionStore::Session.find_by_session_id(sid)
    session ||= ActiveRecord::SessionStore::Session.new(:session_id =&gt; sid, :data =&gt; {})

    [200, {&quot;Content-Type&quot; =&gt; &quot;text/html&quot;}, session.data.inspect]
  else
    [404, {&quot;Content-Type&quot; =&gt; &quot;text/html&quot;}, [&quot;Not Found&quot;]]
  end
end
</pre>
<p>This has worked so far as I can get the user_id necessary. I&#8217;m not sure there is a &#8220;just works&#8221; way of doing this &#8212; but I couldn&#8217;t find it and Google didn&#8217;t help much.</p>
<p>Hopefully someone out there can make use of this, I scratched me head for a while before just loading the session by hand.</p>
<p><a name='middleware'></a></p>
<h3>Using Middleware</h3>
<p>I just hacked this together and it seems to work (for my testing at least):</p>
<pre class="brush: ruby;">
# lib/force_active_record_session.rb
module Rack
  class ForceActiveRecordSession
    def initialize(app, options = {})
      @app = app
    end
    def call(env)
      request = Rack::Request.new(env)
      sid = request.cookies[env['rack.session.options'][:key]]
      env['rack.session.record'] = \
        ActiveRecord::SessionStore::Session.find_by_session_id(sid) || \
          ActiveRecord::SessionStore::Session.new(:session_id =&gt; sid, :data =&gt; {})
      @app.call(env)
    end
  end
end

# environment.rb
require 'lib/force_active_record_session.rb'

# environment.rb -- inside Initializer block
config.middleware.insert 5, Rack::ForceActiveRecordSession

# in your metal action
session = env['rack.session.record'].data rescue {}
[200, {&quot;Content-Type&quot; =&gt; &quot;text/html&quot;}, session.inspect]
</pre>
<div class='tip'>
Just double check with <tt>rake middleware</tt> that the <tt>Rack::ForceActiveRecordSession</tt> is before <tt>Rails::Rack::Metal</tt>
</div>
]]></content:encoded>
			<wfw:commentRss>http://blog.ubrio.us/ruby/rails-metal-and-activerecord-sessions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Simple rails time based fragment caching with file store</title>
		<link>http://blog.ubrio.us/ruby/ruby-rails/simple-rails-time-based-fragment-caching-with-file-store/</link>
		<comments>http://blog.ubrio.us/ruby/ruby-rails/simple-rails-time-based-fragment-caching-with-file-store/#comments</comments>
		<pubDate>Wed, 14 Jan 2009 11:27:41 +0000</pubDate>
		<dc:creator>Rob Hurring</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[caching]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://blog.ubrio.us/?p=106</guid>
		<description><![CDATA[I spent a little while this morning looking around for a rails fragment caching solution which used a file store and had simple expirations built in. No luck. I could just use a memory based cache store, but for this particular problem it was too much overhead to setup and manage. 

The features are:

You can [...]]]></description>
			<content:encoded><![CDATA[<p>I spent a little while this morning looking around for a rails fragment caching solution which used a file store and had simple expirations built in. No luck. I could just use a memory based cache store, but for this particular problem it was too much overhead to setup and manage. </p>
<p><a name='features'></a></p>
<h3>The features are:</h3>
<ol>
<li>You can use it in the controller: <code>fragment_exist?(...)</code></li>
<li>You can use it in views: <code>cache(...) {}</code></li>
<li>Very lightweight</li>
<li>Behaves like the regular file store caching</li>
<li>Can expire caches automatically</li>
</ol>
<p><a name='code'></a></p>
<h3>Timed file store code</h3>
<pre class="brush: ruby;">
# lib/timed_file_store.rb
class TimedFileStore &lt; ActiveSupport::Cache::FileStore
  def exist?(name, options = {})
    delete_if_expired(name, options[:time_to_live]) unless options.blank? or options[:time_to_live].blank?
    super
  end
  def read(name, options = {})
    delete_if_expired(name, options[:time_to_live]) unless options.blank? or options[:time_to_live].blank?
    super
  end
protected
  def delete_if_expired(name, time_to_live = 0)
    delete(name) if expired?(name, time_to_live) rescue nil
  end
  def expired?(name, time_to_live = 0)
    return false unless time_to_live &gt; 0
    (Time.now - File.mtime(real_file_path(name))) &gt;= time_to_live
  end
end
</pre>
<p><a name='usage'></a></p>
<h3>Setup &amp; Usage</h3>
<pre class="brush: ruby;">
# environment.rb
# same as :file_store -- just add timed_
config.cache_store = :timed_file_store, File.join(RAILS_ROOT, 'tmp', 'cache')
</pre>
<p><strong>Time based expiration from the controller</strong></p>
<p>Having the controller control the expiration of the cache is good if you are passing along any objects to the views since it will not re-run the code if it is already cached. I&#8217;m using this for a long running report currently.</p>
<pre class="brush: ruby;">
# YourController.rb
# don't run the report if we are cached
@report = Report.find(params[:id])
unless fragment_exists?(&quot;report_#{@report.id}&quot;, :time_to_live =&gt; 1.week)
  @report.run!
end

# views/reports/show.html.erb -- or whatever view file
&lt;% cache(&quot;report_#{@report.id}&quot;) do -%&gt;
  &lt;!-- output the report HTML and such --&gt;
&lt;% end -%&gt;
</pre>
<p>This will expire the fragment and re-run the report after the cache&#8217;s File.mtime is older than a week. The view doesn&#8217;t have anything to do with it so it acts like the normal FileStore.</p>
<p><strong>Time based expiration in the view</strong></p>
<p>If you aren&#8217;t running any intense code in the controller and just want to keep a certain view fragment cached for a while, this should work. (** I didn&#8217;t test this since I only needed the previous method, but it should work &#8212; maybe with some slight tweaks? <img src='http://blog.ubrio.us/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<pre class="brush: ruby;">
# views/wherever/whatever.html.erb
&lt;% cache(&quot;whatever&quot;, :time_to_live =&gt; 1.hour) do -%&gt;
  &lt;!-- This is my HTML content and all that jazz --&gt;
  &lt;!-- After 1 hour this cache should be re-freshed --&gt;
&lt;% end -%&gt;
</pre>
<p>Not sure how useful that would be when considering action and page caching&#8230; but its possible. The only thing I noticed is that in the log when the cache deletes itself it shows a &#8220;Cached fragment hit:&#8221; then a &#8220;Cached fragment miss:&#8221; &#8212; probably needs some attention if I ever get around to it.</p>
<p>Let me know if this works out, and/or any issues, bugs, etc.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.ubrio.us/ruby/ruby-rails/simple-rails-time-based-fragment-caching-with-file-store/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Rails 2.2 Custom Error Pages With Exception Loggable</title>
		<link>http://blog.ubrio.us/code/rails-22-custom-error-pages-with-exception-loggable/</link>
		<comments>http://blog.ubrio.us/code/rails-22-custom-error-pages-with-exception-loggable/#comments</comments>
		<pubDate>Mon, 01 Dec 2008 18:44:03 +0000</pubDate>
		<dc:creator>Rob Hurring</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[rails]]></category>

		<guid isPermaLink="false">http://blog.ubrio.us/?p=105</guid>
		<description><![CDATA[Well, with the release of Rails 2.2 and the ability to create custom error pages I figured I&#8217;d revisit my 404/500 pages and try to do it the new way.
Setting up the rescue_from methods were simple enough, but I noticed that when I was capturing my error 500s it wasn&#8217;t logging the exception. Here is [...]]]></description>
			<content:encoded><![CDATA[<p>Well, with the release of Rails 2.2 and the ability to <a href='http://m.onkey.org/2008/7/20/rescue-from-dispatching' onclick="pageTracker._trackPageview('/outgoing/m.onkey.org/2008/7/20/rescue-from-dispatching?referer=');">create custom error pages</a> I figured I&#8217;d revisit my 404/500 pages and try to do it the new way.</p>
<p>Setting up the <tt>rescue_from</tt> methods were simple enough, but I noticed that when I was capturing my error 500s it wasn&#8217;t logging the exception. Here is a quick way to have it both display your custom 500 page and log the exception for later review:</p>
<pre class="brush: ruby;">
  # application.rb
  include ExceptionLoggable

  unless ActionController::Base.consider_all_requests_local
    # yeah, its a long line
    rescue_from ActiveRecord::RecordNotFound, ActionController::RoutingError, ActionController::UnknownController, ActionController::UnknownAction, :with =&gt; :render_404
    rescue_from RuntimeError, :with =&gt; :render_500
  end

private

  def render_404
    render :template =&gt; &quot;shared/error_404&quot;, :layout =&gt; 'application', :status =&gt; :not_found
  end

  def render_500
    # hacky, but works, this logs the exception in ExceptionLoggable
    log_exception $!
    render :template =&gt; &quot;shared/error_500&quot;, :layout =&gt; 'application', :status =&gt; :internal_server_error
  end
</pre>
<p>To test this just change <code>config.action_controller.consider_all_requests_local = true</code> to <code>config.action_controller.consider_all_requests_local = false</code> in your <tt>config/environments/development.rb</tt> file.</p>
<p>Not the _best_ way or cleanest, but it gets the job done without too much trouble.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.ubrio.us/code/rails-22-custom-error-pages-with-exception-loggable/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>OSX, RubyGems and cross-thread violations in rb_gc</title>
		<link>http://blog.ubrio.us/nix/osx-rubygems-and-cross-thread-violations-in-rb_gc/</link>
		<comments>http://blog.ubrio.us/nix/osx-rubygems-and-cross-thread-violations-in-rb_gc/#comments</comments>
		<pubDate>Thu, 20 Nov 2008 15:37:40 +0000</pubDate>
		<dc:creator>Rob Hurring</dc:creator>
				<category><![CDATA[Mac OS X]]></category>
		<category><![CDATA[Nix]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[bash]]></category>
		<category><![CDATA[gems]]></category>

		<guid isPermaLink="false">http://blog.ubrio.us/?p=104</guid>
		<description><![CDATA[I recently decided to migrate away from OSX&#8217;s default ruby install yesterday and noticed a few quirky hangups. Firstly, for some reason, and I&#8217;m not sure if it is just me or not, OSX&#8217;s default $PATH variable is putting /usr/local/bin AFTER /bin making your local installs not enabled by default. (Editing the /etc/paths didn&#8217;t do [...]]]></description>
			<content:encoded><![CDATA[<p>I recently decided to migrate away from OSX&#8217;s default ruby install yesterday and noticed a few quirky hangups. Firstly, for some reason, and I&#8217;m not sure if it is just me or not, OSX&#8217;s default $PATH variable is putting /usr/local/bin AFTER /bin making your local installs not enabled by default. (Editing the /etc/paths didn&#8217;t do the trick so I manually added it to PATH).</p>
<p>The installation went easily for both ruby gems and ruby, but I decided to take a &#8217;short cut&#8217; and copy all my gems from /Library/Ruby/Gems into my /usr/local/lib directory which started raising all kinds of errors &#8212; this one, in particular was obnoxious.</p>
<p><code>[BUG] cross-thread violation on rb_gc()</code></p>
<p>Luckily, all that means is that I copied over gems which were compiled against the standard OSX ruby version and not the new one. This was a little script I wrote which will show you which gems need to be re-compiled. Just <tt>cd</tt> over to your /usr/local/lib/ruby/gems/1.8/gems directory and run:</p>
<p><code><span>gems $></span>ls -1 **/**/*.bundle|ruby -pe '$_.gsub! /\-.*/, ""'|uniq</code></p>
<p>to get a list, or pipe that into <code><span>$></span> sudo gem install</code> and that should clear up those gc issues.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.ubrio.us/nix/osx-rubygems-and-cross-thread-violations-in-rb_gc/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Rails: Mocking YAML arrays as ActiveRecord objects</title>
		<link>http://blog.ubrio.us/code/rails-mocking-yaml-arrays-as-activerecord-objects/</link>
		<comments>http://blog.ubrio.us/code/rails-mocking-yaml-arrays-as-activerecord-objects/#comments</comments>
		<pubDate>Wed, 24 Sep 2008 14:31:12 +0000</pubDate>
		<dc:creator>Rob Hurring</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Web]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby on rails]]></category>
		<category><![CDATA[yaml]]></category>

		<guid isPermaLink="false">http://blog.ubrio.us/?p=103</guid>
		<description><![CDATA[I&#8217;ve been finding myself using YAML a lot for silly enums &#8212; maybe because I&#8217;m lazy, but mostly because there is no need to manage them via a database table. Here is just a simple example &#8212; I need to associate a region and division to a client. These will not change much and are [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been finding myself using YAML a lot for silly enums &#8212; maybe because I&#8217;m lazy, but mostly because there is no need to manage them via a database table. Here is just a simple example &#8212; I need to associate a region and division to a client. These will not change much and are simple enough to keep as a Yaml array until more logic can be brought to the table. Here is how that YAML file looks:</p>
<pre class="brush: ruby;">
# RAILS_ROOT/config/app.yml

regions:
  - 'northeast'
  - 'southeast'
  - 'west'
  - 'central'
  - 'emerging east'
  - 'emerging west'
  - 'opportunity east'
  - 'opportunity west'
  - 'opportunity national east'
  - 'opportunity national west'

divisions:
  &lt;%= (1..71).map{ |i| &quot;Region #{i}&quot; }.to_yaml %&gt;
</pre>
<p>Loading it up using an initializer:</p>
<pre class="brush: ruby;">
# RAILS_ROOT/config/initializers/load_app_config.rb

fdata =File.open(File.join(RAILS_ROOT, &quot;config&quot;, &quot;app.yml&quot;)).read
APP = YAML::load(ERB.new(fdata).result(binding)).symbolize_keys
</pre>
<p>Now we have our APP hash chock full o&#8217; YAML goodness. My only problem with this is that I might want to eventually put this data set into a table and it is a pain to hunt and search for where the application references APP[:regions] and so on sooo: time to objectize.</p>
<p>I decided that since they are stupid simple objects they can all have the same parent: YamlArrayObject:</p>
<pre class="brush: ruby;">
# RAILS_ROOT/app/models/yaml_array_object.rb
# or in lib

class YamlArrayObject
  attr_reader :name
  def id
    0
  end
  def initialize(name)
    @name = name
  end
  def to_s
    name
  end
  def display_name
    to_s.titleize
  end
  def &lt;=&gt;(b)
    name &lt;=&gt; b.name
  end
end
</pre>
<p>Simple enough. Now we just inherit and overload as appropriate.</p>
<pre class="brush: ruby;">
# RAILS_ROOT/app/models/region.rb
class Region &lt; YamlArrayObject
  def self.all
    APP[:regions].map{ |r| Region.new(r) }
  end
end

# RAILS_ROOT/app/models/division.rb
class Division &lt; YamlArrayObject
  def &lt;=&gt;(b)
    name.to_i &lt;=&gt; b.name.to_i
  end
  def self.all
    APP[:divisions].map{ |d| Division.new(d) }
  end
end
</pre>
<p>This is all Jim Dandy right now since we can populate select boxes using cleaner code (bonus: won&#8217;t break if you decide to add Divisions to a database table)</p>
<pre class="brush: ruby;">
# i like
&lt;%= f.select :division, Division.all.sort.map{ |d| [d.display_name, d] } -%&gt;
# better than
&lt;%= f.select :division, APP[:divisions].sort{|a,b| a.to_i &lt;=&gt; b.to_i}.map{ |d| [d.titleize, d] } -%&gt;
</pre>
<p>The only real issue is that calling <code>Client.first.region</code> still returns a string, which is bad since we want to keep our code as ambiguous as possible. The last step is to override the Client class&#8217; methods for region and division (and whatever else we want to use):</p>
<pre name='code' class='ruby'>
# RAILS_ROOT/app/models/client.rb

def division
  Division.new(@attributes['division']) unless @attributes['division'].blank?
end
def region
  Region.new(@attributes['region']) unless @attributes['region'].blank?
end
</pre>
<p>Now in our views (client/show) we can simply call <code>@client.region.display_name</code> or whatever and not have to change the code when we finally get around to DBing those object.</p>
<p>(There might be better ways to do this that I&#8217;m missing, but this seems pretty okay for my needs right now.)</p>
<div class='tip'>You might also be able to define the simple objects within YAML itself &#8212; but than can get cumbersome</div>
]]></content:encoded>
			<wfw:commentRss>http://blog.ubrio.us/code/rails-mocking-yaml-arrays-as-activerecord-objects/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby on Rails Helpful Helpers: Content Tags</title>
		<link>http://blog.ubrio.us/code/ruby-on-rails-helpful-helpers-content-tags/</link>
		<comments>http://blog.ubrio.us/code/ruby-on-rails-helpful-helpers-content-tags/#comments</comments>
		<pubDate>Mon, 22 Sep 2008 19:07:16 +0000</pubDate>
		<dc:creator>Rob Hurring</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[helper]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby on rails]]></category>

		<guid isPermaLink="false">http://blog.ubrio.us/?p=102</guid>
		<description><![CDATA[Another common thing I like to do is use a helper method to handle tricky tag-soupish markup. A client may have 1 URL, in which case I would like to simply display it, but if they have multiple URLs I&#8217;d like to put it in a list format. The only problem with using the content_tag [...]]]></description>
			<content:encoded><![CDATA[<p>Another common thing I like to do is use a helper method to handle tricky tag-soupish markup. A client may have 1 URL, in which case I would like to simply display it, but if they have multiple URLs I&#8217;d like to put it in a list format. The only problem with using the <tt>content_tag</tt> function is that it ugly to do HTML building. (And sometimes you just don&#8217;t _need_ a builder&#8230;) This is just a simple wrapper for these cases.</p>
<pre class="brush: ruby;">
  def content_tag_each(items)
    items.inject(''){ |output, item| output &lt;&lt; yield(item) }
  end
</pre>
<h3>Usage</h3>
<pre class="brush: ruby;">
# urls = (string) semi-colon seperated URL list since this is
# from a legacy system and doesn't really need normalization
def display_urls(urls)
  link_options = {:target =&gt; :blank}
  urls = urls.split(';')

  # handle single url
  return link_to(urls.first, urls.first, link_options) unless urls.size &gt; 1

  # handle multiple urls
  content_tag(:ul) do
    content_tag_each(urls) do |url|
      content_tag(:li){ link_to(url, url, link_options) }
    end
  end
end
</pre>
<p>Nothing special really, but can come in handy for certain cases.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.ubrio.us/code/ruby-on-rails-helpful-helpers-content-tags/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Ruby on Rails Helpful Helpers: Defaulting Variables</title>
		<link>http://blog.ubrio.us/code/ruby-on-rails-helpful-helpers-defaulting-variables/</link>
		<comments>http://blog.ubrio.us/code/ruby-on-rails-helpful-helpers-defaulting-variables/#comments</comments>
		<pubDate>Mon, 22 Sep 2008 18:57:36 +0000</pubDate>
		<dc:creator>Rob Hurring</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[helper]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby on rails]]></category>

		<guid isPermaLink="false">http://blog.ubrio.us/?p=101</guid>
		<description><![CDATA[One piece of code I find myself using a lot is for defaulting values using a simple conditional if statement: condition ? true : false. This isn&#8217;t bad in itself, but it also isn&#8217;t very powerful  and dynamic. I wrote a small application helper which wraps this function and provides a pretty nice way [...]]]></description>
			<content:encoded><![CDATA[<p>One piece of code I find myself using a lot is for defaulting values using a simple conditional if statement: <code>condition ? true : false</code>. This isn&#8217;t bad in itself, but it also isn&#8217;t very powerful  and dynamic. I wrote a small application helper which wraps this function and provides a pretty nice way of setting default values.</p>
<pre class="brush: ruby;">
  def default(object, default = 'n/a')
    return default if object.blank?
    block_given? ? yield(object) : object
  end
</pre>
<h3>Usage</h3>
<p>A very simple example:</p>
<pre class="brush: ruby;">
#
# Simple Example
#

my_string = ''
puts default(my_string, 'String is empty')
# =&gt; 'String is empty'

my_string = 'hello world'
puts default(my_string, 'String is empty')
# =&gt; 'hello world'

my_string = 'hello world'
puts default(my_string, 'String is empty') { |str| str.titleize }
# =&gt; 'Hello World'

#
# Yielding example
#

puts default(current_user, 'Guest') { |user| user.name.titleize }
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.ubrio.us/code/ruby-on-rails-helpful-helpers-defaulting-variables/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Subversion Info in Ruby / Rails</title>
		<link>http://blog.ubrio.us/code/subversion-info-in-ruby-rails/</link>
		<comments>http://blog.ubrio.us/code/subversion-info-in-ruby-rails/#comments</comments>
		<pubDate>Wed, 16 Jul 2008 15:34:51 +0000</pubDate>
		<dc:creator>Rob Hurring</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Nix]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby on rails]]></category>
		<category><![CDATA[subversion]]></category>
		<category><![CDATA[svn]]></category>

		<guid isPermaLink="false">http://blog.ubrio.us/?p=98</guid>
		<description><![CDATA[I was trying to tag a few of my internal apps with a subversion revision number just for personal reference. Since running the command svn info yields YAML-ish output the ruby YAML library can load it. Sweet. The next step was just wrapping it in a class and creating some instance variables and methods for [...]]]></description>
			<content:encoded><![CDATA[<p>I was trying to tag a few of my internal apps with a subversion revision number just for personal reference. Since running the command <code>svn info</code> yields YAML-ish output the ruby YAML library can load it. Sweet. The next step was just wrapping it in a class and creating some instance variables and methods for them.</p>
<h3>The default YAML output</h3>
<p>This is what you will get if you simply throw the YAML.load result to an array or something. Nice, but I&#8217;m not a big fan of &#8220;Keys Like This&#8221; so&#8230;</p>
<pre class="brush: ruby;">
irb(main):011:0&gt; pp YAML.load(`svn info`)
{&quot;Node Kind&quot;=&gt;&quot;directory&quot;,
 &quot;Last Changed Author&quot;=&gt;&quot;rob&quot;,
 &quot;URL&quot;=&gt;&quot;http://example.com/share/lib&quot;,
 &quot;Schedule&quot;=&gt;&quot;normal&quot;,
 &quot;Last Changed Rev&quot;=&gt;441,
 &quot;Repository UUID&quot;=&gt;&quot;0afc494f-e74d-0410-99f2-b94b27995134&quot;,
 &quot;Repository Root&quot;=&gt;&quot;http://example.com&quot;,
 &quot;Last Changed Date&quot;=&gt;&quot;2008-07-15 15:55:54 -0400 (Tue, 15 Jul 2008)&quot;,
 &quot;Revision&quot;=&gt;446,
 &quot;Path&quot;=&gt;&quot;.&quot;}
=&gt; nil
</pre>
<h3>A nice class wrapper for the SVN Info</h3>
<p>Heres what I ended up with. Nothing fancy, just a simple wrapper around the subversion info dump.</p>
<pre class="brush: ruby;">
require 'yaml'
class SVNInfo
  def initialize
      YAML.load(`svn info`).each do |k,v|
          key = k.gsub(/\s/, '_').downcase
          instance_variable_set &quot;@#{key}&quot;, v
          instance_eval %{ def #{key}; @#{key}; end }
      end
  end
end
</pre>
<p><strong>Here is the end result:</strong></p>
<pre class="brush: ruby;">
irb(main):013:0&gt; svn_info = SVNInfo.new
# ... snip ...
irb(main):014:0&gt; pp svn_info
&lt;SVNInfo:0x57f378
 @last_changed_author=&quot;rob&quot;,
 @last_changed_date=&quot;2008-07-15 15:55:54 -0400 (Tue, 15 Jul 2008)&quot;,
 @last_changed_rev=441,
 @node_kind=&quot;directory&quot;,
 @path=&quot;.&quot;,
 @repository_root=&quot;http://example.com&quot;,
 @repository_uuid=&quot;0afc494f-e74d-0410-99f2-b94b27995134&quot;,
 @revision=446,
 @schedule=&quot;normal&quot;,
 @url=&quot;http://example.com/share/lib&quot;&gt;
=&gt; nil
irb(main):015:0&gt;
</pre>
<p><strong>Messing Around</strong></p>
<pre class="brush: ruby;">
irb(main):018:0&gt; pp svn_info.methods - Object.methods
[&quot;last_changed_author&quot;,
 &quot;revision&quot;,
 &quot;repository_root&quot;,
 &quot;last_changed_rev&quot;,
 &quot;path&quot;,
 &quot;url&quot;,
 &quot;node_kind&quot;,
 &quot;last_changed_date&quot;,
 &quot;repository_uuid&quot;,
 &quot;schedule&quot;]
=&gt; nil
irb(main):019:0&gt; svn_info.revision
=&gt; 446
irb(main):020:0&gt; svn_info.last_changed_author
=&gt; &quot;rob&quot;
irb(main):021:0&gt;
</pre>
<p>Hope that comes in handy <img src='http://blog.ubrio.us/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.ubrio.us/code/subversion-info-in-ruby-rails/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>shakebook pro for leopard &#8211; switch spaces with violence!</title>
		<link>http://blog.ubrio.us/code/shakebook-pro-for-leopard-switch-spaces-with-violence/</link>
		<comments>http://blog.ubrio.us/code/shakebook-pro-for-leopard-switch-spaces-with-violence/#comments</comments>
		<pubDate>Tue, 29 Apr 2008 22:59:21 +0000</pubDate>
		<dc:creator>Rob Hurring</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Mac OS X]]></category>
		<category><![CDATA[Random]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[hack]]></category>
		<category><![CDATA[laptop]]></category>
		<category><![CDATA[smack]]></category>
		<category><![CDATA[violence]]></category>

		<guid isPermaLink="false">http://blog.ubrio.us/ruby/shakebook-pro-for-leopard-switch-spaces-with-violence/</guid>
		<description><![CDATA[
Update!
Switch spaces using your Apple Remote! (Or view the project on GitHub)

I was just goin around on the interblagosphere today and stumbled upon Erling Ellingsen&#8217;s smackbook pro. If you&#8217;ve never heard of this then you&#8217;re in for a shock. The basic idea behind what he has created is a way to switch virtual desktops simply [...]]]></description>
			<content:encoded><![CDATA[<div class='tip'>
<strong>Update!</strong><br />
<a href='http://blog.ubrio.us/web/ruby-dsl-for-apple-remotes/'>Switch spaces using your Apple Remote!</a> <small>(Or view the project on <a href='http://github.com/robhurring/apple-remote' onclick="pageTracker._trackPageview('/outgoing/github.com/robhurring/apple-remote?referer=');">GitHub</a>)</small>
</div>
<p>I was just goin around on the interblagosphere today and stumbled upon <a href="http://blog.medallia.com/2006/05/smacbook_pro.html" onclick="pageTracker._trackPageview('/outgoing/blog.medallia.com/2006/05/smacbook_pro.html?referer=');">Erling Ellingsen&#8217;s smackbook pro</a>. If you&#8217;ve never heard of this then you&#8217;re in for a shock. The basic idea behind what he has created is a way to switch virtual desktops simply by tapping the side of the laptop&#8217;s monitor.</p>
<p>I was immediately in love and wanted to play with it a bit but he was using <a href='http://desktopmanager.berlios.de/' onclick="pageTracker._trackPageview('/outgoing/desktopmanager.berlios.de/?referer=');">DesktopManager</a> to do the space switching. Since I&#8217;m running leopard on the laptop I figured that was a waste of time and I&#8217;d never actually use a 3&#8242;d party virtual desktop switching app&#8230; and so the journey began. I turned to my mortal enemy, applescript, to accomplish this. After some browsing and hacking I found that this simple code can send CONTROL-# keystrokes to get the job done:</p>
<pre>tell application "System Events"
	tell process "Finder"
		keystroke "[SPACENUMBER]" using control down
	end tell
end tell
</pre>
<p>If you toss that into <tt>osascript</tt> from the command line we can finally start to get somewhere. So the next step was to grab that sudden motion sensor app. Erling was using <a href='http://www.osxbook.com/software/sms/amstracker/' onclick="pageTracker._trackPageview('/outgoing/www.osxbook.com/software/sms/amstracker/?referer=');">AMSTracker</a> by Amit Singh so that seemed a good place to start. After that a quick ruby script tied the SMS dump to the applescript and a fun new project was born. It is a lotta bit rough around the edges and needs some sensitivity tuning, but it _does_ get the job done&#8230; just be a little rough* <img src='http://blog.ubrio.us/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<blockquote><p>I am definitely not responsible for any damage caused by using this script &#8212; it was a proof of concept hack.</p></blockquote>
<h3>Based off &#8220;SmackBook Pro&#8221;</h3>
<div class='wp-caption alignleft'>
<img src="http://file.ubrio.us/wordpress/default.jpg" alt="" title="default" width="130" height="97" class="alignnone size-full wp-image-96" /></p>
<p class='wp-caption-text'><a href='http://www.youtube.com/v/6uvQTTPr9Rw&#038;hl=en' rel='flash' class='lightview' title="Smackbook Pro::Bad and Rad" onclick="pageTracker._trackPageview('/outgoing/www.youtube.com/v/6uvQTTPr9Rw_038_hl=en?referer=');">YouTube Video</a></p>
</div>
<p>This is not mine, but mine does essentially the same thing, only using native Leopard spaces&#8230; and ruby.</p>
<p><br clear='both' /></p>
<h3>Where to get the script?</h3>
<ul>
<li><a href='http://code.google.com/p/shakebook/' onclick="pageTracker._trackPageview('/outgoing/code.google.com/p/shakebook/?referer=');">shakebook project site</a></li>
</ul>
<p>Running it is as simple as <code><span>$></span>AMSTracker -S -u0.01 | shakebook.rb</code> then tap away (or shake if you want to be careful)</p>
<div class='success'>Revisions will probably be made to sensitize it once I have time to mess around with it &#8212; if you come up with anything shoot me back a comment <img src='http://blog.ubrio.us/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </div>
]]></content:encoded>
			<wfw:commentRss>http://blog.ubrio.us/code/shakebook-pro-for-leopard-switch-spaces-with-violence/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

