Technical Pickles

Josh on Programming, Linux, and Other Technical Stuff

BDD with Shoulda talk from MountainWest RubyConf

I've been using Shoulda on a few projects recently, and have done a few posts on it as well.

Last week, I came across this talk by Tammer Saleh by way of GIANT ROBOTS SMASHING INTO OTHER GIANT ROBOTS .

Tammer is the author of Shoulda, and hearing him talk about it definitely gave me some insight into Shoulda and how to use it.

Tags
ruby bdd shoulda
Published
April 13, 2008 at 19:31

DRY Controllers and Helpers using Forwardable

I don't know about you, but I've found myself wanting the same methods available in both a controller and a view. In my case, I had an 'authorized?' method for determining if a user is logged in.

Initially, I had two implementations, one in ApplicationController, and a different one in ApplicationHelper. I was young, and naive.

After starting some BDD with test/spec and mocha, I ran into problems because they were different. It was past time to be more DRY.

So let's think about this. As it turns out, 'controller' is a method available to your views, so, if you have 'something' in your controller, you should be able to hit it in your view by going 'controller.something'. This would give you something like:

<% if controller.authorized? %>
  Aieeeeeeeeee
<% end %>

I don't really like how that reads though. If only I could get it to read like I originally had when there were two implementations

<% if authorized? %>
  Aieeeeeeeeee
<% end %>

I then remembered reading long ago that you Ruby has built in constructs for doing delegation. But alas, that was ages ago and my memory was blank. After racking my mind, jumping up and down, and praying the seach engine deities, I found it: Forwardable

My intent is to delegate authorized? to the controller. Here's what the ApplicationHelper ends up looking like:

module ApplicationHelper
  extend Forwardable
  def_delegator :controller, :authorized?

  ...
end

Simple and awesome. I can dig that.

Tags
rails dry authentication forwardable bdd
Published
September 13, 2007 at 09:13