ChangingThePresent
The Few, The Proud, The Pradipta 416
My Resume
Web DOC PDF
RTF ODT TXT
powered by emurse

merb on github and merb filters

bryan / 04.Mar.2008

Well after joining Github recently to work on Merb I did a few things: submitted my first patch, got rejected, and learned a lot about git and merb. xD

Wycats from merb kindly pointed out that the “bug” I had discovered was actually a feature! Indeed it is. Let’s have a look.

(original Lighthouse ticket)

working_foo.rb


class WorkingFoo < Application
  def index
    redirect 'http://merbivore.com'
  end
end

failing_foo.rb


class FailingFoo < Application
  before :choke

  def choke
    redirect 'http://merbivore.com'
  end
end

So what happens? In retrospect my thoughts were clearly biased by Rails. This application would work in Rails. But that doesn’t mean it is necessarily a smart way to do things. In failing_foo.rb the application is kind of losing control; the filter redirects and the session is abruptly interrupted. The outcome is the same in that the user agent is eventually redirected where they need to go, but it’s not the best way of doing it.

Here is the Merb way

merby_foo.rb


class MerbyFoo < Application
  before :awesomeness

  def awesomeness
    throw :halt, redirect "http://merbivore.com" 
  end
end

I read about 75% of the Merb code over the weekend to write a patch, and what I came up with was almost the same as the above MerbyFoo (suggested by Wycats), but with a subtle difference. I placed my throw :halt in the redirect method of the Controller mixin with a check to see if it was being called in a filter. Tsk on me. Wycats and the merb way is better, and now I understand it. You would normally expect the before filter that calls redirect to “halt” the before filters, but perhaps not always.

Merbs filters (in abstract_controller.rb) are flexible. The throw mechanism in filters allows passing a String, Proc, Symbol or nothing. Perhaps the redirect involves something complex:

before :check_em

def check_em
  throw :halt, :complex_stuff
end

def complex_stuff
 redirect "http://google.com" if user =~ /googler/
 redirect "http://yahoo.com" if user =~ /yahooligan/
end

Sorry, comments are closed for this article.

back to top

micro theme by seaofclouds, and powered with Mephisto Hosting by hostingrails.com