sinatra分析

原文:https://docs.google.com/document/pub?id=1fkYc_N7i8Q2VSDliq6v8eFlWsnQyccrgxoH4oZf6lY0

1.sinatra简介

Sinatra is a DSL for quickly creating web applications in Ruby with minimal。

Fewer classes, less inheritance

controller object mapping & routes vs. URLs---Dont's fear the URLs

Exposed Simplicity instead of hidden complexity

Small things, loosely joined, written fast

2.sinatra分析

2.1.Rack机制

sinatra作为一个web框架,是基于rack规范的。rack规范和Java的servlet规范有点类似,Rack中间件和filter机制有些类似,都是能够拦截request/response做一些事情。所谓的rack兼容的中间件无非是一个可以执行 call(env) 的对象,详细关于rack的内容可以参考rack官网,还有这个rack入门文档也很好。

在源码中可以看到,sinatra的Request和Response都是基于rack扩展的,并对Rack::Request和Rack::Response分别做了一些调整。

sinatra是通过Application.run!来启动服务器的

     def run!(options={})

        set options

        handler      = detect_rack_handler

        handler_name = handler.name.gsub(/.*::/, '')

        puts "== Sinatra/#{Sinatra::VERSION} has taken the stage " +

          "on #{port} for #{environment} with backup from #{handler_name}" unless handler_name =~/cgi/i

        handler.run self, :Host => bind, :Port => port do |server|

          trap(:INT) do

            ## Use thins' hard #stop! if available, otherwise just #stop

            server.respond_to?(:stop!) ? server.stop! : server.stop

            puts "\n== Sinatra has ended his set (crowd applauds)" unless handler_name =~/cgi/i

          end

          set :running, true

        end

      rescue Errno::EADDRINUSE => e

        puts "== Someone is already performing on port #{port}!"

      end其中detect_rack_handler是通过 Rack::Handler.get来检测rack处理器的,默认的server有thin/mongrel/webrick,绑定的地址是 0.0.0.0,端口是4567

module Sinatra

        class Base

            set :server, %w[thin mongrel webrick]

            set :bind, '0.0.0.0'

            set :port, 4567

    end

end

注意到handler.run self, :Host => bind, :Port => port do |server|,这个self指的是Sinatra::Base,根据rack规范,最终的请求的入口就是 Sinatra::Base.call(env)方法

      def prototype

        @prototype ||= new

      end

      # Create a new instance of the class fronted by its middleware

      # pipeline. The object is guaranteed to respond to #call but may not be

      # an instance of the class new was called on.

      def new(*args, &bk)

        builder = Rack::Builder.new

        builder.use Rack::Session::Cookie if sessions?

        builder.use Rack::CommonLogger    if logging?

        builder.use Rack::MethodOverride  if method_override?

        builder.use ShowExceptions        if show_exceptions?

        middleware.each { |c,a,b| builder.use(c, *a, &b) }

        builder.run super

        builder.to_app

      end

      def call(env)

        synchronize { prototype.call(env) }

      end

从call方法可以看到,是通过生成一个Sinatra::Base实例对象来运行的,最终会调用的是call(env) -> call!(env)

,接下去的工作就是等客户端发送请求过来就可以了。在生成这个实例对象@prototype的时候,直接引入rack中间件机制,同样,sinatra允许你使用use方法来增加新的中间件(use只是把中间件加入@middleware变量中去而已)。这样sinatra就已经启动起来了。

2.2.路由机制

sinatra的路由机制和rails不大一样,sinatra是在controller里边用get/post path这样来指定的。而rails是把controller和map分开处理,通过map来找到对应的controller和action。rails当初这么搞主要是为了兼容controller和路由不匹配的情况,个人觉得sinatra的写法是非常直观的,也非常的灵活。

delegate :get, :put, :post, :delete, :head, :template, :layout,

             :before, :after, :error, :not_found, :configure, :set, :mime_type,

             :enable, :disable, :use, :development?, :test?, :production?,

             :helpers, :settings看main.rb可以看到include Sinatra::Delegator,可以把get/post等众多方法代理给Sinatra::Application去执行,在后面使用get '/' do xxx end的时候其实会调用Sinatra::Application(即Sinatra::Base)的get方法。

  require 'rubygems'

  require 'sinatra'

  get '/' do

    'Hello world!'

  end例如这样一个简单的web应用就可以响应'/'的请求路径,那么Sinatra::Base是怎么识别到这个路由的呢?我们继续来看看上面的get方法做了什么事情,可以看到最终是调用route方法的(同时,从代码可以看到sinatra支持get/post/put/post/delete/head几种method的请求)。按照我们的大概思路,在看到某个请求方法的时候,sinatra会把{请求类型_路径 => 代码块}放到一个专门放路由的地方上去,然后在每一次请求调用call(env)的时候,根据“请求类型_路径”来获得需要执行的代码块。好,继续看看route的代码是怎么实现的?

      def route(verb, path, options={}, &block)

        # Because of self.options.host

        host_name(options.delete(:bind)) if options.key?(:host)

        options.each {|option, args| send(option, *args)}

        pattern, keys = compile(path)

        conditions, @conditions = @conditions, []

       define_method "#{verb} #{path}", &block

        unbound_method = instance_method("#{verb} #{path}")

        block =

          if block.arity != 0

            proc { unbound_method.bind(self).call(*@block_params) }

          else

            proc { unbound_method.bind(self).call }

          end

        invoke_hook(:route_added, verb, path, block)

        (@routes[verb] ||= []).

          push([pattern, keys, conditions, block]).last

      end这个代码处理的事情比较多,我们来仔细分析分析,前面两句代码是用来记录能够处理的请求的约束(例如特定的host_name,user_agent),然后compile(path)的工作是把path换成一个正则表达式(这样通过match就可以获得匹配的组),还有提取keys(例如*的就变成splat,:name就变成name)。重要的是把get '/' do xxx end动态生成一个"#{verb} #{path}"的方法并最终封装成一个带有上下文状态的proc对象,最终是把[pattern, keys, conditions, block]加入@routes[verb]里边去。而call(env)能够处理请求就得靠这个@routes来实现。

