小编Rub*_*ist的帖子

在Web上公开任何Ruby对象

有人可以解释下面的Ruby代码是如何工作的吗?(取自要点:675667)

require 'rubygems'
require 'rack'

class Object
  def webapp
    class << self
       define_method :call do |env|
         func, *attrs = env['PATH_INFO'].split('/').reject(&:empty?)
         [200, {}, [send(func, *attrs).to_s]]
       end
    end
    self
  end
end

Rack::Handler::Mongrel.run [].webapp, :Port => 9292
#                         ^^^^^^^^^^^
#                              |          (x)
#                         ROFLSCALE DB ---/
#
Run Code Online (Sandbox Code Playgroud)

如果我们运行它,我们可以通过Web访问它:

GET http://localhost:9292/push/1  -> 1
GET http://localhost:9292/push/2  -> 12
GET http://localhost:9292/push/3  -> 123
GET http://localhost:9292/to_a    -> 123
GET http://localhost:9292/pop     -> 3
GET http://localhost:9292/shift   -> 1
Run Code Online (Sandbox Code Playgroud)

当然,我们可以运行如下:

GET http://localhost:9292/instance_eval/exec("rm -rf /")
Run Code Online (Sandbox Code Playgroud)

无论如何......它是如何工作的?你能逐步指导我完成代码吗?

ruby

4
推荐指数
1
解决办法
962
查看次数

标签 统计

ruby ×1