Friday, March 4, 2011

Current view file in Rails helper method

Is there some way to determine what file currently is being rendered by Rails (2.2) in a helper method. An example result would be "/sessions/new.html.erb" or something similar.

I am trying to write a helper function that does something based on the file name that is being rendered, so I need a reliable way to obtain this information. Is there an official way to get this information?

From stackoverflow
  • I now have this extremely ugly solution. Anybody a better idea?

    
    begin
      raise "Nasty hack"
    rescue 
      render = $@.detect { |bti| /\/app\/views\/(.+)\:\d+\:in \`_run_erb_/ =~ bti }
      return $1
    end
    
  • In Rails 2.2 you can use @template.template

  • Thanks, that did it!

    @template.template.relative_path will return the path of the file being rendered.

0 comments:

Post a Comment