Is that possible to call method that uses "content_tag" from controller in Rails 3?

Misha Moroshko picture Misha Moroshko · Jun 2, 2011 · Viewed 10.4k times · Source

In my Rails 3 application I use Ajax to get a formatted HTML:

$.get("/my/load_page?page=5", function(data) {
  alert(data);
});

class MyController < ApplicationController
  def load_page
    render :js => get_page(params[:page].to_i)
  end
end

get_page uses the content_tag method and should be available also in app/views/my/index.html.erb.

Since get_page uses many other methods, I encapsulated all the functionality in:

# lib/page_renderer.rb
module PageRenderer
  ...
  def get_page
    ...
  end
  ...
end

and included it like that:

# config/environment.rb
require 'page_renderer'

# app/controllers/my_controller.rb
class MyController < ApplicationController
  include PageRenderer
  helper_method :get_page
end

But, since the content_tag method isn't available in app/controllers/my_controller.rb, I got the following error:

undefined method `content_tag' for #<LoungeController:0x21486f0>

So, I tried to add:

module PageRenderer
  include ActionView::Helpers::TagHelper    
  ...
end

but then I got:

undefined method `output_buffer=' for #<LoungeController:0x21bded0>

What am I doing wrong ?

How would you solve this ?

Answer

Noz picture Noz · Dec 5, 2012

To answer the proposed question, ActionView::Context defines the output_buffer method, to resolve the error simply include the relevant module:

module PageRenderer
 include ActionView::Helpers::TagHelper
 include ActionView::Context    
 ...
end