Search code examples
rubysinatra

Why is "url_for" undefined in my application?


I'm trying to use the url_for extension so my app can accurately find my static assets (tried the static assets extension as well, but it also complained of this same problem).

The problem is this:

undefined method `url_for' for Sinatra::Raffler:Class (NoMethodError)

Now, I've got the required modules listed, as per the url_for README:

require 'rubygems'
require 'sinatra/base'
require 'data_mapper'
require 'lib/authorization'
require 'pony'
gem 'emk-sinatra-url-for'
require 'sinatra/url_for' 

But I'm still getting the NoMethodError when I try to call url_for

I have tried a couple of different things in regards to helpers. First, I have a helpers block for an authorization extension:

helpers do
    include Sinatra::Authorization
end

So, I thought I could include the url_for helper in there:

helpers do
    include Sinatra::Authorization
    include Sinatra::UrlForHelper
end

But that didn't resolve the issue, so I just added the line:

 helpers Sinatra::UrlForHelper

after that initial helpers do block, but still no resolution.


Solution

  • If you are subclassing Sinatra::Base, you need to include the helpers explicitly:

    class Foobar < Sinatra::Base
      helpers Sinatra::UrlForHelper
    end