2013-10-05 98 views
4

定義'get'方法在哪裏?它是如何被稱爲沒有對象?sinatra hello world示例如何工作?

require 'sinatra' 

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

http://www.sinatrarb.com/爲首頁的示例。

+1

這可能有所幫助:http://stackoverflow.com/questions/6624136/how-does-sinatra-define-and-invoke-the-get-method - 也是這樣的:http://stackoverflow.com/questions/ 917811 /另外你應該注意到'get'被定義爲'private',所以爲了看到它,你需要在'get'調用之前做'p self.private_methods'這樣的事情 - 那麼當你運行'ruby hi.rb'時,你會看到什麼是定義的輸出 –

回答

4

你不是打電話給「沒有對象」的任何東西,而是在Object上調用require 'sinatra',如果它可用於加載,這會給你提供方法get等。

其中get定義在Sinatra gem,lib文件夾中,名爲base.rb的文件中,並且此代碼大概在您的計算機上。

# 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 

爲了理解這裏發生了什麼,您需要對Ruby的工作原理有一個基本的瞭解。這比在這裏的答案中可以或應該回答的要多一點。