<?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</title>
	<atom:link href="http://blog.ubrio.us/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>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Blogubrious Retiring &#8212; Moving to Proccli</title>
		<link>http://blog.ubrio.us/web/blogubrious-retiring-moving-to-proccli/</link>
		<comments>http://blog.ubrio.us/web/blogubrious-retiring-moving-to-proccli/#comments</comments>
		<pubDate>Fri, 26 Mar 2010 20:38:51 +0000</pubDate>
		<dc:creator>Rob Hurring</dc:creator>
				<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://blog.ubrio.us/?p=222</guid>
		<description><![CDATA[I&#8217;m migrating all new blog entries to a new name/site: Proccli: Code Sprouts. I&#8217;ll try to keep on top of comments and such coming in here, but it will eventually start to decay (hopefully gracefully). -Rob]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m migrating all new blog entries to a new name/site: <a href='http://proccli.com' onclick="pageTracker._trackPageview('/outgoing/proccli.com?referer=');">Proccli: Code Sprouts</a>. </p>
<p>I&#8217;ll try to keep on top of comments and such coming in here, but it will eventually start to decay (hopefully gracefully).</p>
<p>-Rob</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.ubrio.us/web/blogubrious-retiring-moving-to-proccli/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby DSL for Apple Remotes</title>
		<link>http://blog.ubrio.us/web/ruby-dsl-for-apple-remotes/</link>
		<comments>http://blog.ubrio.us/web/ruby-dsl-for-apple-remotes/#comments</comments>
		<pubDate>Fri, 17 Jul 2009 01:31:33 +0000</pubDate>
		<dc:creator>Rob Hurring</dc:creator>
				<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://blog.ubrio.us/?p=208</guid>
		<description><![CDATA[I was curious about RubyCocoa and decided to play around a bit. I came across this article on rubycocoa.com about the apple remote and ruby. I got it working and boredom took over&#8230; so I decided to wrap it with a simple DSL. It seems pretty pointless, although switching OSX spaces with it was fun&#8230; [...]]]></description>
			<content:encoded><![CDATA[<p>I was curious about RubyCocoa and decided to play around a bit. I came across this article on rubycocoa.com <a href='http://www.rubycocoa.com/appleremote/1' onclick="pageTracker._trackPageview('/outgoing/www.rubycocoa.com/appleremote/1?referer=');">about the apple remote</a> and ruby. I got it working and boredom took over&#8230; so I decided to wrap it with a simple DSL. It seems pretty pointless, although <a href='http://github.com/robhurring/apple-remote/blob/9fc726c85d7fa90701e6a701266a67f801bdcdfc/spaces.rb' onclick="pageTracker._trackPageview('/outgoing/github.com/robhurring/apple-remote/blob/9fc726c85d7fa90701e6a701266a67f801bdcdfc/spaces.rb?referer=');">switching OSX spaces with it</a> was fun&#8230;</p>
<h3>How does it look?</h3>
<p>More examples are on the GitHub project page linked below, but here is a small overview.</p>
<pre class="brush: ruby;">
require 'lib/apple_remote'

play do
  puts &quot;I'm playing... (Playing? #{playing?})&quot;
end

pause do
  puts &quot;I'm paused... (Playing? #{playing?})&quot;
end

menu do
  if playing?
    puts &quot;Do something with the menu while we're in 'play' state&quot;
  else
    puts &quot;Do something with the menu while we're not in the 'play' state&quot;
  end
end
</pre>
<p>Tons of fun <img src='http://blog.ubrio.us/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h4>Code</h4>
<p><a href='http://github.com/robhurring/apple-remote' onclick="pageTracker._trackPageview('/outgoing/github.com/robhurring/apple-remote?referer=');">Ruby Apple Remote DSL project on GitHub</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.ubrio.us/web/ruby-dsl-for-apple-remotes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>GitHub theme for SyntaxHighlighter WordPress plugin</title>
		<link>http://blog.ubrio.us/code/github-theme-for-syntaxhighlighter-wordpress-plugin/</link>
		<comments>http://blog.ubrio.us/code/github-theme-for-syntaxhighlighter-wordpress-plugin/#comments</comments>
		<pubDate>Fri, 17 Jul 2009 01:20:49 +0000</pubDate>
		<dc:creator>Rob Hurring</dc:creator>
				<category><![CDATA[Because I'll Forget]]></category>
		<category><![CDATA[Code]]></category>
		<category><![CDATA[Wordpress]]></category>

		<guid isPermaLink="false">http://blog.ubrio.us/?p=187</guid>
		<description><![CDATA[I did a very stupid thing. I automatically updated my syntaxhighlighter plugin (which is excellent by the way) through the wordpress admin panel. I also forgot that I had made a custom theme and added a few more matchers to the ruby brush, which were subsequently overwritten in the update. Bummer. So. Here is the [...]]]></description>
			<content:encoded><![CDATA[<p>I did a very stupid thing. I automatically updated my <a href='http://wordpress.org/extend/plugins/syntaxhighlighter/' onclick="pageTracker._trackPageview('/outgoing/wordpress.org/extend/plugins/syntaxhighlighter/?referer=');">syntaxhighlighter plugin</a> (which is excellent by the way) through the wordpress admin panel. I also forgot that I had made a custom theme and added a few more matchers to the ruby brush, which were subsequently overwritten in the update. Bummer.</p>
<p>So. Here is the theme, should I ever do that again, or if you aren&#8217;t a big fan of the default themes.</p>
<h3>Adding a new theme to SyntaxHighlighter</h3>
<p>If you are use version 2.2.0 of the plugin you can run this patch against it (<a href='http://file.ubrio.us/wordpress/add_github_theme.patch' onclick="pageTracker._trackPageview('/outgoing/file.ubrio.us/wordpress/add_github_theme.patch?referer=');">Add GitHub theme patch</a>). To use the patch just run:</p>
<p><code><span>$></span>patch syntaxhighlighter.php add_github_theme.patch</code></p>
<p>Or you can simply open it up and duplicate how the default themes are in there.</p>
<h3>Grab the GitHub SyntaxHighlighter  Theme</h3>
<p><a href='http://gist.github.com/148782' onclick="pageTracker._trackPageview('/outgoing/gist.github.com/148782?referer=');"> GitHub SyntaxHighlighter theme (Gist)</a> (It isn&#8217;t 100%, but it looks pretty nice for Ruby code)</p>
<h4>Heres how it looks</h4>
<div class='wp-caption alignleft'>
<img src='http://file.ubrio.us/wordpress/github_syntaxhighlighter_theme.png' /></p>
<p class='wp-caption-text'>GitHub Theme</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://blog.ubrio.us/code/github-theme-for-syntaxhighlighter-wordpress-plugin/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Rails theme support with Metal</title>
		<link>http://blog.ubrio.us/ruby/rails-theme-support-with-metal/</link>
		<comments>http://blog.ubrio.us/ruby/rails-theme-support-with-metal/#comments</comments>
		<pubDate>Wed, 11 Mar 2009 22:30:12 +0000</pubDate>
		<dc:creator>Rob Hurring</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[metal]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[rails 2.3]]></category>
		<category><![CDATA[themes]]></category>

		<guid isPermaLink="false">http://blog.ubrio.us/?p=167</guid>
		<description><![CDATA[Metal is neat. Themes are neat. Together they are nifty. So, in the spirit of the upcoming St. Patrick&#8217;s day holiday I decided to play around with metal to add theme support to my rails app. I like how WordPress supported themes by having meta data tucked into the stylesheet itself, and I also like [...]]]></description>
			<content:encoded><![CDATA[<p>Metal is neat. Themes are neat. Together they are nifty. So, in the spirit of the upcoming St. Patrick&#8217;s day holiday I decided to play around with metal to add theme support to my rails app. I like how WordPress supported themes by having meta data tucked into the stylesheet itself, and I also like query string (odd, I know) &#8212; so I figured I&#8217;d melt them together&#8230; in the spirit of the holiday and all.</p>
<p><a name='themes'></a></p>
<h3>The Theme Files</h3>
<p>First things first. We need to create a themes folder. I chose <tt>RAILS_ROOT/public/stylesheets/themes</tt> but anywhere public would work. Inside there I threw the following stylesheet:</p>
<p>I made the theme support a minimum of 3 meta fields:</p>
<ol>
<li><strong>theme</strong> &#8212; The name of the theme</li>
<li><strong>begin</strong> &#8212; What date to start using the theme</li>
<li><strong>end</strong> &#8212; What date to stop using the theme</li>
<li><strong>*enabled</strong> &#8212; Optional: If you want to enable this theme</li>
</ol>
<p>You can hack on this and include as many as you want &#8212; they follow the same basic format as URLs:</p>
<p><code><span>theme.css</span>theme=My Themes Name&#038;begin=March 17&#038;end=March 18</code></p>
<pre class="brush: css;">
/*
RAILS_ROOT/public/stylesheets/themes/st_patricks_day.css
{{
	theme=st patricks day
	&amp;begin=March 17
	&amp;end=March 18
	&amp;enabled=1
}}
*/

#header{
	background:#C2DDCA url(theme_images/shamrock.png) no-repeat 25px 20px;
	padding-left:50px;
	}
</pre>
<p><a name='metal'></a></p>
<h3>The Metal</h3>
<p>And, now into the neat part. Generate a rails metal file to handle theme switching on the fly, according to the current date.</p>
<p><code><span>$></span>./script/generate metal theme</code></p>
<p>Which should give you a nice <tt>app/metal/theme.rb</tt> file which you can play with.</p>
<p>I hacked together this code &#8212; and I&#8217;m not sure how stable it is, but should probably used in production with caution. It uses <tt>Rails.cache</tt> so make sure in your <tt>environment.rb</tt> file you have a cache store set.</p>
<pre class="brush: ruby;">
class Theme
  # this is where the theme index is stored
  CacheKey = 'themes'
  # this is what we will look for in the layout
  ThemeEnvKey = 'rails.theme'
  # this is the path to your themes folder
  ThemesPath = File.join(RAILS_ROOT, 'public', 'stylesheets', 'themes')

  def self.call(env)
    # Build our theme index
    themes = Rails.cache.fetch(CacheKey) do
      data = {}
      Dir[File.join(ThemesPath, '*.css')].each do |theme|
        # looks for {{ url_type_string_here }} comment meta data and parses
        # it out into a hash for the theme's file name
        #
        # within your theme file, you would have:
        #   {{theme=my name&amp;begin=DATE&amp;end=DATE}}
        # becomes
        #   {'theme.css' =&gt; {:theme =&gt; 'my mane', :begin =&gt; 'START_DATE', :end =&gt; 'FINISH_DATE'}}
        #
        # DATE is parsed so it can be any type of
        # date-ish string see ActiveSupport::TimeZone#parse
        begin
          data[File.basename(theme)] = \
            $1.split('&amp;').inject({}) do |h, v|
              s = v.split('=').map(&amp;:strip)
              h[s.first.to_sym] = s.last
              h
            end if File.read(theme) =~ /\{\{(.+)\}\}/m
        rescue Exception =&gt; e
          data[theme] = {:error =&gt; e.to_s}
        end
      end
      data
    end

    # Set the appropriate theme
    now = Time.zone.now.beginning_of_day
    themes.each_pair do |file, data|
      next if data.keys.include?(:enabled) and data[:enabled].to_i.zero?
      next unless data.keys.include?(:begin) and data.keys.include?(:end)

      if Time.zone.parse(data[:begin]) &lt;= now and Time.zone.parse(data[:end]) &gt; now
        env[ThemeEnvKey] = file
        break
      end
    end

    # pass
    Rails::Rack::Metal::NotFoundResponse
  end
end
</pre>
<p>What this basically does is:</p>
<ol>
<li>Check within the <tt>ThemesPath</tt> for any .css files</li>
<li>Reads them and parses out the metadata within the stylesheet</li>
<li>Caches that</li>
<li>Checks the date to see if any theme files should be turned on</li>
<li>Sets an <tt>env</tt> key to let the rest of Rails know we want a theme</li>
</ol>
<p><a name='layout'></a></p>
<h3>The Rails Layout</h3>
<p>Well, now Metal has set our <tt>env['rails.theme']</tt> key so we know a theme is in order it is time to put that theme to use.</p>
<div class='tip'>
Some DRYing is in order to make sure the metal and layout share the same <tt>env</tt> keys and paths, but this should get your basic themes goin.
</div>
<pre class="brush: ruby;">
# your applications main layout file (app/views/layouts/application.html.erb?)
# I put this after the normal stylesheet call, so our theme can override what we want instead of the entire stylesheet

&lt;% if theme = request.env['rails.theme'] %&gt;
  &lt;%= stylesheet_link_tag &quot;themes/#{theme}&quot;, :media =&gt; :all %&gt;
&lt;% end %&gt;
</pre>
<p>Once all these steps are combined, and March 17th hits, we should now have a stylish header image that shows the shamrock.png! I can almost hear the users clinging glasses <img src='http://blog.ubrio.us/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<div id='tip'><a href='http://gist.github.com/79871' onclick="pageTracker._trackPageview('/outgoing/gist.github.com/79871?referer=');">View as Gist</a></div>
]]></content:encoded>
			<wfw:commentRss>http://blog.ubrio.us/ruby/rails-theme-support-with-metal/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<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 [...]]]></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 [...]]]></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 [...]]]></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 &#8216;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>6</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>
	</channel>
</rss>

