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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With