Generate Rails Pages from a Helper

In Rails, you sometimes need to to break the MVC pattern. In my case, I wanted to take a fully-generated page and extract a certain portion of it in a helper. In this way I was able to base a foreign-channel’s template on my application’s template.
The key to this black magic is ActionController::Integration:: Session.new. Note that in order to use this class you will need to put the following line in config/environment.rb.

   require "action_controller/integration"

Then from your helper function you can GET a page given a url. In the example below I want to extract the portion of the page between begin #{token} and end #{token}

module MyGrabberHelper
  def pull_from_site(token)
     url = url_for(:controller => "my_grabber", :action => "content")
     app = ActionController::Integration::Session.new
     app.get url
     body = app.response.body
     body =~ /<!-- begin #{token} -->(.*?)<!-- end #{token} -->/m
     $1
   end
 end

~

Share:
  • del.icio.us
  • Reddit
  • Technorati
  • Twitter
  • Facebook
  • Google Bookmarks
  • HackerNews
  • PDF
  • RSS
This entry was posted in programming. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.