Calvin Jones
Calvin Jones

Reputation: 367

uninitialized constant Ruby

I'm working on a ruby app that pinpoints your location given your ip address. I have run into a road block though. I've already searched on this site, but the solutions I've already found are too general.

Here's the error:

uninitialized constant Place::IpGeocoder (NameError)

And the code I'm developing:

require 'socket'
require 'geocoder'
require 'geokit'


class Place

  def get_location

  ip = UDPSocket.open {|s| s.connect("64.233.187.99", 1); s.addr.last}
  location = IpGeocoder.geocode(ip.to_s())
  end

end

me=Place.new
me.get_location

I already installed the gems. Do I need to create a instance of it or something like in java?

Upvotes: 2

Views: 8718

Answers (2)

snowe
snowe

Reputation: 1375

It's called namespacing. Essentially what you've done is tried to access the IpGeocoder constant that is located in your Place class. Except you didn't define a constant there. You have to tell ruby where to locate the IpGeocoder constant by giving it a direction. (Clarification: in ruby class names are constants)

The class and method are probably declared in the source code like this:

module Geokit
  module Geocoders
    class IpGeocoder
    def geocode(ip)
    end
  end
end

As you can see here, to reference the method in the IpGeocoder class, you need to tell your class so way to get to it. Arup has described that succinctly.

Upvotes: 2

Arup Rakshit
Arup Rakshit

Reputation: 118271

You need to do, as below as per the doc Geokit::Geocoders::IpGeocoder .

Geokit::Geocoders::IpGeocoder.geocode(ip.to_s())

The class IpGeocoder is defined inside the module Geokit::Geocoders. So to access the class you need to use full path to that class, which is Geokit::Geocoders::IpGeocoder, using scope resolution operator ::.

Upvotes: 6

Related Questions