Archive for the 'Ruby on Rails' Category

Ruby Timing Shortcut

Tuesday, June 10th, 2008 By: Daniel

Recently I was trying to optimize my code a little and needed a quick way to compare the speed of different code snippets. Of course Rails comes with the Benchmark module for doing just that. It is, however, in my opinion a bit clunky for quick tests. Look at all the typing it takes just to find the average speed of a snippet over 100 iterations:

Benchmark.bm do |x|
  x.report do
    100.times do
      (1...1000).to_a.sum
    end
  end
end

So I tossed this into my ~/.irbrc file:

class Integer
  def ti(&block)
    Benchmark.bm do |x|
      x.report do
        self.times do
          yield
        end
      end
    end
  end
end

And now I can “time it” like this:

>> 100.ti {(1...1000).to_a.sum}
      user     system      total        real
  0.540000   0.050000   0.590000 (  0.597664)
=> true

Much nicer!

Fragment caching with Radiant CMS

Tuesday, June 10th, 2008 By: wes

We’re in the process of converting our website to Radiant CMS, and one of the new things on the site is a “Blog Blurbs” section at the bottom of every page that lists our latest blog post. Our blog is in Wordpress, so I setup the RSS Reader extension in Radiant to fetch the posts. Everything worked great, except that page loading was noticeably slower. After the page gets cached everything is fine but this is included on every page so going through the site when there were not cached pages was really frustrating. I thought about modifying the RSS Reader extension to cache our blog blurbs, but I figured a more general approach would work better, so I came up with a fragment caching extension. We’re using it like this:

<r:cache name="rss_fragment" time="60">
  <r:feed:items url="[feed_url]" limit="1">
    <h3><r:feed:link /></h3>
    <p><r:feed:content max_length="300" no_html="true" /></p>
  </r:feed:items>
</r:cache>

The code is at github.

Highlighting Active Rows in Forms

Thursday, April 17th, 2008 By: Daniel

What can be done to make the ubiquitous form element a little more usable and appealing? That was a question we asked ourselves on a recent project and one of our answers was to highlight the active row. It’s easy to change the appearance of the active input element with the focus pseudo-class in css, but a quick Google search didn’t reveal an easy way to highlight the containing tr element and so I ended up rolling my own implementation. Read the rest of this entry »