Rails: Finding Who Called A Partial

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.)

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

  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.)

2 thoughts on Rails: Finding Who Called A Partial

Comments are closed.