先来看看call(env) -> call!(env),最重要的部分是invoke { dispatch! },可以看到dispatch!的整个流程是

判断并处理static文件 -> before_filter! -> route! -> after_filter!,主要的处理过程是route!方法

    def route!(base=self.class, pass_block=nil)

      if routes = base.routes[@request.request_method]

        original_params = @params

        path            = unescape(@request.path_info)

        routes.each do |pattern, keys, conditions, block|

          if match = pattern.match(path)

            values = match.captures.to_a

            params =

              if keys.any?

                keys.zip(values).inject({}) do |hash,(k,v)|

                  if k == 'splat'

                    (hash[k] ||= []) << v

                  else

                    hash[k] = v

                  end

                  hash

                end

              elsif values.any?

                {'captures' => values}

              else

                {}

              end

            @params = original_params.merge(params)

            @block_params = values

            pass_block = catch(:pass) do

              conditions.each { |cond|

                throw :pass if instance_eval(&cond) == false }

              route_eval(&block)

            end

          end

        end

        @params = original_params

      end

首先sinatra先从@routes里边取得符合请求类型的[pattern, keys, conditions, block]列表,然后逐个扫描,通过pattern来match路径,如果符合的话,取得通配符,命名参数的值并封装到params去(得益于compile(path)的工作)。接下去判断conditions是否符合,如果都符合,则执行业务,即block。整个流程处理完之后,把params恢复为原本的状态。

2.3.拦截器

在上面已经提到,sinatra的拦截器是通过before_filter!和after_filter!来执行的,如下所示:

    def before_filter!(base=self.class)

      before_filter!(base.superclass) if base.superclass.respond_to?(:before_filters)

      base.before_filters.each { |block| instance_eval(&block) }

    end配置过滤器也非常简单,定义一个前置过滤器,例如

  before do

    @note = 'Hi!'

    request.path_info = '/foo/bar/baz'

  endsinatra通过Sinatra::Base的before把block加入到@before_filters中去,这个应该很容易明白的。不过,这个拦截器功能比起rails那个显得简陋了,毕竟不能直接针对某些路径进行拦截处理。

2.4.模板渲染

sinatra通过Tilt实现多模板的渲染机制,生成页面的过程是在业务代码块那里注明的,例如

  require 'erb'

  get '/' do

    erb :index

  endsinatra的模板方法是在Sinatra::Templates模块里边定义的,能够支持erb,erubis,haml,sass,less,builder,具体的实现如下:

    def render(engine, data, options={}, locals={}, &block)

      # merge app-level options

      options = settings.send(engine).merge(options) if settings.respond_to?(engine)

      # extract generic options

      locals = options.delete(:locals) || locals || {}

      views = options.delete(:views) || settings.views || "./views"

      layout = options.delete(:layout)

      layout = :layout if layout.nil? || layout == true

      # compile and render template

      template = compile_template(engine, data, options, views)

      output = template.render(self, locals, &block)

      # render layout

      if layout

        begin

          options = options.merge(:views => views, :layout => false)

          output = render(engine, layout, options, locals) { output }

        rescue Errno::ENOENT

        end

      end

      output

    end具体的流程是先找到template engine,通过template的render方法渲染子页面,然后在把子页面的内容作为一个block参数放到渲染layout的render方法上去,这样在父页面里边的yield就会被子页面的内容所取代,从而实现整体页面的渲染。

2.5.错误及状态处理

sinatra在这方面的处理,我觉得非常巧妙,还认识了一些从来没用过的api。几个重要的特性:

halt:

  halt 410

  halt 'this will be the body'

  halt 401, 'go away!'error:

  error do

    'Sorry there was a nasty error - ' + env['sinatra.error'].name

  end

  error MyCustomError do

    'So what happened was...' + request.env['sinatra.error'].message

  end

  error 400..510 do

    'Boom'

  end

error的实现很简单,只是把error code和block记录到@errors上去,而not_found其实就是404的error了。halt从代码实现上看,它是throw一个halt的异常。

这些处理方式在sinatra最终是怎么处理的呢?我们先回到dispatch!这个主方法,从源码中可以看到如果是静态页面,会抛出halt(line 173),到了route!方法的时候,如下

            pass_block = catch(:pass) do

              conditions.each { |cond|

                throw :pass if instance_eval(&cond) == false }

                route_eval(&block)

            end

catch(args,&block)这个方法是会忽视在遇到pass异常的时候忽略异常并跳出block的运行,所以conditions验证不通过的时候,就会转入下一个pattern验证,而在验证通过后到了route_eval(&block) 就会抛出halt从而跳出循环,表示已经匹配成功。抛出异常之后会在dispatch!通过rescue来处理。error_block!(*keys)就是用来处理error的,@errors根据error code来获取block,这样就可以输出自定义的错误页面了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值