Search code examples
rubysinatra

How to get request url in ruby Sinatra class context?


In Sinatra you have the possibility to get the request full path by using the following lines:

get '/hello-world' do
  request.path_info   # => '/hello-world'
  request.fullpath    # => '/hello-world?foo=bar'
  request.url         # => 'http://example.com/hello-world?foo=bar'
end

I have several classes I use in my app. In this one particular class I like to compare the request.path_info to a string.

class foo
  def build_menu
    if request.path_info == "/hello-world"
      highlight_menu_entry
    end
  end
end

But the request-Object is not known in this class context and an error is thrown. I though this is a SUPER-GLOBAL like in PHP $_POST or $_GET, if there is some in Ruby/Sinatra.

So how can I check the request.path in a class context?


Solution

  • Found the answer by my myself. I use a self defined global variable $PATHNAME which I can use in any context. Combined with the before do-preprocessor in my main app, I can fill an use the variable.

    before do
      $PATHNAME=request.path_info
    end
    
    class Foo
      def build_menu
        highlight_menu_entry if $PATHNAME == '/hello-world'
      end
    end