辛纳屈 "hello world" 示例如何工作?

4
“get”方法定义在哪里?如何在没有对象的情况下调用它?
require 'sinatra'

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

首页的http://www.sinatrarb.com/上的示例。

1
这可能会有所帮助:https://dev59.com/zVnUa4cB1Zd3GeqPWwlX - 还有这个:https://dev59.com/b3NA5IYBdhLWcg3wjOlS 此外,您应该注意到 get 被定义为 private,因此要查看它,您需要在 get 调用之前执行类似于 p self.private_methods 的操作 - 然后当您运行 ruby hi.rb 时,您将看到定义的输出。 - Neil Slater
1个回答

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的工作原理有基本的了解。这比在此处回答的内容更多,也更重要。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接