Search code examples
sinatrarackrails-geocoder

NameError: undefined local variable or method `request' for main:Object


I'm building a Sinatra app which will take a visitor's IP address and return the weather of that location. Following the Geocoder doc, it would seem that getting the IP is as simple as

city = request.location.city

Entering that into irb, however, just gives the NameError you see in the post title. Going what seems to me the logical route and attempting to create a new class upon which to use the request method results in another NameError - this time for the env hash taken by Rack::Request.new(env).

I can figure out how to build the thing on my own, but I'm stumped on this particular point, and assume that I am overlooking something not mentioned in the docs. What am I doing wrong that is causing request and env to remain undefined, and how do I go about correctly defining them?


Solution

  • It is as simple as that:

    require "sinatra"
    require "geocoder"
    
    get "/" do
        p request.location.city
        "works"
    end
    

    Your problem is that you trying to run it in irb where you haven't the context of a request which creates and populates your request object. To play with it I would recommend just to run sinatra. Or use something like racksh, tux which gives you a something like irb but with all the context needed.