Archive for the ‘Uncategorized’ Category

How to Put Rewrite Rules in Your Ruby Code, Not Your Web Server

November 4, 2009

Need to put some URL rewrite rules in your Rails app? Not too crazy about writing Apache mod_rewrite rules? Prefer writing Ruby code?

Refraction to the rescue.

Refraction is a new Rails plugin from Josh Susser and Pivotal Labs that helps you easily implement URL rewrites in Ruby, rather than writing the rules in web-server-specific lingo. Your code gets called by Rack, although you don’t need to know anything about Rack to write rewrite rules.

Here’s an example. Let’s say you want to duplicate Twitter’s /@username routes (did you know Twitter supports URLs like that?) but have found as I did that routes.rb doesn’t seem to work with a “@:username” rule. Instead, create a RESTful UsersController and then put this in your refraction_rules.rb file:

Refraction.configure do |req|
  # rewrite /@username as /users/username
  if req.path =~ %r{/@(.+)}
    req.rewrite! :path => "/users/#{$1}"
  end
end

The notes in the blog post (see link above) mention that there is already a Rack rewrite plugin called Rack::Rewrite but “Rack::Rewrite only really gives you access to the request URI, whereas Refraction appears to give the entire request object… that can be much more useful for determining where to send someone.”

Define Your Own Custom Service Token for OAuth

October 8, 2009

For anyone who consumes OAuth APIs with the excellent oauth-plugin gem: I’ve just submitted a patch so you can now create your own custom “service token” in your models folder.

See the “Creating your own wrapper tokens” section of the tutorial link above to see what I’m talking about. It didn’t work before but it does now. Or will, as soon as it gets pulled back into the source. Until then you can get it here. After it’s pulled back in I’ll probably delete my fork.

Update: my change was pulled back into the master.

Intuit Community makes Business Week

July 21, 2009

Thanks to tjhanley for alerting me to this while I was on vacation: Business Week has written a short article about Intuit Community, the product I worked on last year and early this year, which is an in-product community where users can help each other. In addition to helping users it has apparently improved QuickBooks sales and reduced product support costs.

to_json => as_json?

July 20, 2009

The Javafication of Ruby on Rails

May 21, 2009

As you know, one of the nice things about using Ruby on Rails is the emphasis on code simplicity and readability. A month ago in “This Week in Edge Rails,” Mike Gunderloy posted something that makes me a little concerned—it feels like one small step toward the Javafication (a.k.a. complexification) of Ruby on Rails.

The change is called “Pluggable JSON Backends” and it was implemented by Rick Olson, a.k.a. Technoweenie. (I have the utmost respect for Technoweenie. I’ve used his code before and it’s wonderful stuff—it’s clean, it’s simple, and it works.)

Instead of this:

my_model.to_json

we are now encouraged to do this:

ActiveSupport::json.encode(my_model)

I Like Stuff that’s Simple

It’s a little thing and I don’t want to blow it out of proportion, but this is a pattern I would like to see the community avoid. Once people see this style of coding they start to copy it.

I think I understand the motivation behind the change, but I believe the new style of coding is harder to read and write. It reminds me of all the years I wrote C++ code and wished I could just extend a class outside its original definition. Ruby can do that and I love the fact that Rails isn’t shy about taking advantage of this capability to make programmers’ lives easier and code simpler.

It may be too late to have this debate when it comes to JSON. Maybe this was the only way to meet the requirements Technoweenie had. I don’t know. And I understand sometimes it’s necessary to do something a little ugly to achieve a goal that’s more important than simplicity or readability. But I am writing today to encourage the Rails core committers, and the rest of us in the Rails community, to please avoid this pattern when possible. If you are considering writing a method that looks like this:

ClassOrModule::namespacey_function.method_name(obj)

please pause and consider whether the users of your API would find it easier if you instead made it look like this:

obj.method_name

Thanks!

Listen to my interview on the Ruby on Rails Podcast

April 15, 2009

On Friday, Geoffrey Grosenbach interviewed Tom Hanley and me for the Ruby on Rails Podcast. Woo hoo!

Add Optional SEO-Friendliness to link_to_remote

April 2, 2009

link_to_remote_with_seo adds optional SEO-friendly goodness to the Rails link_to_remote function.  I wrote it for cases where I would have used link_to_remote in my Rails app but I wanted GoogleBot and other search engines to be able to follow the links.  In addition to setting onclick like the normal link_to_remote, it also sets html_options[:href] to the SAME URL that you pass in to options[:url]. (It only does this if you pass :seo => true and you do not explicitly set the href.)

See the big honking warning at the bottom for an explanation of why this plugin doesn’t just override the behavior of link_to_remote.

I Like Stuff that’s SEO-Friendly

The following example shows a “Next” link in paginated output.  Clicking the link in a browser results in an AJAX call (using the POST method) that retrieves just the “page” partial and inserts it into the “results” div on the page with a highlight visual effect.  When a search engine sees the link, however, it will send a GET request to the same URL, and the entire page (not just the partial) will be sent in the response.

Putting this in the view (home/index.html.erb):

<div id="results">
  <%= render :partial => "page" -%></div>
<%= link_to_seo_remote "Next",
  { :update => "#results",
    :url => { :action => "next_page" },
    :complete => visual_effect(:highlight, "#results") } %>

Produces (pay attention to the href attrbute):

<div id="results">
  <!-- first page of results shown here --></div>
<a href="/home/next_page"
  onclick="new Ajax.Updater('#results', '/home/next_page',
  {asynchronous:true, evalScripts:true,
  onComplete:function(request){new Effect.Highlight(&quot;#results&quot;,{});}}); return false;">
  Next
</a>

In  the controller (home.rb), render just the partial if called in an XHR (AJAX) request:

def next_page
  if request.xhr?
    render :partial => "page"
  else
    # Render the entire page, including the "results" section.
    render :action => "index"
  end
end

WARNING ABOUT INCORRECT USE OF THIS FUNCTION

Sorry but I have to yell for emphasis here.

When Google crawls your site it will follow all links on a page in advance, even before the user clicks on them.  Adding :confirm => “Are you sure?” WILL NOT HELP because it generates JavaScript that Google doesn’t execute.  So when you use link_to_seo_remote, DO NOT ALLOW destructive links to be placed in the href attribute.  Instead, override html_options[:href] to link to an intermediate page with “Are you sure?” and a BUTTON (not a link.  The crawler will not click the link, so the data will not be deleted.

See Using Rails AJAX Helpers to Create Safe State-Changing Links and search the page for “request.post?” for an explanation and some sample code.

Does it Have Tests?

Why, yes. I’d like to thank the Rails Community for not tolerating code with no tests. It was soooo tempting just to release this without writing automated tests but the peer pressure got to me.

And I’ll also like to thank Cake for awesome music.

To get the code

ruby script/plugin install http://github.com/BMorearty/link_to_remote_with_seo.git

Obfuscated ActionScript

April 1, 2009

My brother Mike, a developer on the Flex team at Adobe, wrote a pretty impressive bit of Obfuscated ActionScript on his blog.

Check it out. See if you can figure out what the program does before you follow his link to the answer.

(This snippet is just a taste of it.)

getset

hello, world

April 13, 2008

I am Brian Morearty. Welcome to my blog.

I’m a software engineer living with my wife and three kids in the San Francisco Bay Area.

I plan to blog about stuff like software development, things that strike me as funny, etc. The technology that currently has my interest is Ruby on Rails and Flex but that may change over time. For most of my career in software I’ve been working on Windows, and I’m also a fan of most Microsoft developer technology (WPF, ASP.NET, and so on.)