4

Where is the 'get' method defined? And how is it called on no object?

require 'sinatra'

get '/hi' do
  "Hello World!"
end

The example from the http://www.sinatrarb.com/ homepage.

Neil Slater
  • 26,512
  • 6
  • 76
  • 94
Roman A. Taycher
  • 18,619
  • 19
  • 86
  • 141
  • 1
    This may help: http://stackoverflow.com/questions/6624136/how-does-sinatra-define-and-invoke-the-get-method - also this: http://stackoverflow.com/questions/917811/what-is-main-in-ruby in addition you should note that `get` is defined `private`, so to see it you need to do something like `p self.private_methods` just before the `get` call - then you will see what's defined output when you run `ruby hi.rb` – Neil Slater Oct 05 '13 at 10:56

1 Answers1

4

You are not calling anything on "no object" but calling require 'sinatra' on Object and this loads the library, if it is available to be loaded, which gives you the method get, among other things.

Where get is defined is in the Sinatra gem, in the lib folder, in a file called base.rb and this code is presumably on your computer.

# Defining a `GET` handler also automatically defines
# a `HEAD` handler.
def get(path, opts = {}, &block)
  conditions = @conditions.dup
  route('GET', path, opts, &block)

  @conditions = conditions
  route('HEAD', path, opts, &block)
end

In order to understand what is going on here, you need a fundamental understanding of how Ruby works. That is a bit more than what can or should be answered in an answer here.

vgoff
  • 10,980
  • 3
  • 38
  • 56