Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call erb within an external class in sinatra

Tags:

ruby

erb

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?

like image 371
obaqueiro Avatar asked Nov 01 '22 06:11

obaqueiro


1 Answers

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
like image 124
matt Avatar answered Nov 12 '22 21:11

matt