obaqueiro obaqueiro - 2 months ago 14
Ruby Question

Call erb within an external class in sinatra

What's the correct way to call the erb function (which is available via Sinatra) if I have a helper class outside the Sinatra main application.

For example, I have in my_app.rb:

require 'sinatra'
require 'my_external_class.rb'
get '/' do
MyExternalClass.some_function(request)
end


Then I have a file called: my_external_class.rb

class MyExternalClass
def self.some_function request
erb :some_template
end
end


When running Sinatra and executing a get request, I get a undefined method `erb' for MyExternalClass. I assume I am missing either some require, or maybe I need to pass the Sinatra object to the class (but I don't know how to achieve that).

How could I achieve something like that?

Answer

You can achieve this by creating a helpers module for your methods:

# module instead of a class
module MyHelpersModule
  # no need for 'self'
  def some_function(request)
    erb :some_template
  end
end

Then in your main app file call helpers MyHelpersModule. This will make all the methods in MyHelpersModule available in your application and also, since they are executed in the same context, the existing Sinatra methods (like erb) will be available to your helpers.

require 'sinatra'
require './my_helpers_module'

helpers MyHelpersModule

get '/' do
   some_function(request)
end