Software As She’s Developed

Mahemoff’s Podcast/Blog - Web, Programming, Usabilty from the Author of ‘Ajax Design Patterns’ (AjaxPatterns.org)

Software As She’s Developed header image 2

Rails: Finding Who Called A Partial

August 16th, 2006 · 2 Comments

So you're coding a partial and you want to know which template has pulled it in. The magic word is "@first_render", which will give you something like "homepage/admin" for the homepage/admin.rhtml template. Trivial, I know, but I couldn't find any mention of it after much googling, so I decided to output self.inspect and was pleased to find that property. I have no idea how reliable it is, if it will survive to Rails 1.2 and beyond, etc, etc, caveat, disclaimer, etc. I do think developers could benefit if Rails explicitly supported the property ... just like knowing who called a function, there are always good reasons to do it, and the Ruby philosophy is to give developers the power to choose what's good for them.

I'm using the property in a tabbed navigation partial, to determine which is the current page. A classic example of where the temlpate property is useful, since the property is used in a generic way, not as part of some complex "if" loop (viz "if template is leftColumn, make the background pink" etc.)

RUBY:
  1. css_classes = ["templateA", "templateB", "templateC"].map {
  2.   |template| @first_render==template ? "on" : "off"
  3. }


HTML:
  1. <div class="nav">
  2.   <a class="<%= css_classes[0] %>" href="/controllerX/actionA">The A Thang</a>
  3.   <a class="<%= css_classes[1] %>" href="/controllerX/actionB">The B Thang</a>
  4.   <a class="<%= css_classes[2] %>" href="/controllerX/actionC">The C Thang</a>
  5. </div>


(It could be refactored to use some tag helpers and an associative array mapping actions to css classes.)

Categories: SoftwareDev

Tags:

2 responses so far ↓

  • 1 takiuchi // Aug 25, 2006 at 7:30 am

    You can also use controller.parent_controller to similar purpose.

  • 2 Anonymous // May 7, 2007 at 7:41 pm

    I’ve also found that @controller_id works well as well.

Leave a Comment