I'm having some trouble getting helpers to work with a modular Sinatra app. I have a master controller and a bunch of others inheriting from it. So /
maps to Root
, /auth
maps to Auth
, etc.
Main module:
require 'sinatra/base'
# Lots of other requires
# Helper
module Utils
def test
puts "Test helper"
return 'test'
end
end
# Main app
class Application < Sinatra::Base
helpers Utils
# Lots of config
end
"Controllers" inherit Application
, like:
class Root < Application
get '/' do
puts Utils # Exists
puts Utils.test # Breaks
# view() Defined directly in `Application`, runs slim
view :index
end
end
This results in:
NoMethodError at /
private method `test' called for Utils:Module
A bit stumped. Any help?
Using a helpers module makes all the methods in it directly available to the code in the routes, without needing to prefix it with the module name.
You can just do this:
get '/' do
puts test
# view() Defined directly in `Application`, runs slim
view :index
end
The reason you are getting private method `test' called for Utils:Module
rather than undefined method `test' for Utils:Module
is because there already is a test
method in Kernel, which is therefore available as a private method on all classes.