Question

I have this ApplicationController:

class ApplicationController < ActionController::Base
  before_filter :class_breadcrumb
end

I require every controller to define its own class_breadcrumb() method. And I'd like to show a message, without raising an exception, if that method doesn't exist. Finally, I want every other exception to fallback to the standard xml 500 page.

I felt it would be pretty simple to handle with this rescue_from block:

rescue_from "NameError" do |e|
  if e.to_s.include?('class_breadcrumb')
    flash.now["alert-danger"] = "You didn't provide a breadcrumb for #{request.fullpath}! Please send us a feedback including this message!"
    render params[:action]
  else
    # default behavior
    render :xml => e, :status => 500
  end
end

And it works! But when any other exception raises from within a controller... let's suppose I'm calling an undefined method like this:

<%= undefined_method_that_raise_an_exception %>

I see a blank page with this message:

Internal Server Error

no implicit conversion of NameError into String

What's wrong with my code?

Was it helpful?

Solution

Finally, I figured it out!

# rescue NoMethodError
def method_missing(method, *args, &block)
  if method == 'class_breadcrumb'
    flash.now["alert-danger"] = "You didn't provide a breadcrumb for #{request.fullpath}! Please send us a feedback including this message!"
    render params[:action]
  end
end

This is metaprogramming Ruby! That's why I've just convinced myself to buy this book and get the pain out: http://pragprog.com/book/ppmetr/metaprogramming-ruby

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top