Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call Sinatra erb from another class

Tags:

ruby

sinatra

I need to render a Sinatra erb template inside a class in my controller. I'm having issues calling this though. I've looked in the Sinatra rdocs and have come up with this:

Sinatra::Templates.erb :template_to_render

When I do this, I get the following error:

undefined method `erb' for Sinatra::Templates:Module

Is there a way to call this from another class?

like image 501
Eugene Avatar asked Mar 08 '10 14:03

Eugene


1 Answers

To imitate rendering behavior of Sinatra controller in some other class (not controller) you can create module like this:

module ErbRender

  include Sinatra::Templates
  include Sinatra::Helpers
  include Sinatra::ContentFor

  def settings
    @settings ||= begin
      settings = Sinatra::Application.settings
      settings.root = "#{ROOT}/app"
      settings
    end
  end

  def template_cache
    @template_cache ||= Tilt::Cache.new
  end

end

Here you may need to tune settings.root

Usage example:

class ArticleIndexingPostBody

  include ErbRender

  def get_body
    erb :'amp/articles/show', layout: :'amp/layout'
  end

end

This will properly render templates with layouts including content_for

like image 118
Daniel Garmoshka Avatar answered Sep 19 '22 02:09

Daniel Garmoshka