Sinatra如何定义和调用get方法? [英] How does Sinatra define and invoke the get method?

查看:64
本文介绍了Sinatra如何定义和调用get方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇这东西是如何工作的.

I'm pretty curious about how this thing works.

之后需要'sinatra'

after require 'sinatra'

然后我可以在顶级范围内调用get().

then I can invoke get() in the top level scope.

深入研究源代码之后,我发现了此get()结构

after digging into the source code, I found this get() structure

module Sinatra
 class << self
   def get
    ...
    end
  end
end

了解课程<< self打开了self对象的单例类定义,并在其中添加get(),因此它开始变得有意义.

know the class << self is open up the self object's singleton class definition and add get() inside, so it starts to make sense.

但是我唯一不知道的是它在模块Sinstra中,如何在不使用Sinatra ::解析操作之类的情况下调用get()?

But the only thing left I can't figure out is it's within module Sinstra, how could get() be invoked without using Sinatra:: resolution operation or something?

推荐答案

它分散在几个地方,但是如果您查看lib/sinatra/main.rb,则可以在底部看到此行: include Sinatra::Delegator

It is spread out in a few places, but if you look in lib/sinatra/main.rb, you can see this line at the bottom: include Sinatra::Delegator

如果进入lib/sinatra/base.rb,我们会看到大约1470的这段代码.

If we go into lib/sinatra/base.rb we see this chunk of code around like 1470.

  # Sinatra delegation mixin. Mixing this module into an object causes all
  # methods to be delegated to the Sinatra::Application class. Used primarily
  # at the top-level.
  module Delegator #:nodoc:
    def self.delegate(*methods)
      methods.each do |method_name|
        define_method(method_name) do |*args, &block|
          return super(*args, &block) if respond_to? method_name
          Delegator.target.send(method_name, *args, &block)
        end
        private method_name
      end
    end

    delegate :get, :patch, :put, :post, :delete, :head, :options, :template, :layout,
             :before, :after, :error, :not_found, :configure, :set, :mime_type,
             :enable, :disable, :use, :development?, :test?, :production?,
             :helpers, :settings
    class << self
      attr_accessor :target
    end

    self.target = Application
  end

这段代码按照注释的内容进行操作:如果包含注释,它将所有对委托方法列表的调用委托给Sinatra::Application类,该类是Sinatra::Base的子类,而get是该方法的所在.定义.当您编写这样的内容时:

This code does what the comment says: if it is included, it delegates all calls to the list of delegated methods to Sinatra::Application class, which is a subclass of Sinatra::Base, which is where the get method is defined. When you write something like this:

require "sinatra"

get "foo" do
  "Hello World"
end

由于先前设置的委托,Sinatra将最终在Sinatra::Base上调用get方法.

Sinatra will end up calling the get method on Sinatra::Base due to the delegation it set up earlier.

这篇关于Sinatra如何定义和调用get方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