How does Sinatra define and call the get method?

I am very interested in how this works.

after the query "Sinatra"

then I can call get () on the top level area.

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

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

to know the class <self opens the class definition of a single object self and adds get () inside, so it starts to make sense.

But the only thing that remains, I can’t understand, is in the Sinstra module, how could one call () to be called without using the Sinatra :: resolution operation or something like that?

+6
source share
2 answers

It is laid out in several places, but if you look in lib/sinatra/main.rb , you can see this line below: include Sinatra::Delegator

If we move on to lib/sinatra/base.rb , we will see this piece of code approximately as 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 

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

 require "sinatra" get "foo" do "Hello World" end 

Sinatra will ultimately invoke the get method on Sinatra::Base due to previously installed delegation.

+9
source

I did not look at the source of Sinatra, but its essence should be something like

 >> module Test .. extend self .. class << self .. def get; "hi";end .. end .. end #=> nil >> include Test #=> Object >> get #=> "hi" 
0
source

Source: https://habr.com/ru/post/892317/


All Articles