Topic: Refactor current controller check

In quite a few of my apps I find myself regularly having to check the current controller to display certain things conditionally.

Many times a widget will only be diplayed on 2 controller pages, or another one shows up on all except one., etc etc ad infinitum

I basically end up littering my view files with all these repetitive controller checks

<%= user_widget if @current_controller == 'users' || current_controller == 'widgets' %>

Ugh.. that makes me want to puke!

So I decided to refactor some of this to helper files

<%= user_widget if user_or_widgets %>
# helper

def user_or_widgets
  @current_controller == 'users' || @current_controller == 'widgets'


Its okay..but.i know I can do better

What I would much rather have is something like

<%= user_widget if controller_is('users','widgets') %>

I been racking my brain to figure out how to use a block or metaprogramming to build that method but the solution eludes me.

Last edited by pimpmaster (2007-08-11 14:32:05)

Re: Refactor current controller check

Here is my lousy attempt

def controller_is(*attrs)
    attrs.each { |c| @current_controller == c }.split( || )

It obviously doesnt work but I am having fun trying smile

Edit: I just realized that the OR operator is limited and I should probably try to work some %w[goodness] in there


Last edited by pimpmaster (2007-08-11 14:36:19)

Re: Refactor current controller check

def controller_is(*attrs){|attr| attr.to_s}.include?(@controller.controller_name)

Vincent Woo Ruby on Rails Blog

Re: Refactor current controller check


Glad to see I wasn't that far off smile