views:

74

answers:

1

I want a method in app/controllers/application.rb that can prepend/append text to whatever template gets rendered. Of course I can't call render twice w/o getting a double render error, so is this possible?

I want to redirect after a delay using a meta refresh. Here's what I've got:

app/controllers/application_controller.rb:

def redirect_after_delay (url, delay)
  @redirect_delay = delay
  @redirect_url = url
  render
end

app/views/layouts/application.html.erb

<!DOCTYPE html>
<html lang="en">
  <head>
    <%= yield :refresh_tag %>
  </head>

  <body>
    <%= yield %>
  </body>
</html>

So then if I want to add a redirect-after-delay, I add the following to 1) my controller and 2) the action's view:
app/controllers/my_controller.rb

def my_action
  redirect_after_delay 'http://www.google.com', 3 if some_condition
end

app/views/my_controller/my_action.html.erb

<% content_for :refresh_tag do %>
  <meta http-equiv='refresh' content='<%=@redirect_delay%>;url=<%=@redirect_url%>'>
<% end %>
<h1>Please wait while you are redirected...</h1>

Since the content_for block never changes, is it possible to do this in some generic way so that I don't have to put <%= yield :refresh_tag %> in each template? (e.g. could redirect_after_delay add it into whatever template is going to be rendered?)

A: 

One idea is to use an after_filter in application_controller.rb to add the meta refresh tag if appropriate e.g.

def after_filter
  if @redirect_url and @refresh_delay
    # update controller.response.body to add meta refresh tag
  end
end

I'm not sure that this would be as efficient as using yield :refresh_tag as you would have to parse the HTML to insert the meta tag after the head tag but it is a possible approach to investigate.

Another idea would be to just put your header HTML in a partial that you then include in your other pages. e.g.

Header partial:

<!DOCTYPE html>
<html lang="en">
  <head>
    <%= yield :refresh_tag %>
  </head>

Footer partial:

</html>
mikej
yeah i think i may be trying to make it too complicated, i will probably put something in the layout. thanks for your input!
aaronstacy