Tag Archives: image_tag

Small post, just to document a funny bit of code that I needed. Thanks to this blog post I got a start on making use of the Rails tag helpers from inside a controller. I needed to do this because I wanted to change an ActiveScaffold link label to be an image, and in order to do that I had to create the image tag in the controller in order to set the link label. Kind of annoying, but I was curious if it would work.

The basic trick is shown in the above-linked blog post, which is to create a “mini-helper” class inside ApplicationController, and sort of “link” to it via a help method. So I added to my ApplicationController:

  def self.tag_helper

  class TagHelper
    include Singleton
    include ActionView::Helpers::TagHelper
    include ActionView::Helpers::AssetTagHelper

Now I have a method available to my controllers called tag_helper, which uses a Singleton instance of TagHelper, which in turn includes the helpers. This requires including Singleton, in order to have one instance of the helper, and then the ActionView helpers. TagHelper is needed for AssetTagHelper to work, unfortunately.

So now in my controller that extends ApplicationController, I do the ActiveScaffold configuration and set the link labels. The idea here is that ActiveScaffold creates a list of items with “Edit”, “Delete”, and “Show” links. Instead of using those words as the links, I wanted to use some nice icons:

  active_scaffold :mything do |config|
    config.columns = [:name, :number, :active, :description] = tag_helper.image_tag('document_edit.png', :width => "30") = tag_helper.image_tag('document_delete.png', :width => "30") = tag_helper.image_tag('document.png', :width => "30")
    list.sorting = {:name => 'ASC'}

I configure which columns to display, and the sorting order, and I set the labels for the “update”, “delete”, and “show” links. I use the tag_helper() method to get access to the image_tag() method, which then does its thing and returns the properly-formed tag.

Nothing magic, but it took a little while looking at the ActiveScaffold code to decipher the not-quite-right docs for setting the labels, and then some more time to find a nice way to use the tag helper so I didn’t have to hard-code the tags. Someone else might find it useful, so here it is.